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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.811   ! raeburn     4: # $Id: grades.pm,v 1.810 2025/01/18 22:04:36 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.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.752     raeburn    49: use Apache::lontexconvert();
1.796     raeburn    50: use Apache::loncourserespicker;
1.170     albertel   51: use String::Similarity;
1.760     raeburn    52: use HTML::Parser();
                     53: use File::MMagic;
1.359     www        54: use LONCAPA;
1.796     raeburn    55: use LONCAPA::ltiutils();
1.359     www        56: 
1.315     bowersj2   57: use POSIX qw(floor);
1.87      www        58: 
1.435     foxr       59: 
1.513     foxr       60: 
1.435     foxr       61: my %perm=();
1.674     raeburn    62: my %old_essays=();
1.447     foxr       63: 
1.513     foxr       64: #  These variables are used to recover from ssi errors
                     65: 
                     66: my $ssi_retries = 5;
                     67: my $ssi_error;
                     68: my $ssi_error_resource;
                     69: my $ssi_error_message;
1.798     raeburn    70: my $registered_cleanup;
1.513     foxr       71: 
                     72: sub ssi_with_retries {
                     73:     my ($resource, $retries, %form) = @_;
                     74:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     75:     if ($response->is_error) {
                     76: 	$ssi_error          = 1;
                     77: 	$ssi_error_resource = $resource;
                     78: 	$ssi_error_message  = $response->code . " " . $response->message;
                     79:     }
                     80: 
                     81:     return $content;
                     82: 
                     83: }
                     84: #
                     85: #  Prodcuces an ssi retry failure error message to the user:
                     86: #
                     87: 
                     88: sub ssi_print_error {
                     89:     my ($r) = @_;
1.516     raeburn    90:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     91:     $r->print('
                     92: <br />
                     93: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     94: <p>
                     95: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     96: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     97: '.&mt('Error:').' '.$ssi_error_message.'
                     98: </p>
                     99: <p>'.
                    100: &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 />'.
                    101: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                    102: '</p>');
                    103:     return;
1.513     foxr      104: }
                    105: 
1.44      ng        106: #
1.146     albertel  107: # --- Retrieve the parts from the metadata file.---
1.598     www       108: # Returns an array of everything that the resources stores away
                    109: #
                    110: 
1.44      ng        111: sub getpartlist {
1.582     raeburn   112:     my ($symb,$errorref) = @_;
1.439     albertel  113: 
                    114:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   115:     unless (ref($navmap)) {
                    116:         if (ref($errorref)) { 
                    117:             $$errorref = 'navmap';
                    118:             return;
                    119:         }
                    120:     }
1.439     albertel  121:     my $res      = $navmap->getBySymb($symb);
                    122:     my $partlist = $res->parts();
                    123:     my $url      = $res->src();
1.745     raeburn   124:     my $toolsymb;
                    125:     if ($url =~ /ext\.tool$/) {
                    126:         $toolsymb = $symb;
                    127:     }
                    128:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
1.439     albertel  129: 
1.146     albertel  130:     my @stores;
1.439     albertel  131:     foreach my $part (@{ $partlist }) {
1.146     albertel  132: 	foreach my $key (@metakeys) {
                    133: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    134: 	}
                    135:     }
                    136:     return @stores;
1.2       albertel  137: }
                    138: 
1.129     ng        139: #--- Format fullname, username:domain if different for display
                    140: #--- Use anywhere where the student names are listed
                    141: sub nameUserString {
                    142:     my ($type,$fullname,$uname,$udom) = @_;
                    143:     if ($type eq 'header') {
1.485     albertel  144: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        145:     } else {
1.398     albertel  146: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    147: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        148:     }
                    149: }
                    150: 
1.44      ng        151: #--- Get the partlist and the response type for a given problem. ---
1.773     raeburn   152: #--- Count responseIDs, essayresponse items, and dropbox items ---
1.623     www       153: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        154: sub response_type {
1.582     raeburn   155:     my ($symb,$response_error) = @_;
1.377     albertel  156: 
                    157:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   158:     unless (ref($navmap)) {
                    159:         if (ref($response_error)) {
                    160:             $$response_error = 1;
                    161:         }
                    162:         return;
                    163:     }
1.377     albertel  164:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   165:     unless (ref($res)) {
                    166:         $$response_error = 1;
                    167:         return;
                    168:     }
1.377     albertel  169:     my $partlist = $res->parts();
1.773     raeburn   170:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
1.392     albertel  171:     my %vPart = 
                    172: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  173:     my (%response_types,%handgrade);
                    174:     foreach my $part (@{ $partlist }) {
1.392     albertel  175: 	next if (%vPart && !exists($vPart{$part}));
                    176: 
1.377     albertel  177: 	my @types = $res->responseType($part);
                    178: 	my @ids = $res->responseIds($part);
                    179: 	for (my $i=0; $i < scalar(@ids); $i++) {
1.773     raeburn   180:             $numresp ++;
1.377     albertel  181: 	    $response_types{$part}{$ids[$i]} = $types[$i];
1.773     raeburn   182:             if ($types[$i] eq 'essay') {
                    183:                 $numessay ++;
                    184:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
                    185:                     $numdropbox ++;
                    186:                 }
                    187:             }
1.377     albertel  188: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    189: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    190: 				     '.handgrade',$symb);
1.41      ng        191: 	}
                    192:     }
1.773     raeburn   193:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
1.39      ng        194: }
                    195: 
1.375     albertel  196: sub flatten_responseType {
                    197:     my ($responseType) = @_;
                    198:     my @part_response_id =
                    199: 	map { 
                    200: 	    my $part = $_;
                    201: 	    map {
                    202: 		[$part,$_]
                    203: 		} sort(keys(%{ $responseType->{$part} }));
                    204: 	} sort(keys(%$responseType));
                    205:     return @part_response_id;
                    206: }
                    207: 
1.207     albertel  208: sub get_display_part {
1.324     albertel  209:     my ($partID,$symb)=@_;
1.207     albertel  210:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    211:     if (defined($display) and $display ne '') {
1.577     bisitz    212:         $display.= ' (<span class="LC_internal_info">'
                    213:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  214:     } else {
                    215: 	$display=$partID;
                    216:     }
                    217:     return $display;
                    218: }
1.269     raeburn   219: 
1.773     raeburn   220: #--- Show parts and response type
                    221: sub showResourceInfo {
                    222:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
                    223:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
                    224:         return '<br clear="all">';
                    225:     }
                    226:     my $coltitle = &mt('Problem Part Shown');
                    227:     if ($checkboxes) {
                    228:         $coltitle = &mt('Problem Part');
                    229:     } else {
                    230:         my $checkedparts = 0;
                    231:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                    232:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
                    233:                 $checkedparts ++;
                    234:             }
                    235:         }
                    236:         if ($checkedparts == scalar(@{$partlist})) {
                    237:             return '<br clear="all">';
                    238:         }
                    239:         if ($uploads) {
                    240:             $coltitle = &mt('Problem Part Selected');
                    241:         }
                    242:     }
                    243:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
                    244:     if ($checkboxes) {
                    245:         my $legend = &mt('Parts to display');
                    246:         if ($uploads) {
                    247:             $legend = &mt('Part(s) with dropbox');
                    248:         }
                    249:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
                    250:                    '<span class="LC_nobreak">'.
                    251:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
                    252:                    &mt('All parts').'</label>'.('&nbsp;'x2).
                    253:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
                    254:                    &mt('Selected parts').'</label></span>'.
                    255:                    '<div id="LC_partselector" style="display:none">';
                    256:     }
                    257:     $result .= &Apache::loncommon::start_data_table()
                    258:               .&Apache::loncommon::start_data_table_header_row();
                    259:     if ($checkboxes) {
                    260:         $result .= '<th>'.&mt('Display?').'</th>';
                    261:     }
                    262:     $result .= '<th>'.$coltitle.'</th>'
                    263:               .'<th>'.&mt('Res. ID').'</th>'
                    264:               .'<th>'.&mt('Type').'</th>'
                    265:               .&Apache::loncommon::end_data_table_header_row();
                    266:     my %partsseen;
                    267:     foreach my $partID (sort(keys(%$responseType))) {
                    268:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    269:             my $responsetype = $responseType->{$partID}->{$resID};
                    270:             if ($uploads) {
                    271:                 next unless ($responsetype eq 'essay');
                    272:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
                    273:             }
                    274:             my $display_part=&get_display_part($partID,$symb);
                    275:             if (exists($partsseen{$partID})) {
                    276:                 $result.=&Apache::loncommon::continue_data_table_row();
                    277:             } else {
                    278:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
                    279:                 $result.=&Apache::loncommon::start_data_table_row().
                    280:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
                    281:                 if ($checkboxes) {
                    282:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
                    283:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
                    284:                 } else {
                    285:                     $result.=$display_part.'</td>';
                    286:                 }
                    287:             }
                    288:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
                    289:                     .'<td>'.&mt($responsetype).'</td>'
                    290:                     .&Apache::loncommon::end_data_table_row();
                    291:         }
                    292:     }
                    293:     $result.=&Apache::loncommon::end_data_table();
                    294:     if ($checkboxes) {
                    295:         $result .= '</div></fieldset>';
                    296:     }
                    297:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
1.775     raeburn   298:     if (!keys(%partsseen)) {
                    299:         $result = '';
                    300:         if ($uploads) {
                    301:             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
                    302:                    '<p class="LC_info">'.
                    303:                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
                    304:                    '</p>';
                    305:         } else {
                    306:             return '<br clear="all" />';
                    307:         }
                    308:     }
1.773     raeburn   309:     return $result;
                    310: }
                    311: 
                    312: sub part_selector_js {
                    313:     my $js = <<"END";
                    314: function toggleParts(formname) {
                    315:     if (document.getElementById('LC_partselector')) {
                    316:         var index = '';
                    317:         if (document.forms.length) {
                    318:             for (var i=0; i<document.forms.length; i++) {
                    319:                 if (document.forms[i].name == formname) {
                    320:                     index = i;
                    321:                     break;
                    322:                 }
                    323:             }
                    324:         }
                    325:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
                    326:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
                    327:                 if (document.forms[index].elements['chooseparts'][i].checked) {
                    328:                    var val = document.forms[index].elements['chooseparts'][i].value;
                    329:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
                    330:                         document.getElementById('LC_partselector').style.display = 'block';
                    331:                     } else {
                    332:                         document.getElementById('LC_partselector').style.display = 'none';
                    333:                     }
                    334:                 }
                    335:             }
                    336:         }
                    337:     }
                    338: }
                    339: END
                    340:     return &Apache::lonhtmlcommon::scripttag($js);
                    341: }
                    342: 
1.434     albertel  343: sub reset_caches {
                    344:     &reset_analyze_cache();
                    345:     &reset_perm();
1.674     raeburn   346:     &reset_old_essays();
1.434     albertel  347: }
                    348: 
                    349: {
                    350:     my %analyze_cache;
1.557     raeburn   351:     my %analyze_cache_formkeys;
1.148     albertel  352: 
1.434     albertel  353:     sub reset_analyze_cache {
                    354: 	undef(%analyze_cache);
1.557     raeburn   355:         undef(%analyze_cache_formkeys);
1.434     albertel  356:     }
                    357: 
                    358:     sub get_analyze {
1.649     raeburn   359: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  360: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   361:         if ($type eq 'randomizetry') {
                    362:             if ($trial ne '') {
                    363:                 $key .= "\0".$trial;
                    364:             }
                    365:         }
1.557     raeburn   366: 	if (exists($analyze_cache{$key})) {
                    367:             my $getupdate = 0;
                    368:             if (ref($add_to_hash) eq 'HASH') {
                    369:                 foreach my $item (keys(%{$add_to_hash})) {
                    370:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    371:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    372:                             $getupdate = 1;
                    373:                             last;
                    374:                         }
                    375:                     } else {
                    376:                         $getupdate = 1;
                    377:                     }
                    378:                 }
                    379:             }
                    380:             if (!$getupdate) {
                    381:                 return $analyze_cache{$key};
                    382:             }
                    383:         }
1.434     albertel  384: 
                    385: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    386: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   387:         my %form = ('grade_target'      => 'analyze',
                    388:                     'grade_domain'      => $udom,
                    389:                     'grade_symb'        => $symb,
                    390:                     'grade_courseid'    =>  $env{'request.course.id'},
                    391:                     'grade_username'    => $uname,
                    392:                     'grade_noincrement' => $no_increment);
1.649     raeburn   393:         if ($bubbles_per_row ne '') {
                    394:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    395:         }
1.640     raeburn   396:         if ($type eq 'randomizetry') {
                    397:             $form{'grade_questiontype'} = $type;
                    398:             if ($rndseed ne '') {
                    399:                 $form{'grade_rndseed'} = $rndseed;
                    400:             }
                    401:         }
1.557     raeburn   402:         if (ref($add_to_hash)) {
                    403:             %form = (%form,%{$add_to_hash});
1.640     raeburn   404:         }
1.557     raeburn   405: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  406: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    407: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   408:         if (ref($add_to_hash) eq 'HASH') {
                    409:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    410:         } else {
                    411:             $analyze_cache_formkeys{$key} = {};
                    412:         }
1.434     albertel  413: 	return $analyze_cache{$key} = \%analyze;
                    414:     }
                    415: 
                    416:     sub get_order {
1.640     raeburn   417: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    418: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  419: 	return $analyze->{"$partid.$respid.shown"};
                    420:     }
                    421: 
                    422:     sub get_radiobutton_correct_foil {
1.640     raeburn   423: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    424: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    425:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   426:         if (ref($foils) eq 'ARRAY') {
                    427: 	    foreach my $foil (@{$foils}) {
                    428: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    429: 		    return $foil;
                    430: 	        }
1.434     albertel  431: 	    }
                    432: 	}
                    433:     }
1.554     raeburn   434: 
                    435:     sub scantron_partids_tograde {
1.741     raeburn   436:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   437:         my (%analysis,@parts);
                    438:         if (ref($resource)) {
                    439:             my $symb = $resource->symb();
1.557     raeburn   440:             my $add_to_form;
                    441:             if ($check_for_randomlist) {
                    442:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    443:             }
1.741     raeburn   444:             if ($scancode) {
                    445:                 if (ref($add_to_form) eq 'HASH') {
                    446:                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    447:                 } else {
                    448:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    449:                 }
                    450:             }
1.767     raeburn   451:             my $analyze =
1.649     raeburn   452:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    453:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   454:             if (ref($analyze) eq 'HASH') {
                    455:                 %analysis = %{$analyze};
                    456:             }
                    457:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    458:                 foreach my $part (@{$analysis{'parts'}}) {
                    459:                     my ($id,$respid) = split(/\./,$part);
                    460:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    461:                         push(@parts,$part);
                    462:                     }
                    463:                 }
                    464:             }
                    465:         }
                    466:         return (\%analysis,\@parts);
                    467:     }
                    468: 
1.148     albertel  469: }
1.434     albertel  470: 
1.118     ng        471: #--- Clean response type for display
1.335     albertel  472: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    473: #        response types only.
1.118     ng        474: sub cleanRecord {
1.336     albertel  475:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   476: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  477:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  478:     if ($response =~ /^(option|rank)$/) {
                    479: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     480:         my @answer = %answer;
1.767     raeburn   481:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  482: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    483: 	my ($toprow,$bottomrow);
                    484: 	foreach my $foil (@$order) {
                    485: 	    if ($grading{$foil} == 1) {
                    486: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    487: 	    } else {
                    488: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    489: 	    }
1.398     albertel  490: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  491: 	}
                    492: 	return '<blockquote><table border="1">'.
1.466     albertel  493: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    494: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   495: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  496:     } elsif ($response eq 'match') {
                    497: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     498:         my @answer = %answer;
1.767     raeburn   499:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  500: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    501: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    502: 	my ($toprow,$middlerow,$bottomrow);
                    503: 	foreach my $foil (@$order) {
                    504: 	    my $item=shift(@items);
                    505: 	    if ($grading{$foil} == 1) {
                    506: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  507: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  508: 	    } else {
                    509: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  510: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  511: 	    }
1.398     albertel  512: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        513: 	}
1.126     ng        514: 	return '<blockquote><table border="1">'.
1.466     albertel  515: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    516: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  517: 	    $middlerow.'</tr>'.
1.466     albertel  518: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   519: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  520:     } elsif ($response eq 'radiobutton') {
                    521: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     522:         my @answer = %answer;
                    523:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  524: 	my ($toprow,$bottomrow);
1.434     albertel  525: 	my $correct = 
1.640     raeburn   526: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  527: 	foreach my $foil (@$order) {
1.148     albertel  528: 	    if (exists($answer{$foil})) {
1.434     albertel  529: 		if ($foil eq $correct) {
1.466     albertel  530: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  531: 		} else {
1.466     albertel  532: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  533: 		}
                    534: 	    } else {
1.466     albertel  535: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  536: 	    }
1.398     albertel  537: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  538: 	}
                    539: 	return '<blockquote><table border="1">'.
1.466     albertel  540: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    541: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   542: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  543:     } elsif ($response eq 'essay') {
1.257     albertel  544: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        545: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  546: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    547: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        548: 
1.257     albertel  549: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    550: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    551: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    552: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    553: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    554: 	    $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        555: 	}
1.751     raeburn   556:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
1.730     kruse     557: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  558:     } elsif ( $response eq 'organic') {
1.721     bisitz    559:         my $result=&mt('Smile representation: [_1]',
                    560:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  561: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    562: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    563: 	return $result;
1.335     albertel  564:     } elsif ( $response eq 'Task') {
                    565: 	if ( $answer eq 'SUBMITTED') {
                    566: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  567: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  568: 	    return $result;
                    569: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    570: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    571: 			       keys(%{$record}));
                    572: 	    return join('<br />',($version,@matches));
                    573: 			       
                    574: 			       
                    575: 	} else {
                    576: 	    my $result =
                    577: 		'<p>'
                    578: 		.&mt('Overall result: [_1]',
                    579: 		     $record->{$version."resource.$respid.$partid.status"})
                    580: 		.'</p>';
                    581: 	    
                    582: 	    $result .= '<ul>';
                    583: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    584: 			     keys(%{$record}));
                    585: 	    foreach my $grade (sort(@grade)) {
                    586: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    587: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    588: 				     $dim, $record->{$grade}).
                    589: 			  '</li>';
                    590: 	    }
                    591: 	    $result.='</ul>';
                    592: 	    return $result;
                    593: 	}
1.716     bisitz    594:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    595:         # Respect multiple input fields, see Bug #5409
1.440     albertel  596: 	$answer = 
                    597: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    598: 							      $answer);
1.720     kruse     599: 	return $answer;
1.122     ng        600:     }
1.720     kruse     601:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        602: }
                    603: 
                    604: #-- A couple of common js functions
                    605: sub commonJSfunctions {
                    606:     my $request = shift;
1.597     wenzelju  607:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        608:     function radioSelection(radioButton) {
                    609: 	var selection=null;
                    610: 	if (radioButton.length > 1) {
                    611: 	    for (var i=0; i<radioButton.length; i++) {
                    612: 		if (radioButton[i].checked) {
                    613: 		    return radioButton[i].value;
                    614: 		}
                    615: 	    }
                    616: 	} else {
                    617: 	    if (radioButton.checked) return radioButton.value;
                    618: 	}
                    619: 	return selection;
                    620:     }
                    621: 
                    622:     function pullDownSelection(selectOne) {
                    623: 	var selection="";
                    624: 	if (selectOne.length > 1) {
                    625: 	    for (var i=0; i<selectOne.length; i++) {
                    626: 		if (selectOne[i].selected) {
                    627: 		    return selectOne[i].value;
                    628: 		}
                    629: 	    }
                    630: 	} else {
1.138     albertel  631:             // only one value it must be the selected one
                    632: 	    return selectOne.value;
1.118     ng        633: 	}
                    634:     }
                    635: COMMONJSFUNCTIONS
                    636: }
                    637: 
1.44      ng        638: #--- Dumps the class list with usernames,list of sections,
                    639: #--- section, ids and fullnames for each user.
                    640: sub getclasslist {
1.796     raeburn   641:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus,$filterbypbid,$possibles) = @_;
1.291     albertel  642:     my @getsec;
1.450     banghart  643:     my @getgroup;
1.442     banghart  644:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  645:     if (!ref($getsec)) {
                    646: 	if ($getsec ne '' && $getsec ne 'all') {
                    647: 	    @getsec=($getsec);
                    648: 	}
                    649:     } else {
                    650: 	@getsec=@{$getsec};
                    651:     }
                    652:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  653:     if (!ref($getgroup)) {
                    654: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    655: 	    @getgroup=($getgroup);
                    656: 	}
                    657:     } else {
                    658: 	@getgroup=@{$getgroup};
                    659:     }
                    660:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  661: 
1.449     banghart  662:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  663:     # Bail out if we were unable to get the classlist
1.56      matthew   664:     return if (! defined($classlist));
1.449     banghart  665:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   666:     #
                    667:     my %sections;
                    668:     my %fullnames;
1.796     raeburn   669:     my %passback;
1.750     raeburn   670:     my ($cdom,$cnum,$partlist);
                    671:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    672:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    673:         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    674:         my $res_error;
1.773     raeburn   675:         ($partlist) = &response_type($symb,\$res_error);
1.796     raeburn   676:     } elsif ($filterbypbid) {
                    677:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    678:         $cnum = $env{"course.$env{'request.course.id'}.num"};
1.750     raeburn   679:     }
1.205     matthew   680:     foreach my $student (keys(%$classlist)) {
                    681:         my $end      = 
                    682:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    683:         my $start    = 
                    684:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    685:         my $id       = 
                    686:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    687:         my $section  = 
                    688:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    689:         my $fullname = 
                    690:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    691:         my $status   = 
                    692:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  693:         my $group   = 
                    694:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        695: 	# filter students according to status selected
1.750     raeburn   696: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  697: 	    if (!($stu_status =~ $status)) {
1.450     banghart  698: 		delete($classlist->{$student});
1.76      ng        699: 		next;
                    700: 	    }
                    701: 	}
1.450     banghart  702: 	# filter students according to groups selected
1.453     banghart  703: 	my @stu_groups = split(/,/,$group);
1.450     banghart  704: 	if (@getgroup) {
                    705: 	    my $exclude = 1;
1.454     banghart  706: 	    foreach my $grp (@getgroup) {
                    707: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  708: 	            if ($stu_group eq $grp) {
                    709: 	                $exclude = 0;
                    710:     	            } 
1.450     banghart  711: 	        }
1.453     banghart  712:     	        if (($grp eq 'none') && !$group) {
1.750     raeburn   713:         	    $exclude = 0;
1.453     banghart  714:         	}
1.450     banghart  715: 	    }
                    716: 	    if ($exclude) {
                    717: 	        delete($classlist->{$student});
1.750     raeburn   718: 		next;
1.450     banghart  719: 	    }
                    720: 	}
1.750     raeburn   721:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    722:             my $udom =
                    723:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    724:             my $uname =
                    725:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    726:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    727:                 if ($submitonly eq 'queued') {
                    728:                     my %queue_status =
                    729:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    730:                                                                 $udom,$uname);
                    731:                     if (!defined($queue_status{'gradingqueue'})) {
                    732:                         delete($classlist->{$student});
                    733:                         next;
                    734:                     }
                    735:                 } else {
                    736:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    737:                     my $submitted = 0;
                    738:                     my $graded = 0;
                    739:                     my $incorrect = 0;
                    740:                     foreach (keys(%status)) {
                    741:                         $submitted = 1 if ($status{$_} ne 'nothing');
                    742:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    743:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    744: 
                    745:                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    746:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    747:                             $submitted = 0;
                    748:                         }
                    749:                     }
                    750:                     if (!$submitted && ($submitonly eq 'yes' ||
                    751:                                         $submitonly eq 'incorrect' ||
                    752:                                         $submitonly eq 'graded')) {
                    753:                         delete($classlist->{$student});
                    754:                         next;
                    755:                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    756:                         delete($classlist->{$student});
                    757:                         next;
                    758:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    759:                         delete($classlist->{$student});
                    760:                         next;
                    761:                     }
                    762:                 }
                    763:             }
                    764:         }
1.796     raeburn   765:         if ($filterbypbid) {
                    766:             if (ref($possibles) eq 'HASH') {
                    767:                 unless (exists($possibles->{$student})) {
                    768:                     delete($classlist->{$student});
                    769:                     next;
                    770:                 }
                    771:             }
                    772:             my $udom =
                    773:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    774:             my $uname =
                    775:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    776:             if (($udom ne '') && ($uname ne '')) {
                    777:                 my %pbinfo = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',[$filterbypbid],$udom,$uname);
                    778:                 if (ref($pbinfo{$filterbypbid}) eq 'ARRAY') {
1.798     raeburn   779:                     $passback{$student} = $pbinfo{$filterbypbid};
1.796     raeburn   780:                 } else {
                    781:                     delete($classlist->{$student});
                    782:                     next;
                    783:                 }
                    784:             }
                    785:         }
1.205     matthew   786: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  787: 	if (&canview($section)) {
1.291     albertel  788: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  789: 		$sections{$section}++;
1.450     banghart  790: 		if ($classlist->{$student}) {
                    791: 		    $fullnames{$student}=$fullname;
                    792: 		}
1.103     albertel  793: 	    } else {
1.205     matthew   794: 		delete($classlist->{$student});
1.103     albertel  795: 	    }
                    796: 	} else {
1.205     matthew   797: 	    delete($classlist->{$student});
1.103     albertel  798: 	}
1.44      ng        799:     }
1.56      matthew   800:     my @sections = sort(keys(%sections));
1.796     raeburn   801:     return ($classlist,\@sections,\%fullnames,\%passback);
1.44      ng        802: }
                    803: 
1.103     albertel  804: sub canmodify {
                    805:     my ($sec)=@_;
                    806:     if ($perm{'mgr'}) {
                    807: 	if (!defined($perm{'mgr_section'})) {
                    808: 	    # can modify whole class
                    809: 	    return 1;
                    810: 	} else {
                    811: 	    if ($sec eq $perm{'mgr_section'}) {
                    812: 		#can modify the requested section
                    813: 		return 1;
                    814: 	    } else {
1.763     raeburn   815: 		# can't modify the requested section
1.103     albertel  816: 		return 0;
                    817: 	    }
                    818: 	}
                    819:     }
                    820:     #can't modify
                    821:     return 0;
                    822: }
                    823: 
                    824: sub canview {
                    825:     my ($sec)=@_;
                    826:     if ($perm{'vgr'}) {
                    827: 	if (!defined($perm{'vgr_section'})) {
1.763     raeburn   828: 	    # can view whole class
1.103     albertel  829: 	    return 1;
                    830: 	} else {
                    831: 	    if ($sec eq $perm{'vgr_section'}) {
1.763     raeburn   832: 		#can view the requested section
1.103     albertel  833: 		return 1;
                    834: 	    } else {
1.763     raeburn   835: 		# can't view the requested section
1.103     albertel  836: 		return 0;
                    837: 	    }
                    838: 	}
                    839:     }
1.763     raeburn   840:     #can't view
1.103     albertel  841:     return 0;
                    842: }
                    843: 
1.44      ng        844: #--- Retrieve the grade status of a student for all the parts
                    845: sub student_gradeStatus {
1.324     albertel  846:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  847:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        848:     my %partstatus = ();
                    849:     foreach (@$partlist) {
1.128     ng        850: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        851: 	$status              = 'nothing' if ($status eq '');
                    852: 	$partstatus{$_}      = $status;
                    853: 	my $subkey           = "resource.$_.submitted_by";
                    854: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    855:     }
                    856:     return %partstatus;
                    857: }
                    858: 
1.45      ng        859: # hidden form and javascript that calls the form
                    860: # Use by verifyscript and viewgrades
                    861: # Shows a student's view of problem and submission
                    862: sub jscriptNform {
1.324     albertel  863:     my ($symb) = @_;
1.442     banghart  864:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  865:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        866: 	'    function viewOneStudent(user,domain) {'."\n".
                    867: 	'	document.onestudent.student.value = user;'."\n".
                    868: 	'	document.onestudent.userdom.value = domain;'."\n".
                    869: 	'	document.onestudent.submit();'."\n".
                    870: 	'    }'."\n".
1.597     wenzelju  871: 	"\n");
1.45      ng        872:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  873: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  874: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        875: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    876: 	'<input type="hidden" name="student" value="" />'."\n".
                    877: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    878: 	'</form>'."\n";
                    879:     return $jscript;
                    880: }
1.39      ng        881: 
1.447     foxr      882: 
                    883: 
1.811   ! raeburn   884: # Given the score (as a number [0-1], the weight, and a posible 
        !           885: # reduction for submission between duedate and overduedate)
        !           886: # what is the final point value? This function will round to 
        !           887: # the nearest  tenth, third, or quarter if one of those is 
        !           888: # within the tolerance of .00001.
1.316     albertel  889: sub compute_points {
1.811   ! raeburn   890:     my ($score, $weight, $latefrac) = @_;
1.315     bowersj2  891:     
                    892:     my $tolerance = .00001;
                    893:     my $points = $score * $weight;
1.811   ! raeburn   894:     if (($latefrac ne '') && 
        !           895:         ($latefrac < 1) && ($latefrac >= 0))  {
        !           896:         $points = $points * $latefrac;
        !           897:     }
1.315     bowersj2  898: 
                    899:     # Check for nearness to 1/x.
                    900:     my $check_for_nearness = sub {
                    901:         my ($factor) = @_;
                    902:         my $num = ($points * $factor) + $tolerance;
                    903:         my $floored_num = floor($num);
1.316     albertel  904:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  905:             return $floored_num / $factor;
                    906:         }
                    907:         return $points;
                    908:     };
                    909: 
                    910:     $points = $check_for_nearness->(10);
                    911:     $points = $check_for_nearness->(3);
                    912:     $points = $check_for_nearness->(4);
                    913:     
                    914:     return $points;
                    915: }
                    916: 
1.44      ng        917: #------------------ End of general use routines --------------------
1.87      www       918: 
                    919: #
                    920: # Find most similar essay
                    921: #
                    922: 
                    923: sub most_similar {
1.674     raeburn   924:     my ($uname,$udom,$symb,$uessay)=@_;
                    925: 
                    926:     unless ($symb) { return ''; }
                    927: 
                    928:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       929: 
                    930: # ignore spaces and punctuation
                    931: 
                    932:     $uessay=~s/\W+/ /gs;
                    933: 
1.282     www       934: # ignore empty submissions (occuring when only files are sent)
                    935: 
1.598     www       936:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       937: 
1.87      www       938: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       939:     my $limit=0.6;
1.87      www       940:     my $sname='';
                    941:     my $sdom='';
                    942:     my $scrsid='';
                    943:     my $sessay='';
                    944: # go through all essays ...
1.674     raeburn   945:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  946: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       947: # ... except the same student
1.426     albertel  948:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   949: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  950: 	$tessay=~s/\W+/ /gs;
1.87      www       951: # String similarity gives up if not even limit
1.426     albertel  952: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       953: # Found one
1.426     albertel  954: 	if ($tsimilar>$limit) {
                    955: 	    $limit=$tsimilar;
                    956: 	    $sname=$tname;
                    957: 	    $sdom=$tdom;
                    958: 	    $scrsid=$tcrsid;
1.674     raeburn   959: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  960: 	}
1.87      www       961:     }
1.88      www       962:     if ($limit>0.6) {
1.87      www       963:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    964:     } else {
                    965:        return ('','','','',0);
                    966:     }
                    967: }
                    968: 
1.44      ng        969: #-------------------------------------------------------------------
                    970: 
                    971: #------------------------------------ Receipt Verification Routines
1.45      ng        972: #
1.602     www       973: 
                    974: sub initialverifyreceipt {
1.608     www       975:    my ($request,$symb) = @_;
1.602     www       976:    &commonJSfunctions($request);
1.694     bisitz    977:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       978:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    979:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       980:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    981:         '<input type="hidden" name="command" value="verify" />'.
                    982:         "</form>\n";
1.602     www       983: }
                    984: 
1.44      ng        985: #--- Check whether a receipt number is valid.---
                    986: sub verifyreceipt {
1.766     raeburn   987:     my ($request,$symb) = @_;
1.44      ng        988: 
1.257     albertel  989:     my $courseid = $env{'request.course.id'};
1.184     www       990:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  991: 	$env{'form.receipt'};
1.44      ng        992:     $receipt     =~ s/[^\-\d]//g;
                    993: 
1.766     raeburn   994:     my $title =
1.487     albertel  995: 	'<h3><span class="LC_info">'.
1.605     www       996: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    997: 	'</span></h3>'."\n";
1.44      ng        998: 
                    999:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew  1000:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel 1001:     
                   1002:     my $receiptparts=0;
1.390     albertel 1003:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                   1004: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel 1005:     my $parts=['0'];
1.582     raeburn  1006:     if ($receiptparts) {
                   1007:         my $res_error; 
                   1008:         ($parts)=&response_type($symb,\$res_error);
                   1009:         if ($res_error) {
                   1010:             return &navmap_errormsg();
                   1011:         } 
                   1012:     }
1.486     albertel 1013:     
                   1014:     my $header = 
                   1015: 	&Apache::loncommon::start_data_table().
                   1016: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel 1017: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                   1018: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                   1019: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel 1020:     if ($receiptparts) {
1.487     albertel 1021: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel 1022:     }
                   1023:     $header.=
                   1024: 	&Apache::loncommon::end_data_table_header_row();
                   1025: 
1.294     albertel 1026:     foreach (sort 
                   1027: 	     {
                   1028: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1029: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1030: 		 }
                   1031: 		 return $a cmp $b;
                   1032: 	     } (keys(%$fullname))) {
1.44      ng       1033: 	my ($uname,$udom)=split(/\:/);
1.177     albertel 1034: 	foreach my $part (@$parts) {
                   1035: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel 1036: 		$contents.=
                   1037: 		    &Apache::loncommon::start_data_table_row().
                   1038: 		    '<td>&nbsp;'."\n".
1.177     albertel 1039: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 1040: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel 1041: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                   1042: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                   1043: 		if ($receiptparts) {
                   1044: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                   1045: 		}
1.486     albertel 1046: 		$contents.= 
                   1047: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel 1048: 		
                   1049: 		$matches++;
                   1050: 	    }
1.44      ng       1051: 	}
                   1052:     }
                   1053:     if ($matches == 0) {
1.584     bisitz   1054:         $string = $title
                   1055:                  .'<p class="LC_warning">'
                   1056:                  .&mt('No match found for the above receipt number.')
                   1057:                  .'</p>';
1.44      ng       1058:     } else {
1.324     albertel 1059: 	$string = &jscriptNform($symb).$title.
1.487     albertel 1060: 	    '<p>'.
1.584     bisitz   1061: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel 1062: 	    '</p>'.
1.486     albertel 1063: 	    $header.
                   1064: 	    $contents.
                   1065: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng       1066:     }
1.614     www      1067:     return $string;
1.44      ng       1068: }
                   1069: 
1.798     raeburn  1070: #-------------------------------------------------------------------
                   1071: 
                   1072: #------------------------------------------- Grade Passback Routines
                   1073: #
                   1074: 
1.796     raeburn  1075: sub initialpassback {
                   1076:     my ($request,$symb) = @_;
                   1077:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1078:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1079:     my $crstype = &Apache::loncommon::course_type();
                   1080:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   1081:     my $readonly;
                   1082:     unless ($perm{'mgr'}) {
                   1083:         $readonly = 1;
                   1084:     }
                   1085:     my $formname = 'initialpassback';
                   1086:     my $navmap = Apache::lonnavmaps::navmap->new();
                   1087:     my $output;
                   1088:     if (!defined($navmap)) {
                   1089:         if ($crstype eq 'Community') {
                   1090:             $output = &mt('Unable to retrieve information about community contents');
                   1091:         } else {
                   1092:             $output = &mt('Unable to retrieve information about course contents');
                   1093:         }
                   1094:         return '<p>'.$output.'</p>';
                   1095:     }
                   1096:     return &Apache::loncourserespicker::create_picker($navmap,'passback',$formname,$crstype,undef,
                   1097:                                                       undef,undef,undef,undef,undef,undef,
                   1098:                                                       \%passback,$readonly);
                   1099: }
                   1100: 
                   1101: sub passback_filters {
                   1102:     my ($request,$symb) = @_;
                   1103:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1104:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1105:     my $crstype = &Apache::loncommon::course_type();
                   1106:     my ($launcher,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
                   1107:     if ($env{'form.passback'} ne '') {
                   1108:         $chosen = &unescape($env{'form.passback'});
                   1109:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1110:         ($launcher,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
                   1111:     }
                   1112:     my $result;
                   1113:     if ($launcher ne '') {
                   1114:         $result = &launcher_info_box($launcher,$appname,$setter,$linkuri,$scope).
                   1115:                   '<p><br />'.&mt('Set criteria to use to list students for possible passback of scores, then push Next [_1]',
                   1116:                                   '&rarr;').
                   1117:                   '</p>';
                   1118:     }
                   1119:     $result .= '<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   1120:                '<input type="hidden" name="passback" value="'.&escape($chosen).'" />'."\n".
                   1121:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   1122:     my ($submittext,$newcommand);
                   1123:     if ($launcher ne '') {
                   1124:         $submittext = &mt('Next').' &rarr;';
                   1125:         $newcommand = 'passbacknames';
                   1126:         $result .=  &selectfield(0)."\n";
                   1127:     } else {
                   1128:         $submittext = '&larr; '.&mt('Previous');
                   1129:         $newcommand = 'initialpassback';
                   1130:         if ($env{'form.passback'}) {
                   1131:             $result .= '<span class="LC_warning">'.&mt('Invalid launcher').'</span>'."\n";
                   1132:         } else {
                   1133:             $result .= '<span class="LC_warning">'.&mt('No launcher selected').'</span>'."\n";
                   1134:         }
                   1135:     }
                   1136:     $result .=  '<input type="hidden" name="command" value="'.$newcommand.'" />'."\n".
                   1137:                 '<div>'."\n".
                   1138:                 '<input type="submit" value="'.$submittext.'" />'."\n".
                   1139:                 '</div>'."\n".
                   1140:                 '</form>'."\n";
                   1141:     return $result;
                   1142: }
                   1143: 
                   1144: sub names_for_passback {
                   1145:     my ($request,$symb) = @_;
                   1146:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1147:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1148:     my $crstype = &Apache::loncommon::course_type();
                   1149:     my ($launcher,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
                   1150:     if ($env{'form.passback'} ne '') {
                   1151:         $chosen = &unescape($env{'form.passback'});
                   1152:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1153:         ($launcher,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
                   1154:     }
                   1155:     my ($result,$ctr,$newcommand,$submittext);
                   1156:     if ($launcher ne '') {
                   1157:         $result = &launcher_info_box($launcher,$appname,$setter,$linkuri,$scope);
                   1158:     }
                   1159:     $ctr = 0;
                   1160:     my @statuses = &Apache::loncommon::get_env_multiple('form.Status');
                   1161:     my $stu_status = join(':',@statuses);
                   1162:     $result .= '<form action="/adm/grades" method="post" name="passbackusers">'."\n".
                   1163:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   1164:     if ($launcher ne '') {
                   1165:         $result .= '<input type="hidden" name="passback" value="'.&escape($chosen).'" />'."\n".
                   1166:                    '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
                   1167:         my ($sections,$groups,$group_display,$disabled) = &sections_and_groups();
                   1168:         my $section_display = join(' ',@{$sections});
                   1169:         my $status_display;
                   1170:         if ((grep(/^Any$/,@statuses)) ||
                   1171:             (@statuses == 3)) {
                   1172:             $status_display = &mt('Any');
                   1173:         } else {
                   1174:             $status_display = join(' '.&mt('or').' ',map { &mt($_); } @statuses);
                   1175:         }
                   1176:         $result .= '<p>'.&mt('Student(s) with stored passback credentials for [_1], and also satisfy:',
                   1177:                              '<span class="LC_cusr_emph">'.$linkuri.'</span>').
                   1178:                    '<ul>'.
                   1179:                    '<li>'.&mt('Section(s)').": $section_display</li>\n".
                   1180:                    '<li>'.&mt('Group(s)').": $group_display</li>\n".
                   1181:                    '<li>'.&mt('Status').": $status_display</li>\n".
                   1182:                    '</ul>';
                   1183:         my ($classlist,undef,$fullname) = &getclasslist($sections,'1',$groups,'','','',$chosen);
                   1184:         if (keys(%$fullname)) {
                   1185:             $newcommand = 'passbackscores';
                   1186:             $result .= &build_section_inputs().
                   1187:                        &checkselect_js('passbackusers').
                   1188:                        '<p><br />'.
                   1189:                        &mt("To send scores, check box(es) next to the student's name(s), then push 'Send Scores'.").
                   1190:                        '</p>'.
                   1191:                        &check_script('passbackusers', 'stuinfo')."\n".
                   1192:                        '<input type="button" '."\n".
                   1193:                        'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1194:                        'value="'.&mt('Send Scores').'" /> <br />'."\n".
                   1195:                        &check_buttons()."\n".
                   1196:                        &Apache::loncommon::start_data_table().
                   1197:                        &Apache::loncommon::start_data_table_header_row();
                   1198:             my $loop = 0;
                   1199:             while ($loop < 2) {
                   1200:                 $result .= '<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1201:                            '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
                   1202:                 $loop++;
                   1203:             }
                   1204:             $result .= &Apache::loncommon::end_data_table_header_row()."\n";
                   1205:             foreach my $student (sort
                   1206:                                  {
                   1207:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1208:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1209:                                      }
                   1210:                                      return $a cmp $b;
                   1211:                                  }
                   1212:                                  (keys(%$fullname))) {
                   1213:                 $ctr++;
                   1214:                 my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                   1215:                 my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
                   1216:                 my $udom = $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                   1217:                 my $uname = $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                   1218:                 if ( $perm{'vgr'} eq 'F' ) {
                   1219:                     if ($ctr%2 ==1) {
                   1220:                         $result.= &Apache::loncommon::start_data_table_row();
                   1221:                     }
                   1222:                     $result .= '<td align="right">'.$ctr.'&nbsp;</td>'.
                   1223:                                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
                   1224:                                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1225:                                ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1226:                                &nameUserString(undef,$$fullname{$student},$uname,$udom).
                   1227:                                '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
                   1228: 
                   1229:                     if ($ctr%2 ==0) {
                   1230:                         $result .= &Apache::loncommon::end_data_table_row()."\n";
                   1231:                     }
                   1232:                 }
                   1233:             }
                   1234:             if ($ctr%2 ==1) {
                   1235:                 $result .= &Apache::loncommon::end_data_table_row();
                   1236:             }
                   1237:             $result .= &Apache::loncommon::end_data_table()."\n";
                   1238:             if ($ctr) {
                   1239:                 $result .= '<input type="button" '.
                   1240:                            'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1241:                            'value="'.&mt('Send Scores').'" />'."\n";
                   1242:             }
                   1243:         } else {
                   1244:             $submittext = '&larr; '.&mt('Previous');
                   1245:             $newcommand = 'passback';
                   1246:             $result .= '<span class="LC_warning">'.&mt('No students match the selection criteria').'</p>';
                   1247:         }
                   1248:     } else {
                   1249:         $newcommand = 'initialpassback';
                   1250:         $submittext = &mt('Start over');
                   1251:         if ($env{'form.passback'}) {
                   1252:             $result .= '<span class="LC_warning">'.&mt('Invalid launcher').'</span>'."\n";
                   1253:         } else {
                   1254:             $result .= '<span class="LC_warning">'.&mt('No launcher selected').'</span>'."\n";
                   1255:         }
                   1256:     }
                   1257:     $result .=  '<input type="hidden" name="command" value="'.$newcommand.'" />'."\n";
                   1258:     if (!$ctr) {
                   1259:         $result .= '<div>'."\n".
                   1260:                    '<input type="submit" value="'.$submittext.'" />'."\n".
                   1261:                    '</div>'."\n";
                   1262:     }
                   1263:     $result .= '</form>'."\n";
                   1264:     return $result;
                   1265: }
                   1266: 
                   1267: sub do_passback {
                   1268:     my ($request,$symb) = @_;
                   1269:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1270:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1271:     my $crstype = &Apache::loncommon::course_type();
1.806     raeburn  1272:     my ($launchsymb,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
1.796     raeburn  1273:     if ($env{'form.passback'} ne '') {
                   1274:         $chosen = &unescape($env{'form.passback'});
                   1275:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
1.806     raeburn  1276:         ($launchsymb,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
1.796     raeburn  1277:     }
1.806     raeburn  1278:     if ($launchsymb ne '') {
                   1279:         $request->print(&launcher_info_box($launchsymb,$appname,$setter,$linkuri,$scope));
1.796     raeburn  1280:     }
                   1281:     my $error;
                   1282:     if ($perm{'mgr'}) {
1.806     raeburn  1283:         if ($launchsymb ne '') {
1.796     raeburn  1284:             my @poss_students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   1285:             if (@poss_students) {
                   1286:                 my %possibles;
                   1287:                 foreach my $item (@poss_students) {
                   1288:                     my ($stuname,$studom) = split(/:/,$item,3);
                   1289:                     $possibles{$stuname.':'.$studom} = 1;
                   1290:                 }
                   1291:                 my ($sections,$groups,$group_display,$disabled) = &sections_and_groups();
                   1292:                 my ($classlist,undef,$fullname,$pbinfo) =
                   1293:                     &getclasslist($sections,'1',$groups,'','','',$chosen,\%possibles);
                   1294:                 if ((ref($classlist) eq 'HASH') && (ref($pbinfo) eq 'HASH')) {
                   1295:                     my %passback = %{$pbinfo};
                   1296:                     my (%tosend,%remotenotok,%scorenotok,%zeroposs,%nopbinfo);
                   1297:                     foreach my $possible (keys(%possibles)) {
                   1298:                         if ((exists($classlist->{$possible})) &&
                   1299:                             (exists($passback{$possible})) && (ref($passback{$possible}) eq 'ARRAY')) {
                   1300:                             $tosend{$possible} = 1;
                   1301:                         }
                   1302:                     }
                   1303:                     if (keys(%tosend)) {
                   1304:                         my ($lti_in_use,$crsdef);
                   1305:                         my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
                   1306:                         if ($ltitype eq 'c') {
                   1307:                             my %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1308:                             $lti_in_use = $crslti{$ltinum};
                   1309:                             $crsdef = 1;
                   1310:                         } else {
                   1311:                             my %domlti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1312:                             $lti_in_use = $domlti{$ltinum};
                   1313:                         }
                   1314:                         if (ref($lti_in_use) eq 'HASH') {
                   1315:                             my $msgformat = $lti_in_use->{'passbackformat'};
                   1316:                             my $keynum = $lti_in_use->{'cipher'};
                   1317:                             my $scoretype = 'decimal';
                   1318:                             if ($lti_in_use->{'scoreformat'} =~ /^(decimal|ratio|percentage)$/) {
                   1319:                                 $scoretype = $1;
                   1320:                             }
                   1321:                             my $pbmap;
1.806     raeburn  1322:                             if ($launchsymb =~ /\.(page|sequence)$/) {
                   1323:                                 $pbmap = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($launchsymb))[2]);
1.796     raeburn  1324:                             } else {
1.806     raeburn  1325:                                 $pbmap = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($launchsymb))[0]);
1.796     raeburn  1326:                             }
                   1327:                             $pbmap = &Apache::lonnet::clutter($pbmap);
                   1328:                             my $pbscope;
                   1329:                             if ($scope eq 'res') {
                   1330:                                 $pbscope = 'resource';
                   1331:                             } elsif ($scope eq 'map') {
                   1332:                                 $pbscope = 'nonrec';
                   1333:                             } elsif ($scope eq 'rec') {
                   1334:                                 $pbscope = 'map';
                   1335:                             }
1.798     raeburn  1336:                             my %pb = &common_passback_info();
1.796     raeburn  1337:                             my $numstudents = scalar(keys(%tosend));
                   1338:                             my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($request,$numstudents);
                   1339:                             my $outcome = &Apache::loncommon::start_data_table().
1.806     raeburn  1340:                                           &Apache::loncommon::start_data_table_header_row();
1.796     raeburn  1341:                             my $loop = 0;
                   1342:                             while ($loop < 2) {
                   1343:                                 $outcome .= '<th>'.&mt('No.').'</th>'.
1.806     raeburn  1344:                                             '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>'.
                   1345:                                             '<th>'.&mt('Score').'</th>';
                   1346:                                 $loop++;
1.796     raeburn  1347:                             }
                   1348:                             $outcome .= &Apache::loncommon::end_data_table_header_row()."\n";
                   1349:                             my $ctr=0;
                   1350:                             foreach my $student (sort
                   1351:                                 {
                   1352:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1353:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1354:                                      }
                   1355:                                      return $a cmp $b;
                   1356:                                 } (keys(%$fullname))) {
                   1357:                                 next unless ($tosend{$student});
                   1358:                                 my ($uname,$udom) = split(/:/,$student);
                   1359:                                 &Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last student');
                   1360:                                 my ($uname,$udom) = split(/:/,$student);
                   1361:                                 my $uhome = &Apache::lonnet::homeserver($uname,$udom),
                   1362:                                 my $id = $passback{$student}[0],
                   1363:                                 my $url = $passback{$student}[1],
                   1364:                                 my ($total,$possible,$usec);
                   1365:                                 if (ref($classlist->{$student}) eq 'ARRAY') {
                   1366:                                     $usec = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION];
                   1367:                                 }
                   1368:                                 if ($pbscope eq 'resource') {
                   1369:                                     $total = 0;
                   1370:                                     $possible = 0;
                   1371:                                     my $navmap = Apache::lonnavmaps::navmap->new($uname,$udom);
                   1372:                                     if (ref($navmap)) {
1.806     raeburn  1373:                                         my $res = $navmap->getBySymb($launchsymb);
1.796     raeburn  1374:                                         if (ref($res)) {
                   1375:                                             my $partlist = $res->parts();
                   1376:                                             if (ref($partlist) eq 'ARRAY') {
1.806     raeburn  1377:                                                 my %record = &Apache::lonnet::restore($launchsymb,$env{'request.course.id'},$udom,$uname);
1.796     raeburn  1378:                                                 foreach my $part (@{$partlist}) {
                   1379:                                                     next if ($record{"resource.$part.solved"} =~/^excused/);
1.806     raeburn  1380:                                                     my $weight = &Apache::lonnet::EXT("resource.$part.weight",$launchsymb,$udom,$uname,$usec);
1.796     raeburn  1381:                                                     $possible += $weight;
                   1382:                                                     if (($record{'version'}) && (exists($record{"resource.$part.awarded"}))) {
                   1383:                                                         my $awarded = $record{"resource.$part.awarded"};
                   1384:                                                         if ($awarded) {
                   1385:                                                             $total += $weight * $awarded;
                   1386:                                                         }
                   1387:                                                     }
                   1388:                                                 }
                   1389:                                             }
                   1390:                                         }
                   1391:                                     }
                   1392:                                 } elsif (($pbscope eq 'map') || ($pbscope eq 'nonrec')) {
                   1393:                                     ($total,$possible) =
1.806     raeburn  1394:                                         &Apache::lonhomework::get_lti_score($uname,$udom,$usec,$pbmap,$pbscope);
1.796     raeburn  1395:                                 }
                   1396:                                 if (($id ne '') && ($url ne '') && ($possible)) {
                   1397:                                     my ($sent,$score,$code,$result) =
1.798     raeburn  1398:                                         &LONCAPA::ltiutils::send_grade($cdom,$cnum,$crsdef,$pb{'type'},$ltinum,$keynum,$id,
                   1399:                                                                        $url,$scoretype,$pb{'sigmethod'},$msgformat,$total,$possible);
1.796     raeburn  1400:                                     my $no_passback;
                   1401:                                     if ($sent) {
                   1402:                                         if ($code == 200) {
                   1403:                                             delete($tosend{$student});
                   1404:                                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
                   1405:                                             my $store = {
                   1406:                                                  'score' => $score,
1.798     raeburn  1407:                                                  'ip' => $pb{'ip'},
                   1408:                                                  'host' => $pb{'lonhost'},
1.796     raeburn  1409:                                                  'protector' => $linkprotector,
                   1410:                                                  'deeplink' => $linkuri,
                   1411:                                                  'scope' => $scope,
                   1412:                                                  'url' => $url,
                   1413:                                                  'id' => $id,
1.798     raeburn  1414:                                                  'clientip' => $pb{'clientip'},
1.796     raeburn  1415:                                                  'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
1.806     raeburn  1416:                                             };
1.796     raeburn  1417:                                             my $value='';
                   1418:                                             foreach my $key (keys(%{$store})) {
                   1419:                                                 $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
                   1420:                                             }
                   1421:                                             $value=~s/\&$//;
                   1422:                                             &Apache::lonnet::courselog(&escape($linkuri).':'.$uname.':'.$udom.':EXPORT:'.$value);
1.807     raeburn  1423:                                             &Apache::lonnet::store_userdata({'score' => $score},$chosen,$namespace,$udom,$uname,$pb{'ip'});
1.796     raeburn  1424:                                             $ctr++;
                   1425:                                             if ($ctr%2 ==1) {
                   1426:                                                 $outcome .= &Apache::loncommon::start_data_table_row();
                   1427:                                             }
                   1428:                                             my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
                   1429:                                             $outcome .= '<td align="right">'.$ctr.'&nbsp;</td>'.
1.806     raeburn  1430:                                                         '<td>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).
                   1431:                                                         '&nbsp;'.$usec.($group ne '' ?'/'.$group:'').'</td>'.
                   1432:                                                         '<td>'.$score.'</td>'."\n";
1.796     raeburn  1433:                                             if ($ctr%2 ==0) {
                   1434:                                                 $outcome .= &Apache::loncommon::end_data_table_row()."\n";
                   1435:                                             }
                   1436:                                         } else {
                   1437:                                             $remotenotok{$student} = 1;
                   1438:                                             $no_passback = "Passback response for ".$linkprotector." was $code ($result)";
                   1439:                                             &Apache::lonnet::logthis($no_passback." for $uname:$udom in ${cdom}_${cnum}");
                   1440:                                         }
                   1441:                                     } else {
                   1442:                                         $scorenotok{$student} = 1;
                   1443:                                         $no_passback = "Passback of grades not sent for ".$linkprotector;
                   1444:                                         &Apache::lonnet::logthis($no_passback." for $uname:$udom in ${cdom}_${cnum}");
                   1445:                                     }
                   1446:                                     if ($no_passback) {
                   1447:                                         &Apache::lonnet::log($udom,$uname,$uhome,$no_passback." score: $score; total: $total; possible: $possible");
1.805     raeburn  1448:                                         my $key = &Time::HiRes::time().':'.$uname.':'.$udom.':'.
                   1449:                                                   "$linkuri\0$linkprotector\0$scope"; 
1.796     raeburn  1450:                                         my $ltigrade = {
1.805     raeburn  1451:                                                          $key => {
                   1452:                                                                    'ltinum'   => $ltinum,
                   1453:                                                                    'lti'      => $lti_in_use,
                   1454:                                                                    'crsdef'   => $crsdef,
                   1455:                                                                    'cid'      => $cdom.'_'.$cnum,
                   1456:                                                                    'uname'    => $uname,
                   1457:                                                                    'udom'     => $udom,
                   1458:                                                                    'uhome'    => $uhome,
                   1459:                                                                    'pbid'     => $id,
                   1460:                                                                    'pburl'    => $url,
                   1461:                                                                    'pbtype'   => $pb{'type'},
                   1462:                                                                    'pbscope'  => $pbscope,
                   1463:                                                                    'pbmap'    => $pbmap,
1.806     raeburn  1464:                                                                    'pbsymb'   => $launchsymb,
1.805     raeburn  1465:                                                                    'format'   => $scoretype,
                   1466:                                                                    'scope'    => $scope,
                   1467:                                                                    'clientip' => $pb{'clientip'},
                   1468:                                                                    'linkprot' => $linkprotector.':'.$linkuri,
                   1469:                                                                    'total'    => $total,
                   1470:                                                                    'possible' => $possible,
                   1471:                                                                    'score'    => $score,
                   1472:                                                                  },
1.796     raeburn  1473:                                         };
                   1474:                                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1475:                                     }
                   1476:                                 } else {
                   1477:                                     if (($id ne '') && ($url ne '')) {
                   1478:                                         $zeroposs{$student} = 1;
                   1479:                                     } else {
                   1480:                                         $nopbinfo{$student} = 1;
                   1481:                                     }
                   1482:                                 }
                   1483:                             }
                   1484:                             &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
                   1485:                             if ($ctr%2 ==1) {
                   1486:                                 $outcome .= &Apache::loncommon::end_data_table_row();
                   1487:                             }
                   1488:                             $outcome .= &Apache::loncommon::end_data_table();
                   1489:                             if ($ctr) {
                   1490:                                 $request->print('<p><br />'.&mt('Scores sent to launcher CMS').'</p>'.
                   1491:                                                 '<p>'.$outcome.'</p>');
                   1492:                             } else {
                   1493:                                 $request->print('<p>'.&mt('No scores sent to launcher CMS').'</p>');
                   1494:                             }
                   1495:                             if (keys(%tosend)) {
                   1496:                                 $request->print('<p>'.&mt('No scores sent for following'));
                   1497:                                 my ($zeros,$nopbcreds,$noconfirm,$noscore);
                   1498:                                 foreach my $student (sort
                   1499:                                 {
                   1500:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1501:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1502:                                      }
                   1503:                                      return $a cmp $b;
                   1504:                                 } (keys(%$fullname))) {
                   1505:                                     next unless ($tosend{$student});
                   1506:                                     my ($uname,$udom) = split(/:/,$student);
                   1507:                                     my $line = '<li>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).'</li>'."\n";
                   1508:                                     if ($zeroposs{$student}) {
                   1509:                                         $zeros .= $line;
                   1510:                                     } elsif ($nopbinfo{$student}) {
                   1511:                                         $nopbcreds .= $line;
                   1512:                                     } elsif ($remotenotok{$student}) {
                   1513:                                         $noconfirm .= $line;
                   1514:                                     } elsif ($scorenotok{$student}) {
                   1515:                                         $noscore .= $line;
                   1516:                                     }
                   1517:                                 }
                   1518:                                 if ($zeros) {
                   1519:                                     $request->print('<br />'.&mt('Total points possible was 0').':'.
                   1520:                                                     '<ul>'.$zeros.'</ul><br />');
                   1521:                                 }
                   1522:                                 if ($nopbcreds) {
                   1523:                                     $request->print('<br />'.&mt('Missing unique identifier and/or passback location').':'.
                   1524:                                                     '<ul>'.$nopbcreds.'</ul><br />');
                   1525:                                 }
                   1526:                                 if ($noconfirm) {
                   1527:                                     $request->print('<br />'.&mt('Score receipt not confirmed by receiving CMS').':'.
                   1528:                                                     '<ul>'.$noconfirm.'</ul><br />');
                   1529:                                 }
                   1530:                                 if ($noscore) {
                   1531:                                     $request->print('<br />'.&mt('Score computation or transmission failed').':'.
                   1532:                                                     '<ul>'.$noscore.'</ul><br />');
                   1533:                                 }
                   1534:                                 $request->print('</p>');
                   1535:                             }
                   1536:                         } else {
                   1537:                             $error = &mt('Settings for deep-link launch target unavailable, so no scores were sent');
                   1538:                         }
                   1539:                     } else {
                   1540:                         $error = &mt('No available students for whom scores can be sent.');
                   1541:                     }
                   1542:                 } else {
                   1543:                     $error = &mt('Classlist could not be retrieved so no scores were sent.');
                   1544:                 }
                   1545:             } else {
                   1546:                 $error = &mt('No students selected to receive scores so none were sent.');
                   1547:             }
                   1548:         } else {
                   1549:             if ($env{'form.passback'}) {
                   1550:                 $error = &mt('Deep-link launch target was invalid so no scores were sent.');
                   1551:             } else {
                   1552:                 $error = &mt('Deep-link launch target was missing so no scores were sent.');
                   1553:             }
                   1554:         }
                   1555:     } else {
                   1556:         $error = &mt('You do not have permission to manage grades, so no scores were sent');
                   1557:     }
                   1558:     if ($error) {
                   1559:         $request->print('<p class="LC_info">'.$error.'</p>');
                   1560:     }
                   1561:     return;
                   1562: }
                   1563: 
                   1564: sub get_passback_launcher {
                   1565:     my ($cdom,$cnum,$chosen) = @_;
                   1566:     my ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1567:     my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
                   1568:     my ($appname,$setter);
                   1569:     if ($ltitype eq 'c') {
                   1570:         my %lti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1571:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1572:             $appname = $lti{$ltinum}{'name'};
                   1573:             if ($appname) {
                   1574:                 $setter = ' (defined in course)';
                   1575:             }
                   1576:         }
                   1577:     } elsif ($ltitype eq 'd') {
                   1578:         my %lti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1579:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1580:             $appname = $lti{$ltinum}{'name'};
                   1581:             if ($appname) {
                   1582:                 $setter = ' (defined in domain)';
                   1583:             }
                   1584:         }
                   1585:     }
1.806     raeburn  1586:     my $launchsymb = &Apache::loncommon::symb_from_tinyurl($linkuri,$cnum,$cdom);
                   1587:     if ($launchsymb eq '') {
                   1588:         my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   1589:         foreach my $poss_symb (keys(%passback)) {
                   1590:             if (ref($passback{$poss_symb}) eq 'HASH') {
                   1591:                 if (exists($passback{$poss_symb}{$chosen})) {
                   1592:                     $launchsymb = $poss_symb;
                   1593:                     last;
1.796     raeburn  1594:                 }
                   1595:             }
                   1596:         }
1.806     raeburn  1597:         if ($launchsymb ne '') {
                   1598:             return ($launchsymb,$appname,$setter);
                   1599:         }
                   1600:     } else {
                   1601:         my %passback = &Apache::lonnet::get('nohist_linkprot_passback',[$launchsymb],$cdom,$cnum);
                   1602:         if (ref($passback{$launchsymb}) eq 'HASH') {
                   1603:             if (exists($passback{$launchsymb}{$chosen})) {
                   1604:                 return ($launchsymb,$appname,$setter);
                   1605:             }
                   1606:         }
1.796     raeburn  1607:     }
                   1608:     return ();
                   1609: }
                   1610: 
                   1611: sub sections_and_groups {
                   1612:     my (@sections,@groups,$group_display);
                   1613:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   1614:     if (grep(/^all$/,@groups)) {
                   1615:          @groups = ('all');
                   1616:          $group_display = 'all';
                   1617:     } elsif (grep(/^none$/,@groups)) {
                   1618:          @groups = ('none');
                   1619:          $group_display = 'none';
                   1620:     } elsif (@groups > 0) {
                   1621:          $group_display = join(', ',@groups);
                   1622:     }
                   1623:     if ($env{'request.course.sec'} ne '') {
                   1624:         @sections = ($env{'request.course.sec'});
                   1625:     } else {
                   1626:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1627:     }
                   1628:     my $disabled = ' disabled="disabled"';
                   1629:     if ($perm{'mgr'}) {
                   1630:         if (grep(/^all$/,@sections)) {
                   1631:             undef($disabled);
                   1632:         } else {
                   1633:             foreach my $sec (@sections) {
                   1634:                 if (&canmodify($sec)) {
                   1635:                     undef($disabled);
                   1636:                     last;
                   1637:                 }
                   1638:             }
                   1639:         }
                   1640:     }
                   1641:     if (grep(/^all$/,@sections)) {
                   1642:         @sections = ('all');
                   1643:     }
                   1644:     return(\@sections,\@groups,$group_display,$disabled);
                   1645: }
                   1646: 
                   1647: sub launcher_info_box {
                   1648:     my ($launcher,$appname,$setter,$linkuri,$scope) = @_;
                   1649:     my $shownscope;
                   1650:     if ($scope eq 'res') {
                   1651:         $shownscope = &mt('Resource');
                   1652:     } elsif ($scope eq 'map') {
                   1653:         $shownscope = &mt('Folder');
                   1654:     }  elsif ($scope eq 'rec') {
                   1655:         $shownscope = &mt('Folder + sub-folders');
                   1656:     }
                   1657:     return '<p>'.
                   1658:            &Apache::lonhtmlcommon::start_pick_box().
                   1659:            &Apache::lonhtmlcommon::row_title(&mt('Launch Item Title')).
1.797     raeburn  1660:            &Apache::lonnet::gettitle($launcher).
1.796     raeburn  1661:            &Apache::lonhtmlcommon::row_closure().
                   1662:            &Apache::lonhtmlcommon::row_title(&mt('Deep-link')).
                   1663:            $linkuri.
                   1664:            &Apache::lonhtmlcommon::row_closure().
                   1665:            &Apache::lonhtmlcommon::row_title(&mt('Launcher')).
                   1666:            $appname.' '.$setter.
                   1667:            &Apache::lonhtmlcommon::row_closure().
                   1668:            &Apache::lonhtmlcommon::row_title(&mt('Score Type')).
                   1669:            $shownscope.      
                   1670:            &Apache::lonhtmlcommon::row_closure(1).
                   1671:            &Apache::lonhtmlcommon::end_pick_box().'</p>'."\n";
                   1672: }
                   1673: 
1.798     raeburn  1674: sub passbacks_for_symb {
                   1675:     my ($cdom,$cnum,$symb) = @_;
                   1676:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   1677:     my %needpb;
                   1678:     if (keys(%passback)) {
                   1679:         my $checkpb = 1;
                   1680:         if (exists($passback{$symb})) {
                   1681:             if (keys(%passback) == 1) {
                   1682:                 undef($checkpb);
                   1683:             }
                   1684:             if (ref($passback{$symb}) eq 'HASH') {
                   1685:                 foreach my $launcher (keys(%{$passback{$symb}})) {
1.806     raeburn  1686:                     $needpb{$launcher} = $symb;
1.798     raeburn  1687:                 }
                   1688:             }
                   1689:         }
                   1690:         if ($checkpb) {
                   1691:             my ($map,$id,$url) = &Apache::lonnet::decode_symb($symb);
                   1692:             my $navmap = Apache::lonnavmaps::navmap->new();
                   1693:             if (ref($navmap)) {
                   1694:                 my $mapres = $navmap->getResourceByUrl($map);
                   1695:                 if (ref($mapres)) {
                   1696:                     my $mapsymb = $mapres->symb();
                   1697:                     if (exists($passback{$mapsymb})) {
                   1698:                         if (keys(%passback) == 1) {
                   1699:                             undef($checkpb);
                   1700:                         }
                   1701:                         if (ref($passback{$mapsymb}) eq 'HASH') {
                   1702:                             foreach my $launcher (keys(%{$passback{$mapsymb}})) {
1.806     raeburn  1703:                                 $needpb{$launcher} = $mapsymb;
1.798     raeburn  1704:                             }
                   1705:                         }
                   1706:                     }
                   1707:                     my %posspb;
                   1708:                     if ($checkpb) {
                   1709:                         my @recurseup = $navmap->recurseup_maps($map,1);
                   1710:                         if (@recurseup) {
                   1711:                             map { $posspb{$_} = 1; } @recurseup;
                   1712:                         }
                   1713:                     }
                   1714:                     foreach my $key (keys(%passback)) {
                   1715:                         if (exists($posspb{$key})) {
                   1716:                             if (ref($passback{$key}) eq 'HASH') {
                   1717:                                 foreach my $launcher (keys(%{$passback{$key}})) {
                   1718:                                     my ($linkuri,$linkprotector,$scope) = split("\0",$launcher);
                   1719:                                     next unless ($scope eq 'rec');
1.806     raeburn  1720:                                     $needpb{$launcher} = $key;
1.798     raeburn  1721:                                 }
                   1722:                             }
                   1723:                         }
                   1724:                     }
                   1725:                 }
                   1726:             }
                   1727:         }
                   1728:     }
                   1729:     return %needpb;
                   1730: }
                   1731: 
                   1732: sub process_passbacks {
1.802     raeburn  1733:     my ($context,$symbs,$cdom,$cnum,$udom,$uname,$usec,$weights,$awardeds,$excuseds,$needpb,
1.798     raeburn  1734:         $skip_passback,$pbsave,$pbids) = @_;
                   1735:     if ((ref($needpb) eq 'HASH') && (ref($skip_passback) eq 'HASH') && (ref($pbsave) eq 'HASH')) {
                   1736:         my (%weight,%awarded,%excused);
                   1737:         if ((ref($symbs) eq 'ARRAY') && (ref($weights) eq 'HASH') && (ref($awardeds) eq 'HASH') &&
                   1738:             (ref($excuseds) eq 'HASH')) {
                   1739:             %weight = %{$weights};
                   1740:             %awarded = %{$awardeds};
                   1741:             %excused = %{$excuseds};
                   1742:         }
                   1743:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
                   1744:         my @launchers = keys(%{$needpb});
                   1745:         my %pbinfo;
                   1746:         if (ref($pbids) eq 'HASH') {
                   1747:             %pbinfo = %{$pbids};
                   1748:         } else {
                   1749:             %pbinfo = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@launchers,$udom,$uname);
                   1750:         }
                   1751:         my %pbc = &common_passback_info();
                   1752:         foreach my $launcher (@launchers) {
                   1753:             if (ref($pbinfo{$launcher}) eq 'ARRAY') {
                   1754:                 my $pbid = $pbinfo{$launcher}[0];
                   1755:                 my $pburl = $pbinfo{$launcher}[1];
                   1756:                 my (%total_by_symb,%possible_by_symb);
                   1757:                 if (($pbid ne '') && ($pburl ne '')) {
                   1758:                     next if ($skip_passback->{$launcher});
                   1759:                     my %pb = %pbc;
                   1760:                     if ((exists($pbsave->{$launcher})) &&
                   1761:                         (ref($pbsave->{$launcher}) eq 'HASH')) {
                   1762:                         foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
                   1763:                                           'symb','map','pbscope','linkuri','linkprotector','scope') {
                   1764:                             $pb{$item} = $pbsave->{$launcher}{$item};
                   1765:                         }
                   1766:                     } else {
                   1767:                         my $ltitype;
                   1768:                         ($pb{'linkuri'},$pb{'linkprotector'},$pb{'scope'}) = split("\0",$launcher);
                   1769:                         ($pb{'ltinum'},$ltitype) = ($pb{'linkprotector'} =~ /^(\d+)(c|d)$/);
                   1770:                         if ($ltitype eq 'c') {
                   1771:                             my %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1772:                             $pb{'lti_in_use'} = $crslti{$pb{'ltinum'}};
                   1773:                             $pb{'crsdef'} = 1;
                   1774:                         } else {
                   1775:                             my %domlti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1776:                             $pb{'lti_in_use'} = $domlti{$pb{'ltinum'}};
                   1777:                         }
                   1778:                         if (ref($pb{'lti_in_use'}) eq 'HASH') {
                   1779:                             $pb{'msgformat'} = $pb{'lti_in_use'}->{'passbackformat'};
                   1780:                             $pb{'keynum'} = $pb{'lti_in_use'}->{'cipher'};
                   1781:                             $pb{'scoretype'} = 'decimal';
                   1782:                             if ($pb{'lti_in_use'}->{'scoreformat'} =~ /^(decimal|ratio|percentage)$/) {
                   1783:                                 $pb{'scoretype'} = $1;
                   1784:                             }
1.806     raeburn  1785:                             $pb{'symb'} = $needpb->{$launcher};
1.798     raeburn  1786:                             if ($pb{'symb'} =~ /\.(page|sequence)$/) {
                   1787:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[2]);
                   1788:                             } else {
                   1789:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[0]);
                   1790:                             }
                   1791:                             $pb{'map'} = &Apache::lonnet::clutter($pb{'map'});
                   1792:                             if ($pb{'scope'} eq 'res') {
                   1793:                                 $pb{'pbscope'} = 'resource';
                   1794:                             } elsif ($pb{'scope'} eq 'map') {
                   1795:                                 $pb{'pbscope'} = 'nonrec';
                   1796:                             } elsif ($pb{'scope'} eq 'rec') {
                   1797:                                 $pb{'pbscope'} = 'map';
                   1798:                             }
                   1799:                             foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
                   1800:                                               'symb','map','pbscope','linkuri','linkprotector','scope') {
                   1801:                                 $pbsave->{$launcher}{$item} = $pb{$item};
                   1802:                             }
                   1803:                         } else {
                   1804:                             $skip_passback->{$launcher} = 1;
                   1805:                         }
                   1806:                     }
                   1807:                     if (ref($symbs) eq 'ARRAY') {
                   1808:                         foreach my $symb (@{$symbs}) {
                   1809:                             if ((ref($weight{$symb}) eq 'HASH') && (ref($awarded{$symb}) eq 'HASH') &&
                   1810:                                 (ref($excused{$symb}) eq 'HASH')) {
                   1811:                                 foreach my $part (keys(%{$weight{$symb}})) {
                   1812:                                     if ($excused{$symb}{$part}) {
                   1813:                                         next;
                   1814:                                     }
                   1815:                                     my $partweight = $weight{$symb}{$part} eq '' ? 1 :
                   1816:                                                      $weight{$symb}{$part};
                   1817:                                     if ($awarded{$symb}{$part}) {
                   1818:                                         $total_by_symb{$symb} += $partweight * $awarded{$symb}{$part};
                   1819:                                     }
                   1820:                                     $possible_by_symb{$symb} += $partweight;
                   1821:                                 }
                   1822:                             }
                   1823:                         }
                   1824:                     }
                   1825:                     if ($context eq 'updatebypage') {
                   1826:                         my $ltigrade = {
                   1827:                                         'ltinum'     => $pb{'ltinum'},
                   1828:                                         'lti'        => $pb{'lti_in_use'},
                   1829:                                         'crsdef'     => $pb{'crsdef'},
                   1830:                                         'cid'        => $cdom.'_'.$cnum,
                   1831:                                         'uname'      => $uname,
                   1832:                                         'udom'       => $udom,
                   1833:                                         'uhome'      => $uhome,
1.802     raeburn  1834:                                         'usec'       => $usec,
1.798     raeburn  1835:                                         'pbid'       => $pbid,
                   1836:                                         'pburl'      => $pburl,
                   1837:                                         'pbtype'     => $pb{'type'},
                   1838:                                         'pbscope'    => $pb{'pbscope'},
                   1839:                                         'pbmap'      => $pb{'map'},
                   1840:                                         'pbsymb'     => $pb{'symb'},
                   1841:                                         'format'     => $pb{'scoretype'},
                   1842:                                         'scope'      => $pb{'scope'},
                   1843:                                         'clientip'   => $pb{'clientip'},
1.799     raeburn  1844:                                         'linkprot'   => $pb{'linkprotector'}.':'.$pb{'linkuri'},
1.798     raeburn  1845:                                         'total_s'    => \%total_by_symb,
                   1846:                                         'possible_s' => \%possible_by_symb,
                   1847:                         };
1.801     raeburn  1848:                         push(@Apache::grades::ltipassback,$ltigrade);
1.798     raeburn  1849:                         next;
                   1850:                     }
                   1851:                     my ($total,$possible);
                   1852:                     if ($pb{'pbscope'} eq 'resource') {
                   1853:                         $total = $total_by_symb{$pb{'symb'}};
                   1854:                         $possible = $possible_by_symb{$pb{'symb'}};
                   1855:                     } elsif (($pb{'pbscope'} eq 'map') || ($pb{'pbscope'} eq 'nonrec')) {
                   1856:                         ($total,$possible) =
1.806     raeburn  1857:                             &Apache::lonhomework::get_lti_score($uname,$udom,$usec,$pb{'map'},$pb{'pbscope'},
1.798     raeburn  1858:                                                                 \%total_by_symb,\%possible_by_symb);
                   1859:                     }
                   1860:                     if (!$possible) {
                   1861:                         $total = 0;
                   1862:                         $possible = 1;
                   1863:                     }
                   1864:                     my ($sent,$score,$code,$result) =
                   1865:                         &LONCAPA::ltiutils::send_grade($cdom,$cnum,$pb{'crsdef'},$pb{'type'},$pb{'ltinum'},
                   1866:                                                        $pb{'keynum'},$pbid,$pburl,$pb{'scoretype'},$pb{'sigmethod'},
                   1867:                                                        $pb{'msgformat'},$total,$possible);
                   1868:                     my $no_passback;
                   1869:                     if ($sent) {
                   1870:                         if ($code == 200) {
                   1871:                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
                   1872:                             my $store = {
                   1873:                                 'score' => $score,
                   1874:                                 'ip' => $pb{'ip'},
                   1875:                                 'host' => $pb{'lonhost'},
                   1876:                                 'protector' => $pb{'linkprotector'},
                   1877:                                 'deeplink' => $pb{'linkuri'},
                   1878:                                 'scope' => $pb{'scope'},
                   1879:                                 'url' => $pburl,
                   1880:                                 'id' => $pbid,
                   1881:                                 'clientip' => $pb{'clientip'},
                   1882:                                 'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
                   1883:                             };
                   1884:                             my $value='';
                   1885:                             foreach my $key (keys(%{$store})) {
                   1886:                                  $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
                   1887:                             }
                   1888:                             $value=~s/\&$//;
                   1889:                             &Apache::lonnet::courselog(&escape($pb{'linkuri'}).':'.$uname.':'.$udom.':EXPORT:'.$value);
1.807     raeburn  1890:                             &Apache::lonnet::store_userdata({'score' => $score},$launcher,$namespace,$udom,$uname,$pb{'ip'});
1.798     raeburn  1891:                         } else {
                   1892:                             $no_passback = 1;
                   1893:                         }
                   1894:                     } else {
                   1895:                         $no_passback = 1;
                   1896:                     }
                   1897:                     if ($no_passback) {
                   1898:                         &Apache::lonnet::log($udom,$uname,$uhome,$no_passback." score: $score; total: $total; possible: $possible");
                   1899:                         my $ltigrade = {
                   1900:                            'ltinum'   => $pb{'ltinum'},
                   1901:                            'lti'      => $pb{'lti_in_use'},
                   1902:                            'crsdef'   => $pb{'crsdef'},
                   1903:                            'cid'      => $cdom.'_'.$cnum,
                   1904:                            'uname'    => $uname,
                   1905:                            'udom'     => $udom,
                   1906:                            'uhome'    => $uhome,
                   1907:                            'pbid'     => $pbid,
                   1908:                            'pburl'    => $pburl,
                   1909:                            'pbtype'   => $pb{'type'},
                   1910:                            'pbscope'  => $pb{'pbscope'},
                   1911:                            'pbmap'    => $pb{'map'},
                   1912:                            'pbsymb'   => $pb{'symb'},
                   1913:                            'format'   => $pb{'scoretype'},
                   1914:                            'scope'    => $pb{'scope'},
                   1915:                            'clientip' => $pb{'clientip'},
1.799     raeburn  1916:                            'linkprot' => $pb{'linkprotector'}.':'.$pb{'linkuri'},
1.798     raeburn  1917:                            'total'    => $total,
                   1918:                            'possible' => $possible,
                   1919:                            'score'    => $score,
                   1920:                         };
                   1921:                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1922:                     }
                   1923:                 }
                   1924:             }
                   1925:         }
                   1926:     }
                   1927:     return;
                   1928: }
                   1929: 
                   1930: sub common_passback_info {
                   1931:     my %pbc = (
                   1932:                sigmethod => 'HMAC-SHA1',
                   1933:                type      => 'linkprot',
                   1934:                clientip  => &Apache::lonnet::get_requestor_ip(),
                   1935:                lonhost   => $Apache::lonnet::perlvar{'lonHostID'},
                   1936:                ip        => &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}),
                   1937:              );
                   1938:     return %pbc;
                   1939: }
                   1940: 
1.44      ng       1941: #--- This is called by a number of programs.
                   1942: #--- Called from the Grading Menu - View/Grade an individual student
                   1943: #--- Also called directly when one clicks on the subm button 
                   1944: #    on the problem page.
1.30      ng       1945: sub listStudents {
1.773     raeburn  1946:     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1947: 
1.747     raeburn  1948:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1949:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1950:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1951:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1952:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www      1953:     unless ($submitonly) {
1.766     raeburn  1954:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www      1955:     }
1.49      albertel 1956: 
1.632     www      1957:     my $result='';
1.623     www      1958:     my $res_error;
1.773     raeburn  1959:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   1960: 
                   1961:     my $table;
                   1962:     if (ref($partlist) eq 'ARRAY') {
                   1963:         if (scalar(@$partlist) > 1 ) {
                   1964:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1965:         } elsif ($divforres) {
                   1966:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1967:         } else {
                   1968:             $table = '<br clear="all" />';
                   1969:         }
                   1970:     }
1.49      albertel 1971: 
1.796     raeburn  1972:     $request->print(&checkselect_js());
1.597     wenzelju 1973:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1974: 
                   1975:     function reLoadList(formname) {
1.112     ng       1976: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1977: 	formname.command.value = 'submission';
                   1978: 	formname.submit();
                   1979:     }
1.45      ng       1980: LISTJAVASCRIPT
                   1981: 
1.118     ng       1982:     &commonJSfunctions($request);
1.41      ng       1983:     $request->print($result);
1.39      ng       1984: 
1.154     albertel 1985:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.773     raeburn  1986: 	"\n".$table;
                   1987: 
1.561     bisitz   1988:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn  1989:     unless ($is_tool) {
                   1990:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1991:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1992:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1993:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1994:                       .&Apache::lonhtmlcommon::row_closure();
                   1995:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1996:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1997:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1998:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1999:                       .&Apache::lonhtmlcommon::row_closure();
                   2000:     }
1.485     albertel 2001: 
1.442     banghart 2002:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   2003:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 2004:     $env{'form.Status'} = $saveStatus;
1.745     raeburn  2005:     my %optiontext;
                   2006:     if ($is_tool) {
                   2007:         %optiontext = &Apache::lonlocal::texthash (
                   2008:                           lastonly => 'last transaction',
                   2009:                           last     => 'last transaction with details',
                   2010:                           datesub  => 'all transactions',
                   2011:                           all      => 'all transactions with details',
                   2012:                       );
                   2013:     } else {
                   2014:         %optiontext = &Apache::lonlocal::texthash (
                   2015:                           lastonly => 'last submission',
                   2016:                           last     => 'last submission with details',
                   2017:                           datesub  => 'all submissions',
                   2018:                           all      => 'all submissions with details',
                   2019:                       );
                   2020:     }
1.773     raeburn  2021:     my $submission_options =
1.592     bisitz   2022:         '<span class="LC_nobreak">'.
1.624     www      2023:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  2024:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   2025:         '<span class="LC_nobreak">'.
                   2026:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  2027:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   2028:         '<span class="LC_nobreak">'.
1.628     www      2029:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  2030:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   2031:         '<span class="LC_nobreak">'.
                   2032:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  2033:         $optiontext{'all'}.'</label></span>';
                   2034:     my $viewtitle;
                   2035:     if ($is_tool) {
                   2036:         $viewtitle = &mt('View Transactions');
                   2037:     } else {
                   2038:         $viewtitle = &mt('View Submissions');
                   2039:     }
1.773     raeburn  2040:     my ($compmsg,$nocompmsg);
                   2041:     $nocompmsg = ' checked="checked"';
                   2042:     if ($numessay) {
                   2043:         $compmsg = $nocompmsg;
                   2044:         $nocompmsg = '';
                   2045:     }
1.745     raeburn  2046:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.780     raeburn  2047:                   .$submission_options;
                   2048: # Check if any gradable
                   2049:     my $showmore;
                   2050:     if ($perm{'mgr'}) {
                   2051:         my @sections;
                   2052:         if ($env{'request.course.sec'} ne '') {
                   2053:             @sections = ($env{'request.course.sec'});
1.783     raeburn  2054:         } elsif ($env{'form.section'} eq '') {
                   2055:             @sections = ('all');
1.780     raeburn  2056:         } else {
                   2057:             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   2058:         }
                   2059:         if (grep(/^all$/,@sections)) {
                   2060:             $showmore = 1;
                   2061:         } else {
                   2062:             foreach my $sec (@sections) {
                   2063:                 if (&canmodify($sec)) {
                   2064:                     $showmore = 1;
                   2065:                     last;
                   2066:                 }
                   2067:             }
                   2068:         }
                   2069:     }
                   2070: 
                   2071:     if ($showmore) {
                   2072:         $gradeTable .=
                   2073:                    &Apache::lonhtmlcommon::row_closure()
1.773     raeburn  2074:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   2075:                   .'<span class="LC_nobreak">'
                   2076:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   2077:                   .&mt('No').('&nbsp;'x2).'</label>'
                   2078:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   2079:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   2080:                   .&Apache::lonhtmlcommon::row_closure();
                   2081: 
1.780     raeburn  2082:         $gradeTable .= 
                   2083:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   2084:                   .'<select name="increment">'
                   2085:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   2086:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   2087:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   2088:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773     raeburn  2089:                   .'</select>';
1.780     raeburn  2090:     }
1.485     albertel 2091:     $gradeTable .= 
1.432     banghart 2092:         &build_section_inputs().
1.45      ng       2093: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 2094: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       2095: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      2096:     if (exists($env{'form.Status'})) {
1.784     raeburn  2097: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng       2098:     } else {
1.773     raeburn  2099:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2100:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   2101:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773     raeburn  2102:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       2103:     }
1.773     raeburn  2104:     if ($numessay) {
                   2105:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2106:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   2107:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  2108:     }
1.773     raeburn  2109:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
                   2110:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  2111:     my $regrademsg;
                   2112:     if ($is_tool) {
                   2113:         $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.");
                   2114:     } else {
                   2115:         $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.");
                   2116:     }
1.561     bisitz   2117:     $gradeTable .= '<p>'
1.745     raeburn  2118:                   .$regrademsg."\n"
1.561     bisitz   2119:                   .'<input type="hidden" name="command" value="processGroup" />'
                   2120:                   .'</p>';
1.249     albertel 2121: 
                   2122: # checkall buttons
                   2123:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       2124:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   2125:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   2126:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 2127:     $gradeTable.=&check_buttons();
1.450     banghart 2128:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 2129:     $gradeTable.= &Apache::loncommon::start_data_table().
                   2130: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       2131:     my $loop = 0;
                   2132:     while ($loop < 2) {
1.485     albertel 2133: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   2134: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      2135: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 2136: 	    foreach my $part (sort(@$partlist)) {
                   2137: 		my $display_part=
                   2138: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   2139: 		$gradeTable.=
                   2140: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       2141: 	    }
1.301     albertel 2142: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 2143: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       2144: 	}
                   2145: 	$loop++;
1.126     ng       2146: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       2147:     }
1.474     albertel 2148:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       2149: 
1.45      ng       2150:     my $ctr = 0;
1.294     albertel 2151:     foreach my $student (sort 
                   2152: 			 {
                   2153: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2154: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2155: 			     }
                   2156: 			     return $a cmp $b;
                   2157: 			 }
                   2158: 			 (keys(%$fullname))) {
1.41      ng       2159: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2160: 
1.110     ng       2161: 	my %status = ();
1.301     albertel 2162: 
                   2163: 	if ($submitonly eq 'queued') {
                   2164: 	    my %queue_status = 
                   2165: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2166: 							$udom,$uname);
                   2167: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2168: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   2169: 	}
                   2170: 
1.618     www      2171: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 2172: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2173: 	    my $submitted = 0;
1.164     albertel 2174: 	    my $graded = 0;
1.248     albertel 2175: 	    my $incorrect = 0;
1.110     ng       2176: 	    foreach (keys(%status)) {
1.145     albertel 2177: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2178: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   2179: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   2180: 		
1.110     ng       2181: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2182: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 2183: 		    $submitted = 0;
1.150     albertel 2184: 		    my ($part)=split(/\./,$partid);
1.110     ng       2185: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 2186: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       2187: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   2188: 		}
1.41      ng       2189: 	    }
1.248     albertel 2190: 	    
1.156     albertel 2191: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2192: 				     $submitonly eq 'incorrect' ||
                   2193: 				     $submitonly eq 'graded'));
1.248     albertel 2194: 	    next if (!$graded && ($submitonly eq 'graded'));
                   2195: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2196: 	}
1.34      ng       2197: 
1.45      ng       2198: 	$ctr++;
1.249     albertel 2199: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 2200:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 2201: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 2202: 	    if ($ctr%2 ==1) {
                   2203: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   2204: 	    }
1.126     ng       2205: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   2206:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 2207:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   2208: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   2209: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 2210: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       2211: 
1.618     www      2212: 	    if ($submitonly ne 'all') {
1.524     raeburn  2213: 		foreach (sort(keys(%status))) {
1.485     albertel 2214: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   2215: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       2216: 		}
1.41      ng       2217: 	    }
1.126     ng       2218: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 2219: 	    if ($ctr%2 ==0) {
                   2220: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   2221: 	    }
1.41      ng       2222: 	}
                   2223:     }
1.110     ng       2224:     if ($ctr%2 ==1) {
1.126     ng       2225: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      2226: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       2227: 		foreach (@$partlist) {
                   2228: 		    $gradeTable.='<td>&nbsp;</td>';
                   2229: 		}
1.301     albertel 2230: 	    } elsif ($submitonly eq 'queued') {
                   2231: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       2232: 	    }
1.474     albertel 2233: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       2234:     }
                   2235: 
1.474     albertel 2236:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   2237:         '<input type="button" '.
                   2238:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   2239:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       2240:     if ($ctr == 0) {
1.96      albertel 2241: 	my $num_students=(scalar(keys(%$fullname)));
                   2242: 	if ($num_students eq 0) {
1.485     albertel 2243: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 2244: 	} else {
1.171     albertel 2245: 	    my $submissions='submissions';
                   2246: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   2247: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 2248: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 2249: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   2250: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 2251: 		    $num_students).
                   2252: 		'</span><br />';
1.96      albertel 2253: 	}
1.46      ng       2254:     } elsif ($ctr == 1) {
1.474     albertel 2255: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       2256:     }
                   2257:     $request->print($gradeTable);
1.44      ng       2258:     return '';
1.10      ng       2259: }
                   2260: 
1.796     raeburn  2261: #---- Called from the listStudents and the names_for_passback routines.
                   2262: 
                   2263: sub checkselect_js {
                   2264:     my ($formname) = @_;
                   2265:     if ($formname eq '') {
                   2266:         $formname = 'gradesub';
                   2267:     }
                   2268:     my %js_lt;
                   2269:     if ($formname eq 'passbackusers') {
                   2270:         %js_lt = &Apache::lonlocal::texthash (
                   2271:                      'multiple' => 'Please select a student or group of students before pushing the Save Scores button.',
                   2272:                      'single'   => 'Please select the student before pushing the Save Scores button.',
                   2273:                  );
                   2274:     } else {
                   2275:         %js_lt = &Apache::lonlocal::texthash (
                   2276:                      'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   2277:                      'single'   => 'Please select the student before clicking on the Next button.',
                   2278:                  );
                   2279:     }
                   2280:     &js_escape(\%js_lt);
                   2281:     return &Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT);
                   2282: 
                   2283:     function checkSelect(checkBox) {
                   2284:         var ctr=0;
                   2285:         var sense="";
                   2286:         var len = checkBox.length;
                   2287:         if (len == undefined) len = 1;
                   2288:         if (len > 1) {
                   2289:             for (var i=0; i<len; i++) {
                   2290:                 if (checkBox[i].checked) {
                   2291:                     ctr++;
                   2292:                 }
                   2293:             }
                   2294:             sense = '$js_lt{'multiple'}';
                   2295:         } else {
                   2296:             if (checkBox.checked) {
                   2297:                 ctr = 1;
                   2298:             }
                   2299:             sense = '$js_lt{'single'}';
                   2300:         }
                   2301:         if (ctr == 0) {
                   2302:             alert(sense);
                   2303:             return false;
                   2304:         }
                   2305:         document.$formname.submit();
                   2306:     }
                   2307: LISTJAVASCRIPT
                   2308: 
                   2309: }
1.249     albertel 2310: 
                   2311: sub check_script {
1.766     raeburn  2312:     my ($form,$type) = @_;
                   2313:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 2314:     function checkall() {
                   2315:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2316:             ele = document.forms.'.$form.'.elements[i];
                   2317:             if (ele.name == "'.$type.'") {
                   2318:             document.forms.'.$form.'.elements[i].checked=true;
                   2319:                                        }
                   2320:         }
                   2321:     }
                   2322: 
                   2323:     function checksec() {
                   2324:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2325:             ele = document.forms.'.$form.'.elements[i];
                   2326:            string = document.forms.'.$form.'.chksec.value;
                   2327:            if
                   2328:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   2329:               document.forms.'.$form.'.elements[i].checked=true;
                   2330:             }
                   2331:         }
                   2332:     }
                   2333: 
                   2334: 
                   2335:     function uncheckall() {
                   2336:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2337:             ele = document.forms.'.$form.'.elements[i];
                   2338:             if (ele.name == "'.$type.'") {
                   2339:             document.forms.'.$form.'.elements[i].checked=false;
                   2340:                                        }
                   2341:         }
                   2342:     }
                   2343: 
1.597     wenzelju 2344: '."\n");
1.249     albertel 2345:     return $chkallscript;
                   2346: }
                   2347: 
                   2348: sub check_buttons {
1.485     albertel 2349:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   2350:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   2351:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 2352:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   2353:     return $buttons;
                   2354: }
                   2355: 
1.44      ng       2356: #     Displays the submissions for one student or a group of students
1.34      ng       2357: sub processGroup {
1.766     raeburn  2358:     my ($request,$symb) = @_;
1.41      ng       2359:     my $ctr        = 0;
1.155     albertel 2360:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       2361:     my $total      = scalar(@stuchecked)-1;
1.45      ng       2362: 
1.396     banghart 2363:     foreach my $student (@stuchecked) {
                   2364: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 2365: 	$env{'form.student'}        = $uname;
                   2366: 	$env{'form.userdom'}        = $udom;
                   2367: 	$env{'form.fullname'}       = $fullname;
1.619     www      2368: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2369: 	$ctr++;
                   2370:     }
                   2371:     return '';
1.35      ng       2372: }
1.34      ng       2373: 
1.44      ng       2374: #------------------------------------------------------------------------------------
                   2375: #
                   2376: #-------------------------- Next few routines handles grading by student, essentially
                   2377: #                           handles essay response type problem/part
                   2378: #
                   2379: #--- Javascript to handle the submission page functionality ---
                   2380: sub sub_page_js {
                   2381:     my $request = shift;
1.736     damieng  2382:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   2383:     &js_escape(\$alertmsg);
1.597     wenzelju 2384:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       2385:     function updateRadio(formname,id,weight) {
1.125     ng       2386: 	var gradeBox = formname["GD_BOX"+id];
                   2387: 	var radioButton = formname["RADVAL"+id];
                   2388: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       2389: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       2390: 	gradeBox.value = pts;
                   2391: 	var resetbox = false;
                   2392: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  2393: 	    alert("$alertmsg"+pts);
1.71      ng       2394: 	    for (var i=0; i<radioButton.length; i++) {
                   2395: 		if (radioButton[i].checked) {
                   2396: 		    gradeBox.value = i;
                   2397: 		    resetbox = true;
                   2398: 		}
                   2399: 	    }
                   2400: 	    if (!resetbox) {
                   2401: 		formtextbox.value = "";
                   2402: 	    }
                   2403: 	    return;
1.44      ng       2404: 	}
1.71      ng       2405: 
                   2406: 	if (pts > weight) {
                   2407: 	    var resp = confirm("You entered a value ("+pts+
                   2408: 			       ") greater than the weight for the part. Accept?");
                   2409: 	    if (resp == false) {
1.125     ng       2410: 		gradeBox.value = oldpts;
1.71      ng       2411: 		return;
                   2412: 	    }
1.44      ng       2413: 	}
1.13      albertel 2414: 
1.71      ng       2415: 	for (var i=0; i<radioButton.length; i++) {
                   2416: 	    radioButton[i].checked=false;
                   2417: 	    if (pts == i && pts != "") {
                   2418: 		radioButton[i].checked=true;
                   2419: 	    }
                   2420: 	}
                   2421: 	updateSelect(formname,id);
1.125     ng       2422: 	formname["stores"+id].value = "0";
1.41      ng       2423:     }
1.5       albertel 2424: 
1.72      ng       2425:     function writeBox(formname,id,pts) {
1.125     ng       2426: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2427: 	if (checkSolved(formname,id) == 'update') {
                   2428: 	    gradeBox.value = pts;
                   2429: 	} else {
1.125     ng       2430: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       2431: 	    gradeBox.value = oldpts;
1.125     ng       2432: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       2433: 	    for (var i=0; i<radioButton.length; i++) {
                   2434: 		radioButton[i].checked=false;
1.72      ng       2435: 		if (i == oldpts) {
1.71      ng       2436: 		    radioButton[i].checked=true;
                   2437: 		}
                   2438: 	    }
1.41      ng       2439: 	}
1.125     ng       2440: 	formname["stores"+id].value = "0";
1.71      ng       2441: 	updateSelect(formname,id);
                   2442: 	return;
1.41      ng       2443:     }
1.44      ng       2444: 
1.71      ng       2445:     function clearRadBox(formname,id) {
                   2446: 	if (checkSolved(formname,id) == 'noupdate') {
                   2447: 	    updateSelect(formname,id);
                   2448: 	    return;
                   2449: 	}
1.125     ng       2450: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       2451: 	for (var i=0; i<gradeSelect.length; i++) {
                   2452: 	    if (gradeSelect[i].selected) {
                   2453: 		var selectx=i;
                   2454: 	    }
                   2455: 	}
1.125     ng       2456: 	var stores = formname["stores"+id];
1.71      ng       2457: 	if (selectx == stores.value) { return };
1.125     ng       2458: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2459: 	gradeBox.value = "";
1.125     ng       2460: 	var radioButton = formname["RADVAL"+id];
1.71      ng       2461: 	for (var i=0; i<radioButton.length; i++) {
                   2462: 	    radioButton[i].checked=false;
                   2463: 	}
                   2464: 	stores.value = selectx;
                   2465:     }
1.5       albertel 2466: 
1.71      ng       2467:     function checkSolved(formname,id) {
1.125     ng       2468: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       2469: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   2470: 	    if (!reply) {return "noupdate";}
1.120     ng       2471: 	    formname.overRideScore.value = 'yes';
1.41      ng       2472: 	}
1.71      ng       2473: 	return "update";
1.13      albertel 2474:     }
1.71      ng       2475: 
                   2476:     function updateSelect(formname,id) {
1.125     ng       2477: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       2478: 	return;
1.41      ng       2479:     }
1.33      ng       2480: 
1.121     ng       2481: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       2482:     function checksubmit(formname,val,total,parttot) {
1.121     ng       2483: 	formname.gradeOpt.value = val;
1.71      ng       2484: 	if (val == "Save & Next") {
                   2485: 	    for (i=0;i<=total;i++) {
                   2486: 		for (j=0;j<parttot;j++) {
1.125     ng       2487: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       2488: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2489: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       2490: 			if (points == "") {
1.125     ng       2491: 			    var name = formname["name"+i].value;
1.129     ng       2492: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   2493: 			    var resp = confirm("You did not assign a score for "+studentID+
                   2494: 					       ", part "+partid+". Continue?");
1.71      ng       2495: 			    if (resp == false) {
1.125     ng       2496: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       2497: 				return false;
                   2498: 			    }
                   2499: 			}
                   2500: 		    }
                   2501: 		}
                   2502: 	    }
                   2503: 	}
1.120     ng       2504: 	formname.submit();
                   2505:     }
                   2506: 
1.71      ng       2507: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   2508:     function checkSubmitPage(formname,total) {
                   2509: 	noscore = new Array(100);
                   2510: 	var ptr = 0;
                   2511: 	for (i=1;i<total;i++) {
1.125     ng       2512: 	    var partid = formname["q_"+i].value;
1.127     ng       2513: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2514: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   2515: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       2516: 		if (points == "" && status != "correct_by_student") {
                   2517: 		    noscore[ptr] = i;
                   2518: 		    ptr++;
                   2519: 		}
                   2520: 	    }
                   2521: 	}
                   2522: 	if (ptr != 0) {
                   2523: 	    var sense = ptr == 1 ? ": " : "s: ";
                   2524: 	    var prolist = "";
                   2525: 	    if (ptr == 1) {
                   2526: 		prolist = noscore[0];
                   2527: 	    } else {
                   2528: 		var i = 0;
                   2529: 		while (i < ptr-1) {
                   2530: 		    prolist += noscore[i]+", ";
                   2531: 		    i++;
                   2532: 		}
                   2533: 		prolist += "and "+noscore[i];
                   2534: 	    }
                   2535: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   2536: 	    if (resp == false) {
                   2537: 		return false;
                   2538: 	    }
                   2539: 	}
1.45      ng       2540: 
1.71      ng       2541: 	formname.submit();
                   2542:     }
                   2543: SUBJAVASCRIPT
                   2544: }
1.45      ng       2545: 
1.773     raeburn  2546: #--- javascript for grading message center
                   2547: sub sub_grademessage_js {
1.71      ng       2548:     my $request = shift;
1.80      ng       2549:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       2550:     &commonJSfunctions($request);
1.350     albertel 2551: 
1.629     www      2552:     my $inner_js_msg_central= (<<INNERJS);
                   2553: <script type="text/javascript">
1.350     albertel 2554:     function checkInput() {
                   2555:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   2556:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   2557:       var usrctr = document.msgcenter.usrctr.value;
                   2558:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   2559:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   2560: 
                   2561:       var msgchk = "";
                   2562:       if (document.msgcenter.subchk.checked) {
                   2563:          msgchk = "msgsub,";
                   2564:       }
                   2565:       var includemsg = 0;
                   2566:       for (var i=1; i<=nmsg; i++) {
                   2567:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   2568:           var frmmsg = document.msgcenter["msg"+i];
                   2569:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   2570:           var showflg = opener.document.SCORE["shownOnce"+i];
                   2571:           showflg.value = "1";
                   2572:           var chkbox = document.msgcenter["msgn"+i];
                   2573:           if (chkbox.checked) {
                   2574:              msgchk += "savemsg"+i+",";
                   2575:              includemsg = 1;
                   2576:           }
                   2577:       }
                   2578:       if (document.msgcenter.newmsgchk.checked) {
                   2579:          msgchk += "newmsg"+usrctr;
                   2580:          includemsg = 1;
                   2581:       }
                   2582:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   2583:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   2584:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   2585:       includemsg.value = msgchk;
                   2586: 
                   2587:       self.close()
                   2588: 
                   2589:     }
1.629     www      2590: </script>
1.350     albertel 2591: INNERJS
                   2592: 
1.773     raeburn  2593:     my $start_page_msg_central =
1.351     albertel 2594:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   2595: 				       {'js_ready'  => 1,
                   2596: 					'only_body' => 1,
                   2597: 					'bgcolor'   =>'#FFFFFF',});
1.773     raeburn  2598:     my $end_page_msg_central =
1.350     albertel 2599: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   2600: 
1.219     www      2601:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 2602:     $docopen=~s/^document\.//;
1.773     raeburn  2603: 
1.736     damieng  2604:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  2605:                 comp => 'Compose Message for: ',
                   2606:                 incl => 'Include',
1.656     raeburn  2607:                 type => 'Type',
1.652     raeburn  2608:                 subj => 'Subject',
                   2609:                 mesa => 'Message',
                   2610:                 new  => 'New',
                   2611:                 save => 'Save',
                   2612:                 canc => 'Cancel',
                   2613:              );
1.736     damieng  2614:     &html_escape(\%html_js_lt);
                   2615:     &js_escape(\%html_js_lt);
1.597     wenzelju 2616:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       2617: 
1.44      ng       2618: //===================== Script to view submitted by ==================
                   2619:   function viewSubmitter(submitter) {
                   2620:     document.SCORE.refresh.value = "on";
                   2621:     document.SCORE.NCT.value = "1";
                   2622:     document.SCORE.unamedom0.value = submitter;
                   2623:     document.SCORE.submit();
                   2624:     return;
                   2625:   }
                   2626: 
                   2627: //====================== Script for composing message ==============
1.80      ng       2628:    // preload images
                   2629:    img1 = new Image();
                   2630:    img1.src = "$iconpath/mailbkgrd.gif";
                   2631:    img2 = new Image();
                   2632:    img2.src = "$iconpath/mailto.gif";
                   2633: 
1.44      ng       2634:   function msgCenter(msgform,usrctr,fullname) {
                   2635:     var Nmsg  = msgform.savemsgN.value;
                   2636:     savedMsgHeader(Nmsg,usrctr,fullname);
                   2637:     var subject = msgform.msgsub.value;
1.127     ng       2638:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       2639:     re = /msgsub/;
                   2640:     var shwsel = "";
                   2641:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       2642:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   2643:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       2644:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       2645: 	var testmsg = "savemsg"+i+",";
                   2646: 	re = new RegExp(testmsg,"g");
1.44      ng       2647: 	shwsel = "";
                   2648: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       2649: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       2650: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       2651: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   2652: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       2653:     }
1.125     ng       2654:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       2655:     shwsel = "";
                   2656:     re = /newmsg/;
                   2657:     if (re.test(msgchk)) { shwsel = "checked" }
                   2658:     newMsg(newmsg,shwsel);
                   2659:     msgTail(); 
                   2660:     return;
                   2661:   }
                   2662: 
1.123     ng       2663:   function checkEntities(strx) {
                   2664:     if (strx.length == 0) return strx;
                   2665:     var orgStr = ["&", "<", ">", '"']; 
                   2666:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   2667:     var counter = 0;
                   2668:     while (counter < 4) {
                   2669: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   2670: 	counter++;
                   2671:     }
                   2672:     return strx;
                   2673:   }
                   2674: 
                   2675:   function strReplace(strx, orgStr, newStr) {
                   2676:     return strx.split(orgStr).join(newStr);
                   2677:   }
                   2678: 
1.44      ng       2679:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       2680:     var height = 70*Nmsg+250;
1.44      ng       2681:     if (height > 600) {
                   2682: 	height = 600;
                   2683:     }
1.118     ng       2684:     var xpos = (screen.width-600)/2;
                   2685:     xpos = (xpos < 0) ? '0' : xpos;
                   2686:     var ypos = (screen.height-height)/2-30;
                   2687:     ypos = (ypos < 0) ? '0' : ypos;
                   2688: 
1.668     www      2689:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       2690:     pWin.focus();
                   2691:     pDoc = pWin.document;
1.219     www      2692:     pDoc.$docopen;
1.351     albertel 2693:     pDoc.write('$start_page_msg_central');
1.76      ng       2694: 
                   2695:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   2696:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  2697:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       2698: 
1.676     golterma 2699:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  2700:     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       2701: }
                   2702:     function displaySubject(msg,shwsel) {
1.76      ng       2703:     pDoc = pWin.document;
1.676     golterma 2704:     pDoc.write("<tr>");
                   2705:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2706:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 2707:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       2708: }
                   2709: 
1.72      ng       2710:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       2711:     pDoc = pWin.document;
1.676     golterma 2712:     pDoc.write("<tr>");
                   2713:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 2714:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   2715:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2716: }
                   2717: 
                   2718:   function newMsg(newmsg,shwsel) {
1.76      ng       2719:     pDoc = pWin.document;
1.676     golterma 2720:     pDoc.write("<tr>");
                   2721:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2722:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 2723:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2724: }
                   2725: 
                   2726:   function msgTail() {
1.76      ng       2727:     pDoc = pWin.document;
1.676     golterma 2728:     //pDoc.write("<\\/table>");
1.465     albertel 2729:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  2730:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   2731:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 2732:     pDoc.write("<\\/form>");
1.351     albertel 2733:     pDoc.write('$end_page_msg_central');
1.128     ng       2734:     pDoc.close();
1.44      ng       2735: }
                   2736: 
1.773     raeburn  2737: SUBJAVASCRIPT
                   2738: }
                   2739: 
                   2740: #--- javascript for essay type problem --
                   2741: sub sub_page_kw_js {
                   2742:     my $request = shift;
                   2743: 
                   2744:     unless ($env{'form.compmsg'}) {
                   2745:         &commonJSfunctions($request);
                   2746:     }
                   2747: 
                   2748:     my $inner_js_highlight_central= (<<INNERJS);
                   2749: <script type="text/javascript">
                   2750:     function updateChoice(flag) {
                   2751:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   2752:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   2753:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   2754:       opener.document.SCORE.refresh.value = "on";
                   2755:       if (opener.document.SCORE.keywords.value!=""){
                   2756:          opener.document.SCORE.submit();
                   2757:       }
                   2758:       self.close()
                   2759:     }
                   2760: </script>
                   2761: INNERJS
                   2762: 
                   2763:     my $start_page_highlight_central =
                   2764:         &Apache::loncommon::start_page('Highlight Central',
                   2765:                                        $inner_js_highlight_central,
                   2766:                                        {'js_ready'  => 1,
                   2767:                                         'only_body' => 1,
                   2768:                                         'bgcolor'   =>'#FFFFFF',});
                   2769:     my $end_page_highlight_central =
                   2770:         &Apache::loncommon::end_page({'js_ready' => 1});
                   2771: 
                   2772:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   2773:     $docopen=~s/^document\.//;
                   2774: 
                   2775:     my %js_lt = &Apache::lonlocal::texthash(
                   2776:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   2777:                 plse => 'Please select a word or group of words from document and then click this link.',
                   2778:                 adds => 'Add selection to keyword list? Edit if desired.',
                   2779:                 col1 => 'red',
                   2780:                 col2 => 'green',
                   2781:                 col3 => 'blue',
                   2782:                 siz1 => 'normal',
                   2783:                 siz2 => '+1',
                   2784:                 siz3 => '+2',
                   2785:                 sty1 => 'normal',
                   2786:                 sty2 => 'italic',
                   2787:                 sty3 => 'bold',
                   2788:              );
                   2789:     my %html_js_lt = &Apache::lonlocal::texthash(
                   2790:                 save => 'Save',
                   2791:                 canc => 'Cancel',
                   2792:                 kehi => 'Keyword Highlight Options',
                   2793:                 txtc => 'Text Color',
                   2794:                 font => 'Font Size',
                   2795:                 fnst => 'Font Style',
                   2796:              );
                   2797:     &js_escape(\%js_lt);
                   2798:     &html_escape(\%html_js_lt);
                   2799:     &js_escape(\%html_js_lt);
                   2800:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   2801: 
                   2802: //===================== Show list of keywords ====================
                   2803:   function keywords(formname) {
                   2804:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   2805:     if (nret==null) return;
                   2806:     formname.keywords.value = nret;
                   2807: 
                   2808:     if (formname.keywords.value != "") {
                   2809:         formname.refresh.value = "on";
                   2810:         formname.submit();
                   2811:     }
                   2812:     return;
                   2813:   }
                   2814: 
                   2815: //===================== Script to add keyword(s) ==================
                   2816:   function getSel() {
                   2817:     if (document.getSelection) txt = document.getSelection();
                   2818:     else if (document.selection) txt = document.selection.createRange().text;
                   2819:     else return;
                   2820:     if (typeof(txt) != 'string') {
                   2821:         txt = String(txt);
                   2822:     }
                   2823:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   2824:     if (cleantxt=="") {
                   2825:         alert("$js_lt{'plse'}");
                   2826:         return;
                   2827:     }
                   2828:     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   2829:     if (nret==null) return;
                   2830:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   2831:     if (document.SCORE.keywords.value != "") {
                   2832:         document.SCORE.refresh.value = "on";
                   2833:         document.SCORE.submit();
                   2834:     }
                   2835:     return;
                   2836:   }
                   2837: 
1.44      ng       2838: //====================== Script for keyword highlight options ==============
                   2839:   function kwhighlight() {
                   2840:     var kwclr    = document.SCORE.kwclr.value;
                   2841:     var kwsize   = document.SCORE.kwsize.value;
                   2842:     var kwstyle  = document.SCORE.kwstyle.value;
                   2843:     var redsel = "";
                   2844:     var grnsel = "";
                   2845:     var blusel = "";
1.736     damieng  2846:     var txtcol1 = "$js_lt{'col1'}";
                   2847:     var txtcol2 = "$js_lt{'col2'}";
                   2848:     var txtcol3 = "$js_lt{'col3'}";
                   2849:     var txtsiz1 = "$js_lt{'siz1'}";
                   2850:     var txtsiz2 = "$js_lt{'siz2'}";
                   2851:     var txtsiz3 = "$js_lt{'siz3'}";
                   2852:     var txtsty1 = "$js_lt{'sty1'}";
                   2853:     var txtsty2 = "$js_lt{'sty2'}";
                   2854:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   2855:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   2856:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   2857:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       2858:     var sznsel = "";
                   2859:     var sz1sel = "";
                   2860:     var sz2sel = "";
1.718     bisitz   2861:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   2862:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   2863:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       2864:     var synsel = "";
                   2865:     var syisel = "";
                   2866:     var sybsel = "";
1.718     bisitz   2867:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   2868:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   2869:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       2870:     highlightCentral();
1.718     bisitz   2871:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   2872:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   2873:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       2874:     highlightend();
                   2875:     return;
                   2876:   }
                   2877: 
                   2878:   function highlightCentral() {
1.76      ng       2879: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       2880:     var xpos = (screen.width-400)/2;
                   2881:     xpos = (xpos < 0) ? '0' : xpos;
                   2882:     var ypos = (screen.height-330)/2-30;
                   2883:     ypos = (ypos < 0) ? '0' : ypos;
                   2884: 
1.206     albertel 2885:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       2886:     hwdWin.focus();
                   2887:     var hDoc = hwdWin.document;
1.219     www      2888:     hDoc.$docopen;
1.351     albertel 2889:     hDoc.write('$start_page_highlight_central');
1.76      ng       2890:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  2891:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       2892: 
1.718     bisitz   2893:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  2894:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       2895:   }
                   2896: 
                   2897:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       2898:     var hDoc = hwdWin.document;
1.718     bisitz   2899:     hDoc.write("<tr>");
1.76      ng       2900:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2901:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       2902:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2903:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       2904:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2905:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 2906:     hDoc.write("<\\/tr>");
1.44      ng       2907:   }
                   2908: 
                   2909:   function highlightend() { 
1.76      ng       2910:     var hDoc = hwdWin.document;
1.718     bisitz   2911:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  2912:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   2913:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 2914:     hDoc.write("<\\/form>");
1.351     albertel 2915:     hDoc.write('$end_page_highlight_central');
1.128     ng       2916:     hDoc.close();
1.44      ng       2917:   }
                   2918: 
                   2919: SUBJAVASCRIPT
                   2920: }
                   2921: 
1.349     albertel 2922: sub get_increment {
1.348     bowersj2 2923:     my $increment = $env{'form.increment'};
                   2924:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   2925:         $increment != .1) {
                   2926:         $increment = 1;
                   2927:     }
                   2928:     return $increment;
                   2929: }
                   2930: 
1.585     bisitz   2931: sub gradeBox_start {
                   2932:     return (
                   2933:         &Apache::loncommon::start_data_table()
                   2934:        .&Apache::loncommon::start_data_table_header_row()
                   2935:        .'<th>'.&mt('Part').'</th>'
                   2936:        .'<th>'.&mt('Points').'</th>'
                   2937:        .'<th>&nbsp;</th>'
                   2938:        .'<th>'.&mt('Assign Grade').'</th>'
                   2939:        .'<th>'.&mt('Weight').'</th>'
                   2940:        .'<th>'.&mt('Grade Status').'</th>'
                   2941:        .&Apache::loncommon::end_data_table_header_row()
                   2942:     );
                   2943: }
                   2944: 
                   2945: sub gradeBox_end {
                   2946:     return (
                   2947:         &Apache::loncommon::end_data_table()
                   2948:     );
                   2949: }
1.71      ng       2950: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   2951: sub gradeBox {
1.322     albertel 2952:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 2953:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2954: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2955:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2956:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2957:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2958:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2959:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.811   ! raeburn  2960: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt,
        !          2961: 		                       $$record{'resource.'.$partid.'.latefrac'}));
1.695     bisitz   2962:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2963:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2964:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2965: 				       [$partid]);
                   2966:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2967:     if ($last_resets{$partid}) {
                   2968:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2969:     }
1.695     bisitz   2970:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2971:     my $ctr = 0;
1.348     bowersj2 2972:     my $thisweight = 0;
1.349     albertel 2973:     my $increment = &get_increment();
1.485     albertel 2974: 
                   2975:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2976:     while ($thisweight<=$wgt) {
1.532     bisitz   2977: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2978:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2979: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2980: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2981: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2982:         $thisweight += $increment;
1.71      ng       2983: 	$ctr++;
                   2984:     }
1.485     albertel 2985:     $radio.='</tr></table>';
                   2986: 
                   2987:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2988: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2989: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2990: 	$wgt.')" /></td>'."\n";
1.485     albertel 2991:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2992: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2993: 	' </td>'."\n";
                   2994:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2995: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2996:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2997: 	$line.='<option></option>'.
                   2998: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2999:     } else {
1.485     albertel 3000: 	$line.='<option selected="selected"></option>'.
                   3001: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       3002:     }
1.485     albertel 3003:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   3004: 
                   3005: 
                   3006:     $result .= 
1.695     bisitz   3007: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   3008:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   3009:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       3010:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   3011: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   3012: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  3013: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   3014:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   3015:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   3016:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   3017:         $aggtries.'" />'."\n";
1.582     raeburn  3018:     my $res_error;
                   3019:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   3020:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  3021:     if ($res_error) {
                   3022:         return &navmap_errormsg();
                   3023:     }
1.318     banghart 3024:     return $result;
                   3025: }
1.322     albertel 3026: 
                   3027: sub handback_box {
1.623     www      3028:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773     raeburn  3029:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   3030:     return unless ($numessay);
1.323     banghart 3031:     my (@respids);
1.652     raeburn  3032:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 3033:     foreach my $part_response_id (@part_response_id) {
                   3034:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 3035:         if ($part eq $partid) {
1.375     albertel 3036:             push(@respids,$resp);
1.323     banghart 3037:         }
                   3038:     }
1.318     banghart 3039:     my $result;
1.323     banghart 3040:     foreach my $respid (@respids) {
1.322     albertel 3041: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   3042: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3043: 	next if (!@$files);
1.654     raeburn  3044: 	my $file_counter = 0;
1.313     banghart 3045: 	foreach my $file (@$files) {
1.368     banghart 3046: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  3047:                 $file_counter++;
1.368     banghart 3048:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  3049:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 3050:     	        $file_disp = "$name.$ext";
                   3051:     	        $file = $file_path.$file_disp;
                   3052:     	        $result.=&mt('Return commented version of [_1] to student.',
                   3053:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   3054:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  3055:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 3056: 	    }
1.322     albertel 3057: 	}
1.654     raeburn  3058:         if ($file_counter) {
                   3059:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   3060:                        '<span class="LC_info">'.
                   3061:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   3062:         }
1.313     banghart 3063:     }
1.318     banghart 3064:     return $result;    
1.71      ng       3065: }
1.44      ng       3066: 
1.58      albertel 3067: sub show_problem {
1.382     albertel 3068:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 3069:     my $rendered;
1.382     albertel 3070:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 3071:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 3072:     if ($mode eq 'both' or $mode eq 'text') {
                   3073: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 3074: 						       $env{'request.course.id'},
                   3075: 						       undef,\%form);
1.144     albertel 3076:     }
1.58      albertel 3077:     if ($removeform) {
                   3078: 	$rendered=~s|<form(.*?)>||g;
                   3079: 	$rendered=~s|</form>||g;
1.374     albertel 3080: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 3081:     }
1.144     albertel 3082:     my $companswer;
                   3083:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 3084: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 3085: 	$companswer=
                   3086: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   3087: 						    $env{'request.course.id'},
                   3088: 						    %form);
1.144     albertel 3089:     }
1.58      albertel 3090:     if ($removeform) {
                   3091: 	$companswer=~s|<form(.*?)>||g;
                   3092: 	$companswer=~s|</form>||g;
1.144     albertel 3093: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 3094:     }
1.671     raeburn  3095:     my $renderheading = &mt('View of the problem');
                   3096:     my $answerheading = &mt('Correct answer');
                   3097:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   3098:         my $stu_fullname = $env{'form.fullname'};
                   3099:         if ($stu_fullname eq '') {
                   3100:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3101:         }
                   3102:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   3103:         if ($forwhom ne '') {
                   3104:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   3105:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   3106:         }
                   3107:     }
1.468     albertel 3108:     $rendered=
1.588     bisitz   3109:         '<div class="LC_Box">'
1.671     raeburn  3110:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   3111:        .$rendered
                   3112:        .'</div>';
1.468     albertel 3113:     $companswer=
1.588     bisitz   3114:         '<div class="LC_Box">'
1.671     raeburn  3115:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   3116:        .$companswer
                   3117:        .'</div>';
1.468     albertel 3118:     my $result;
1.144     albertel 3119:     if ($mode eq 'both') {
1.588     bisitz   3120:         $result=$rendered.$companswer;
1.144     albertel 3121:     } elsif ($mode eq 'text') {
1.588     bisitz   3122:         $result=$rendered;
1.144     albertel 3123:     } elsif ($mode eq 'answer') {
1.588     bisitz   3124:         $result=$companswer;
1.144     albertel 3125:     }
1.71      ng       3126:     return $result;
1.58      albertel 3127: }
1.397     albertel 3128: 
1.396     banghart 3129: sub files_exist {
                   3130:     my ($r, $symb) = @_;
                   3131:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   3132:     foreach my $student (@students) {
                   3133:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 3134:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3135: 					      $udom,$uname);
1.792     raeburn  3136:         my ($string)= &get_last_submission(\%record);
1.397     albertel 3137:         foreach my $submission (@$string) {
                   3138:             my ($partid,$respid) =
                   3139: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3140:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   3141: 					   \%record);
                   3142:             return 1 if (@$files);
1.396     banghart 3143:         }
                   3144:     }
1.397     albertel 3145:     return 0;
1.396     banghart 3146: }
1.397     albertel 3147: 
1.394     banghart 3148: sub download_all_link {
                   3149:     my ($r,$symb) = @_;
1.621     www      3150:     unless (&files_exist($r, $symb)) {
1.766     raeburn  3151:         $r->print(&mt('There are currently no submitted documents.'));
                   3152:         return;
1.621     www      3153:     }
1.395     albertel 3154:     my $all_students = 
                   3155: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   3156: 
                   3157:     my $parts =
                   3158: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   3159: 
1.394     banghart 3160:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  3161:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   3162:                              'cgi.'.$identifier.'.symb' => $symb,
                   3163:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 3164:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   3165: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      3166:     return;
                   3167: }
                   3168: 
                   3169: sub submit_download_link {
                   3170:     my ($request,$symb) = @_;
                   3171:     if (!$symb) { return ''; }
1.750     raeburn  3172:     my $res_error;
1.773     raeburn  3173:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   3174:         &response_type($symb,\$res_error);
                   3175:     if ($res_error) {
                   3176:         $request->print(&mt('An error occurred retrieving response types'));
                   3177:         return;
                   3178:     }
                   3179:     unless ($numessay) {
                   3180:         $request->print(&mt('No essayresponse items found'));
                   3181:         return;
1.750     raeburn  3182:     }
1.773     raeburn  3183:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3184:     if (@chosenparts) {
                   3185:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   3186:                                           undef,undef,1));
1.750     raeburn  3187:     }
1.773     raeburn  3188:     if ($numessay) {
1.750     raeburn  3189:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   3190:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3191:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   3192:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   3193:         if (ref($fullname) eq 'HASH') {
                   3194:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   3195:             if (@students) {
                   3196:                 @{$env{'form.stuinfo'}} = @students;
1.773     raeburn  3197:                 if ($numdropbox) {
1.750     raeburn  3198:                     &download_all_link($request,$symb);
1.773     raeburn  3199:                 } else {
                   3200:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  3201:                 }
1.773     raeburn  3202: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  3203: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   3204:             } else {
                   3205:                 $request->print(&mt('No students match the criteria you selected'));
                   3206:             }
                   3207:         } else {
                   3208:             $request->print(&mt('Could not retrieve student information'));
                   3209:         }
                   3210:     } else {
                   3211:         $request->print(&mt('No essayresponse items found'));
                   3212:     }
                   3213:     return;
1.394     banghart 3214: }
1.395     albertel 3215: 
1.432     banghart 3216: sub build_section_inputs {
                   3217:     my $section_inputs;
                   3218:     if ($env{'form.section'} eq '') {
                   3219:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   3220:     } else {
                   3221:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 3222:         foreach my $section (@sections) {
1.432     banghart 3223:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   3224:         }
                   3225:     }
                   3226:     return $section_inputs;
                   3227: }
                   3228: 
1.44      ng       3229: # --------------------------- show submissions of a student, option to grade 
                   3230: sub submission {
1.773     raeburn  3231:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 3232:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   3233:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   3234:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3235:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      3236: 
1.324     albertel 3237:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773     raeburn  3238:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  3239:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  3240:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 3241: 
                   3242:     if (!&canview($usec)) {
1.712     bisitz   3243:         $request->print(
                   3244:             '<span class="LC_warning">'.
1.713     bisitz   3245:             &mt('Unable to view requested student.').
1.712     bisitz   3246:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3247:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3248:             '</span>');
1.104     albertel 3249: 	return;
                   3250:     }
                   3251: 
1.773     raeburn  3252:     my $res_error;
                   3253:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   3254:         &response_type($symb,\$res_error);
                   3255:     if ($res_error) {
                   3256:         $request->print(&navmap_errormsg());
                   3257:         return;
                   3258:     }
                   3259: 
1.257     albertel 3260:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  3261:     unless ($is_tool) { 
                   3262:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   3263:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   3264:     }
1.773     raeburn  3265:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   3266:         $env{'form.compmsg'} = 1;
                   3267:     }
1.257     albertel 3268:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 3269:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   3270: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       3271: 	'/check.gif" height="16" border="0" />';
1.41      ng       3272: 
                   3273:     # header info
                   3274:     if ($counter == 0) {
1.773     raeburn  3275:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3276:         if (@chosenparts) {
                   3277:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   3278:         } elsif ($divforres) {
                   3279:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   3280:         } else {
                   3281:             $request->print('<br clear="all" />');
                   3282:         }
1.41      ng       3283: 	&sub_page_js($request);
1.773     raeburn  3284:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   3285: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       3286: 
1.44      ng       3287: 	# option to display problem, only once else it cause problems 
                   3288:         # with the form later since the problem has a form.
1.257     albertel 3289: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 3290: 	    my $mode;
1.257     albertel 3291: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 3292: 		$mode='both';
1.257     albertel 3293: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 3294: 		$mode='text';
1.257     albertel 3295: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 3296: 		$mode='answer';
                   3297: 	    }
1.329     albertel 3298: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 3299: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       3300: 	}
1.441     www      3301: 
1.41      ng       3302: 	my %keyhash = ();
1.773     raeburn  3303: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       3304: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 3305: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   3306: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773     raeburn  3307: 	}
                   3308: 	# kwclr is the only variable that is guaranteed not to be blank
                   3309: 	# if this subroutine has been called once.
                   3310: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 3311: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3312: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   3313: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   3314: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   3315: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773     raeburn  3316: 	}
                   3317: 	if ($env{'form.compmsg'}) {
                   3318: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      3319: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 3320: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       3321: 	}
1.773     raeburn  3322: 
1.257     albertel 3323: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 3324: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 3325: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       3326: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 3327: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       3328: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       3329: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       3330: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   3331: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 3332: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3333: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   3334: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   3335: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773     raeburn  3336: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 3337: 			&build_section_inputs().
1.326     albertel 3338: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       3339: 			'<input type="hidden" name="NCT"'.
1.257     albertel 3340: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773     raeburn  3341: 	if ($env{'form.compmsg'}) {
                   3342: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   3343: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   3344: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   3345: 	}
                   3346: 	if ($numessay) {
1.257     albertel 3347: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   3348: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   3349: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773     raeburn  3350: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       3351: 	}
1.773     raeburn  3352: 
1.41      ng       3353: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 3354: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       3355: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       3356: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 3357: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       3358: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       3359: 		'" />'."\n".
                   3360: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       3361: 	    $cts++;
                   3362: 	}
                   3363: 	$request->print($prnmsg);
1.32      ng       3364: 
1.773     raeburn  3365: 	if ($numessay) {
1.652     raeburn  3366: 
                   3367:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   3368:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  3369:                           keyw => 'Keyword Options',
1.655     raeburn  3370:                           list => 'List',
1.652     raeburn  3371:                           past => 'Paste Selection to List',
1.661     www      3372:                           high => 'Highlight Attribute',
1.773     raeburn  3373:                      );
1.88      www      3374: #
                   3375: # Print out the keyword options line
                   3376: #
1.718     bisitz   3377: 	    $request->print(
                   3378:                 '<div class="LC_columnSection">'
                   3379:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   3380:                .&Apache::lonhtmlcommon::funclist_from_array(
                   3381:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   3382:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   3383:  class="page">'.$lt{'past'}.'</a>',
                   3384:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   3385:                     {legend => $lt{'keyw'}})
                   3386:                .'</fieldset></div>'
                   3387:             );
                   3388: 
1.88      www      3389: #
                   3390: # Load the other essays for similarity check
                   3391: #
1.753     raeburn  3392:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   3393:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3394:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3395:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3396:                 if ($cdom ne '' && $cnum ne '') {
                   3397:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   3398:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   3399:                         my $apath = $1.'_'.$id;
                   3400:                         $apath=~s/\W/\_/gs;
                   3401:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   3402:                     }
                   3403:                 }
                   3404:             } else {
                   3405: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   3406: 	        $apath=&escape($apath);
                   3407: 	        $apath=~s/\W/\_/gs;
                   3408:                 &init_old_essays($symb,$apath,$adom,$aname);
                   3409:             }
1.41      ng       3410:         }
                   3411:     }
1.44      ng       3412: 
1.441     www      3413: # This is where output for one specific student would start
1.592     bisitz   3414:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   3415:     $request->print(
                   3416:         "\n\n"
                   3417:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   3418:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   3419:        ."\n"
                   3420:     );
1.441     www      3421: 
1.592     bisitz   3422:     # Show additional functions if allowed
                   3423:     if ($perm{'vgr'}) {
                   3424:         $request->print(
                   3425:             &Apache::loncommon::track_student_link(
1.708     bisitz   3426:                 'View recent activity',
1.592     bisitz   3427:                 $uname,$udom,'check')
                   3428:            .' '
                   3429:         );
                   3430:     }
                   3431:     if ($perm{'opa'}) {
                   3432:         $request->print(
                   3433:             &Apache::loncommon::pprmlink(
                   3434:                 &mt('Set/Change parameters'),
                   3435:                 $uname,$udom,$symb,'check'));
                   3436:     }
                   3437: 
                   3438:     # Show Problem
1.257     albertel 3439:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 3440: 	my $mode;
1.257     albertel 3441: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 3442: 	    $mode='both';
1.257     albertel 3443: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 3444: 	    $mode='text';
1.257     albertel 3445: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 3446: 	    $mode='answer';
                   3447: 	}
1.329     albertel 3448: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 3449: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 3450:     }
1.144     albertel 3451: 
1.257     albertel 3452:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       3453: 
1.44      ng       3454:     # Display student info
1.41      ng       3455:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   3456: 
1.745     raeburn  3457:     my $boxtitle = &mt('Submissions');
                   3458:     if ($is_tool) {
                   3459:         $boxtitle = &mt('Transactions')
                   3460:     }
1.590     bisitz   3461:     my $result='<div class="LC_Box">'
1.745     raeburn  3462:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       3463:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   3464:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773     raeburn  3465:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   3466:         $result.='<p class="LC_info">'
                   3467:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   3468:                 ."</p>\n";
1.469     albertel 3469:     }
                   3470: 
1.773     raeburn  3471:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 3472:     my $fullname;
                   3473:     my $col_fullnames = [];
1.773     raeburn  3474:     if ($numessay) {
1.464     albertel 3475: 	(my $sub_result,$fullname,$col_fullnames)=
                   3476: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   3477: 				 $counter);
                   3478: 	$result.=$sub_result;
1.41      ng       3479:     }
1.44      ng       3480:     $request->print($result."\n");
1.773     raeburn  3481: 
1.44      ng       3482:     # print student answer/submission
1.773     raeburn  3483:     # Options are (1) Last submission only
                   3484:     #             (2) Last submission (with detailed information for that submission)
                   3485:     #             (3) All transactions (by date)
                   3486:     #             (4) The whole record (with detailed information for all transactions)
                   3487: 
1.793     raeburn  3488:     my ($lastsubonly,$partinfo) =
                   3489:         &show_last_submission($uname,$udom,$symb,$essayurl,$responseType,$env{'form.lastSub'},
                   3490:                               $is_tool,$fullname,\%record,\%coursedesc_by_cid);
                   3491:     $request->print($partinfo);
                   3492:     $request->print($lastsubonly);
                   3493: 
                   3494:     if ($env{'form.lastSub'} eq 'datesub') {
                   3495:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3496: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
                   3497:     }
                   3498:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   3499:         my $identifier = (&canmodify($usec)? $counter : '');
                   3500:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
                   3501: 								 $env{'request.course.id'},
                   3502: 								 $last,'.submission',
                   3503: 								 'Apache::grades::keywords_highlight',
                   3504:                                                                  $usec,$identifier));
                   3505:     }
                   3506:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   3507: 	.$udom.'" />'."\n");
                   3508:     # return if view submission with no grading option
                   3509:     if (!&canmodify($usec)) {
                   3510: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   3511: 	return;
                   3512:     } else {
                   3513: 	$request->print('</div>'."\n");
                   3514:     }
                   3515: 
                   3516:     # grading message center
                   3517: 
                   3518:     if ($env{'form.compmsg'}) {
                   3519:         my $result='<div class="LC_Box">'.
                   3520:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   3521:                    '<div class="LC_grade_message_center_body">';
                   3522:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   3523:         my $msgfor = $givenn.' '.$lastname;
                   3524:         if (scalar(@$col_fullnames) > 0) {
                   3525:             my $lastone = pop(@$col_fullnames);
                   3526:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   3527:         }
                   3528:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   3529:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   3530:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   3531:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   3532:                  ',\''.$msgfor.'\');" target="_self">'.
                   3533:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   3534:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   3535:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   3536:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   3537:                  '<br />&nbsp;('.
                   3538:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   3539:                  '</div></div>';
                   3540:         $request->print($result);
                   3541:     }
                   3542: 
                   3543:     my %seen = ();
                   3544:     my @partlist;
                   3545:     my @gradePartRespid;
                   3546:     my @part_response_id;
                   3547:     if ($is_tool) {
                   3548:         @part_response_id = ([0,'']);
                   3549:     } else {
                   3550:         @part_response_id = &flatten_responseType($responseType);
                   3551:     }
                   3552:     $request->print(
                   3553:         '<div class="LC_Box">'
                   3554:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
                   3555:     );
                   3556:     $request->print(&gradeBox_start());
                   3557:     foreach my $part_response_id (@part_response_id) {
                   3558:     	my ($partid,$respid) = @{ $part_response_id };
                   3559: 	my $part_resp = join('_',@{ $part_response_id });
                   3560: 	next if ($seen{$partid} > 0);
                   3561: 	$seen{$partid}++;
                   3562: 	push(@partlist,$partid);
                   3563: 	push(@gradePartRespid,$partid.'.'.$respid);
                   3564: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
                   3565:     }
                   3566:     $request->print(&gradeBox_end()); # </div>
                   3567:     $request->print('</div>');
                   3568: 
                   3569:     $request->print('<div class="LC_grade_info_links">');
                   3570:     $request->print('</div>');
                   3571: 
                   3572:     $result='<input type="hidden" name="partlist'.$counter.
                   3573: 	'" value="'.(join ":",@partlist).'" />'."\n";
                   3574:     $result.='<input type="hidden" name="gradePartRespid'.
                   3575: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
                   3576:     my $ctr = 0;
                   3577:     while ($ctr < scalar(@partlist)) {
                   3578: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   3579: 	    $partlist[$ctr].'" />'."\n";
                   3580: 	$ctr++;
                   3581:     }
                   3582:     $request->print($result.''."\n");
                   3583: 
                   3584: # Done with printing info for one student
                   3585: 
                   3586:     $request->print('</div>');#LC_grade_show_user
                   3587: 
                   3588: 
                   3589:     # print end of form
                   3590:     if ($counter == $total) {
                   3591:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
                   3592: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
                   3593: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
                   3594: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
                   3595: 	my $ntstu ='<select name="NTSTU">'.
                   3596: 	    '<option>1</option><option>2</option>'.
                   3597: 	    '<option>3</option><option>5</option>'.
                   3598: 	    '<option>7</option><option>10</option></select>'."\n";
                   3599: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
                   3600: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
                   3601:         $endform.=&mt('[_1]student(s)',$ntstu);
                   3602: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
                   3603: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
                   3604: 	    '<input type="button" value="'.&mt('Next').'" '.
                   3605: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
                   3606:         $endform.='<span class="LC_warning">'.
                   3607:                   &mt('(Next and Previous (student) do not save the scores.)').
                   3608:                   '</span>'."\n" ;
                   3609:         $endform.="<input type='hidden' value='".&get_increment().
                   3610:             "' name='increment' />";
                   3611: 	$endform.='</td></tr></table></form>';
                   3612: 	$request->print($endform);
                   3613:     }
                   3614:     return '';
                   3615: }
                   3616: 
                   3617: sub show_last_submission {
                   3618:     my ($uname,$udom,$symb,$essayurl,$responseType,$viewtype,$is_tool,$fullname,
                   3619:         $record,$coursedesc_by_cid) = @_;
1.792     raeburn  3620:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
1.793     raeburn  3621:         &get_last_submission($record,$is_tool);
1.468     albertel 3622: 
1.793     raeburn  3623:     my ($lastsubonly,$partinfo);
1.792     raeburn  3624:     if ($timestamp eq '') {
1.793     raeburn  3625:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>';
1.745     raeburn  3626:     } elsif ($is_tool) {
                   3627:         $lastsubonly =
                   3628:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3629:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$timestamp."</div>\n";
1.702     kruse    3630:     } else {
1.792     raeburn  3631:         my ($shownsubmdate,$showngradedate);
                   3632:         if ($lastsubmittime && $lastgradetime) {
                   3633:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
                   3634:             if ($lastgradetime > $lastsubmittime) {
                   3635:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
                   3636:              }
                   3637:         } else {
                   3638:             $shownsubmdate = $timestamp;
                   3639:         }
1.702     kruse    3640:         $lastsubonly =
                   3641:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3642:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
                   3643:         if ($showngradedate) {
                   3644:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
                   3645:         }
1.702     kruse    3646: 
1.793     raeburn  3647:         my %seenparts;
                   3648:         my @part_response_id = &flatten_responseType($responseType);
                   3649:         foreach my $part (@part_response_id) {
                   3650:             my ($partid,$respid) = @{ $part };
                   3651:             my $display_part=&get_display_part($partid,$symb);
                   3652:             if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   3653:                 if (exists($seenparts{$partid})) { next; }
                   3654:                 $seenparts{$partid}=1;
                   3655:                 $partinfo .=
1.702     kruse    3656:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3657:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   3658:                                '<a href="javascript:viewSubmitter(\''.
                   3659:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   3660:                                '\');" target="_self">'.
                   3661:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
1.793     raeburn  3662:                     '<br />';
                   3663:                 next;
                   3664:             }
                   3665:             my $responsetype = $responseType->{$partid}->{$respid};
                   3666:             if (!exists($record->{"resource.$partid.$respid.submission"})) {
1.702     kruse    3667:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   3668:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3669:                     ' <span class="LC_internal_info">'.
                   3670:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   3671:                     '</span>&nbsp; &nbsp;'.
1.793     raeburn  3672:                     '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   3673:                 next;
                   3674:             }
                   3675:             foreach my $submission (@$string) {
                   3676:                 my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3677:                 if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   3678:                 my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   3679:                 # Similarity check
1.702     kruse    3680:                 my $similar='';
                   3681:                 my ($type,$trial,$rndseed);
                   3682:                 if ($hide eq 'rand') {
                   3683:                     $type = 'randomizetry';
1.793     raeburn  3684:                     $trial = $record->{"resource.$partid.tries"};
                   3685:                     $rndseed = $record->{"resource.$partid.rndseed"};
1.702     kruse    3686:                 }
1.793     raeburn  3687:                 if ($env{'form.checkPlag'}) {
                   3688:                     my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   3689:                     &most_similar($uname,$udom,$symb,$subval);
                   3690:                     if ($osim) {
                   3691:                         $osim=int($osim*100.0);
1.702     kruse    3692:                         if ($hide eq 'anon') {
                   3693:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   3694:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   3695:                         } else {
1.793     raeburn  3696:                             $similar='<hr />';
1.753     raeburn  3697:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3698:                                 $similar .= '<h3><span class="LC_warning">'.
                   3699:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   3700:                                                 $osim,
                   3701:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3702:                                             '</span></h3>';
                   3703:                             } else {
                   3704:                                 my %old_course_desc;
                   3705:                                 if ($ocrsid ne '') {
1.793     raeburn  3706:                                     if (ref($coursedesc_by_cid->{$ocrsid}) eq 'HASH') {
                   3707:                                         %old_course_desc = %{$coursedesc_by_cid->{$ocrsid}};
1.753     raeburn  3708:                                     } else {
                   3709:                                         my $args;
                   3710:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   3711:                                             $args = {'one_time' => 1};
                   3712:                                         }
                   3713:                                         %old_course_desc =
                   3714:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
1.793     raeburn  3715:                                         $coursedesc_by_cid->{$ocrsid} = \%old_course_desc;
1.753     raeburn  3716:                                     }
                   3717:                                     $similar .=
                   3718:                                         '<h3><span class="LC_warning">'.
                   3719:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   3720:                                             $osim,
                   3721:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   3722:                                             $old_course_desc{'description'},
                   3723:                                             $old_course_desc{'num'},
                   3724:                                             $old_course_desc{'domain'}).
                   3725:                                         '</span></h3>';
                   3726:                                 } else {
                   3727:                                     $similar .=
                   3728:                                         '<h3><span class="LC_warning">'.
                   3729:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   3730:                                             $osim,
                   3731:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3732:                                         '</span></h3>';
                   3733:                                 }
                   3734:                             }
                   3735:                             $similar .= '<blockquote><i>'.
                   3736:                                         &keywords_highlight($oessay).
                   3737:                                         '</i></blockquote><hr />';
1.702     kruse    3738:                         }
1.793     raeburn  3739:                     }
                   3740:                 }
                   3741:                 my $order=&get_order($partid,$respid,$symb,$uname,$udom,
1.702     kruse    3742:                                      undef,$type,$trial,$rndseed);
1.793     raeburn  3743:                 if (($viewtype eq 'lastonly') ||
                   3744:                     ($viewtype eq 'datesub')  ||
                   3745:                     ($viewtype =~ /^(last|all)$/)) {
                   3746:                     my $display_part=&get_display_part($partid,$symb);
1.702     kruse    3747:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   3748:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3749:                         ' <span class="LC_internal_info">'.
                   3750:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   3751:                         '</span>&nbsp; &nbsp;';
1.793     raeburn  3752:                     my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3753:                     if (@$files) {
1.702     kruse    3754:                         if ($hide eq 'anon') {
                   3755:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   3756:                         } else {
                   3757:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   3758:                                         .'<br /><span class="LC_warning">';
                   3759:                             if(@$files == 1) {
                   3760:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  3761:                             } else {
1.702     kruse    3762:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   3763:                             }
1.774     raeburn  3764:                             $lastsubonly .= '</span>';
1.702     kruse    3765:                             foreach my $file (@$files) {
                   3766:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   3767:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  3768:                             }
                   3769:                         }
1.793     raeburn  3770:                         $lastsubonly.='<br />';
1.702     kruse    3771:                     }
                   3772:                     if ($hide eq 'anon') {
1.793     raeburn  3773:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
1.702     kruse    3774:                     } else {
1.774     raeburn  3775:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  3776:                         if ($draft) {
                   3777:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   3778:                         }
                   3779:                         $subval =
1.793     raeburn  3780:                             &cleanRecord($subval,$responsetype,$symb,$partid,
                   3781:                                          $respid,$record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  3782:                         if ($responsetype eq 'essay') {
                   3783:                             $subval =~ s{\n}{<br />}g;
                   3784:                         }
                   3785:                         $lastsubonly.=$subval."\n";
1.702     kruse    3786:                     }
1.774     raeburn  3787:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.793     raeburn  3788:                     $lastsubonly.='</div>';
                   3789:                 }
1.702     kruse    3790:             }
1.773     raeburn  3791:         }
1.793     raeburn  3792:         $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.118     ng       3793:     }
1.793     raeburn  3794:     return ($lastsubonly,$partinfo);
1.38      ng       3795: }
                   3796: 
1.464     albertel 3797: sub check_collaborators {
                   3798:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   3799:     my ($result,@col_fullnames);
                   3800:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   3801:     foreach my $part (keys(%$handgrade)) {
                   3802: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   3803: 					'.maxcollaborators',
                   3804: 					$symb,$udom,$uname);
                   3805: 	next if ($ncol <= 0);
                   3806: 	$part =~ s/\_/\./g;
                   3807: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   3808: 	my (@good_collaborators, @bad_collaborators);
                   3809: 	foreach my $possible_collaborator
1.630     www      3810: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 3811: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   3812: 	    next if ($possible_collaborator eq '');
1.631     www      3813: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 3814: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   3815: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   3816: 	    # Doing this grep allows 'fuzzy' specification
                   3817: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   3818: 			       keys(%$classlist));
                   3819: 	    if (! scalar(@matches)) {
                   3820: 		push(@bad_collaborators, $possible_collaborator);
                   3821: 	    } else {
                   3822: 		push(@good_collaborators, @matches);
                   3823: 	    }
                   3824: 	}
                   3825: 	if (scalar(@good_collaborators) != 0) {
1.630     www      3826: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 3827: 	    foreach my $name (@good_collaborators) {
                   3828: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   3829: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      3830: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 3831: 	    }
1.630     www      3832: 	    $result.='</ol><br />'."\n";
1.466     albertel 3833: 	    my ($part)=split(/\./,$part);
1.464     albertel 3834: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   3835: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   3836: 		"\n";
                   3837: 	}
                   3838: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 3839: 	    $result.='<div class="LC_warning">';
1.464     albertel 3840: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   3841: 	    $result .= '</div>';
                   3842: 	}         
                   3843: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 3844: 	    $result .= '<div class="LC_warning">';
1.464     albertel 3845: 	    $result .= &mt('This student has submitted too many '.
                   3846: 		'collaborators.  Maximum is [_1].',$ncol);
                   3847: 	    $result .= '</div>';
                   3848: 	}
                   3849:     }
                   3850:     return ($result,$fullname,\@col_fullnames);
                   3851: }
                   3852: 
1.44      ng       3853: #--- Retrieve the last submission for all the parts
1.38      ng       3854: sub get_last_submission {
1.745     raeburn  3855:     my ($returnhash,$is_tool)=@_;
1.792     raeburn  3856:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
1.119     ng       3857:     if ($$returnhash{'version'}) {
1.46      ng       3858: 	my %lasthash=();
1.792     raeburn  3859:         my %prevsolved=();
                   3860:         my %solved=();
                   3861: 	my $version;
1.119     ng       3862: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.792     raeburn  3863:             my %handgraded = ();
1.397     albertel 3864: 	    foreach my $key (sort(split(/\:/,
                   3865: 					$$returnhash{$version.':keys'}))) {
                   3866: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
1.792     raeburn  3867:                 if ($key =~ /\.([^.]+)\.regrader$/) {
                   3868:                     $handgraded{$1} = 1;
                   3869:                 } elsif ($key =~ /\.portfiles$/) {
                   3870:                     if (($$returnhash{$version.':'.$key} ne '') &&
                   3871:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
                   3872:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3873:                     }
                   3874:                 } elsif ($key =~ /\.submission$/) {
                   3875:                     if ($$returnhash{$version.':'.$key} ne '') {
                   3876:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3877:                     }
                   3878:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
                   3879:                     $prevsolved{$1} = $solved{$1};
                   3880:                     $solved{$1} = $lasthash{$key};
                   3881:                 }
                   3882:             }
                   3883:             foreach my $partid (keys(%handgraded)) {
                   3884:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
                   3885:                     (($solved{$partid} eq 'incorrect_by_override') ||
                   3886:                      ($solved{$partid} eq 'correct_by_override'))) {
                   3887:                     $lastgradetime = $$returnhash{$version.':timestamp'};
                   3888:                 }
                   3889:                 if ($solved{$partid} ne '') {
                   3890:                     $prevsolved{$partid} = $solved{$partid};
                   3891:                 }
1.46      ng       3892: 	    }
                   3893: 	}
1.795     raeburn  3894: #
                   3895: # Timestamp is for last transaction for this resource, which does not
                   3896: # necessarily correspond to the time of last submission for problem (or part).
                   3897: #
                   3898:         if ($lasthash{'timestamp'} ne '') {
                   3899:             $timestamp = &Apache::lonlocal::locallocaltime($lasthash{'timestamp'});
                   3900:         }
1.640     raeburn  3901:         my (%typeparts,%randombytry);
1.596     raeburn  3902:         my $showsurv = 
                   3903:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   3904:         foreach my $key (sort(keys(%lasthash))) {
                   3905:             if ($key =~ /\.type$/) {
                   3906:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  3907:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   3908:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  3909:                     my ($ign,@parts) = split(/\./,$key);
                   3910:                     pop(@parts);
1.641     raeburn  3911:                     my $id = join('.',@parts);
1.640     raeburn  3912:                     if ($lasthash{$key} eq 'randomizetry') {
                   3913:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   3914:                     } else {
                   3915:                         unless ($showsurv) {
                   3916:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   3917:                         }
1.596     raeburn  3918:                     }
                   3919:                     delete($lasthash{$key});
                   3920:                 }
                   3921:             }
                   3922:         }
                   3923:         my @hidden = keys(%typeparts);
1.640     raeburn  3924:         my @randomize = keys(%randombytry);
1.397     albertel 3925: 	foreach my $key (keys(%lasthash)) {
                   3926: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  3927:             my $hide;
                   3928:             if (@hidden) {
                   3929:                 foreach my $id (@hidden) {
                   3930:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  3931:                         $hide = 'anon';
1.596     raeburn  3932:                         last;
                   3933:                     }
                   3934:                 }
                   3935:             }
1.640     raeburn  3936:             unless ($hide) {
                   3937:                 if (@randomize) {
1.732     raeburn  3938:                     foreach my $id (@randomize) {
1.640     raeburn  3939:                         if ($key =~ /^\Q$id\E/) {
                   3940:                             $hide = 'rand';
                   3941:                             last;
                   3942:                         }
                   3943:                     }
                   3944:                 }
                   3945:             }
1.397     albertel 3946: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  3947: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   3948:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   3949:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   3950:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       3951: 	}
                   3952:     }
1.397     albertel 3953:     if (!@string) {
1.745     raeburn  3954:         my $msg;
                   3955:         if ($is_tool) {
1.747     raeburn  3956:             $msg = &mt('No grade passed back.');
1.745     raeburn  3957:         } else {
                   3958:             $msg = &mt('Nothing submitted - no attempts.');
                   3959:         }
1.397     albertel 3960: 	$string[0] =
1.745     raeburn  3961: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 3962:     }
1.792     raeburn  3963:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       3964: }
1.35      ng       3965: 
1.44      ng       3966: #--- High light keywords, with style choosen by user.
1.38      ng       3967: sub keywords_highlight {
1.44      ng       3968:     my $string    = shift;
1.257     albertel 3969:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   3970:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       3971:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 3972:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 3973:     foreach my $keyword (@keylist) {
                   3974: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       3975:     }
                   3976:     return $string;
1.38      ng       3977: }
1.36      ng       3978: 
1.671     raeburn  3979: # For Tasks provide a mechanism to display previous version for one specific student
                   3980: 
                   3981: sub show_previous_task_version {
                   3982:     my ($request,$symb) = @_;
                   3983:     if ($symb eq '') {
1.717     bisitz   3984:         $request->print(
                   3985:             '<span class="LC_error">'.
                   3986:             &mt('Unable to handle ambiguous references.').
                   3987:             '</span>');
1.671     raeburn  3988:         return '';
                   3989:     }
                   3990:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3991:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3992:     if (!&canview($usec)) {
1.712     bisitz   3993:         $request->print(
                   3994:             '<span class="LC_warning">'.
1.713     bisitz   3995:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   3996:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3997:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3998:             '</span>');
1.671     raeburn  3999:         return;
                   4000:     }
                   4001:     my $mode = 'both';
                   4002:     my $isTask = ($symb =~/\.task$/);
                   4003:     if ($isTask) {
                   4004:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   4005:             if ($env{'form.fullname'} eq '') {
                   4006:                 $env{'form.fullname'} =
                   4007:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   4008:             }
                   4009:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   4010:             $request->print("\n\n".
                   4011:                             '<div class="LC_grade_show_user">'.
                   4012:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   4013:                             '</h2>'."\n");
                   4014:             &Apache::lonxml::clear_problem_counter();
                   4015:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   4016:                             {'previousversion' => $env{'form.previousversion'} }));
                   4017:             $request->print("\n</div>");
                   4018:         }
                   4019:     }
                   4020:     return;
                   4021: }
                   4022: 
                   4023: sub choose_task_version_form {
                   4024:     my ($symb,$uname,$udom,$nomenu) = @_;
                   4025:     my $isTask = ($symb =~/\.task$/);
                   4026:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   4027:     if ($isTask) {
                   4028:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4029:                                               $udom,$uname);
                   4030:         if (($record{'resource.0.version'} eq '') ||
                   4031:             ($record{'resource.0.version'} < 2)) {
                   4032:             return ($record{'resource.0.version'},
                   4033:                     $record{'resource.0.version'},$result,$js);
                   4034:         } else {
                   4035:             $current = $record{'resource.0.version'};
                   4036:         }
                   4037:         if ($env{'form.previousversion'}) {
                   4038:             $displayed = $env{'form.previousversion'};
                   4039:             $rowtitle = &mt('Choose another version:')
                   4040:         } else {
                   4041:             $displayed = $current;
                   4042:             $rowtitle = &mt('Show earlier version:');
                   4043:         }
                   4044:         $result = '<div class="LC_left_float">';
                   4045:         my $list;
                   4046:         my $numversions = 0;
                   4047:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   4048:             if ($i == $current) {
                   4049:                 if (!$env{'form.previousversion'} || $nomenu) {
                   4050:                     next;
                   4051:                 } else {
                   4052:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   4053:                     $numversions ++;
                   4054:                 }
                   4055:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   4056:                 unless ($i == $env{'form.previousversion'}) {
                   4057:                     $numversions ++;
                   4058:                 }
                   4059:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   4060:             }
                   4061:         }
                   4062:         if ($numversions) {
                   4063:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   4064:             $result .=
                   4065:                 '<form name="getprev" method="post" action=""'.
                   4066:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   4067:                 &Apache::loncommon::start_data_table().
                   4068:                 &Apache::loncommon::start_data_table_row().
                   4069:                 '<th align="left">'.$rowtitle.'</th>'.
                   4070:                 '<td><select name="version">'.
                   4071:                 '<option>'.&mt('Select').'</option>'.
                   4072:                 $list.
                   4073:                 '</select></td>'.
                   4074:                 &Apache::loncommon::end_data_table_row();
                   4075:             unless ($nomenu) {
                   4076:                 $result .= &Apache::loncommon::start_data_table_row().
                   4077:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   4078:                 '<td><span class="LC_nobreak">'.
                   4079:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   4080:                 &mt('Yes').'</label>'.
                   4081:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   4082:                 '</span></td>'.
                   4083:                 &Apache::loncommon::end_data_table_row();
                   4084:             }
                   4085:             $result .=
                   4086:                 &Apache::loncommon::start_data_table_row().
                   4087:                 '<th align="left">&nbsp;</th>'.
                   4088:                 '<td>'.
                   4089:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   4090:                 '</td>'.
                   4091:                 &Apache::loncommon::end_data_table_row().
                   4092:                 &Apache::loncommon::end_data_table().
                   4093:                 '</form>';
                   4094:             $js = &previous_display_javascript($nomenu,$current);
                   4095:         } elsif ($displayed && $nomenu) {
                   4096:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   4097:         } else {
                   4098:             $result .= &mt('No previous versions to show for this student');
                   4099:         }
                   4100:         $result .= '</div>';
                   4101:     }
                   4102:     return ($current,$displayed,$result,$js);
                   4103: }
                   4104: 
                   4105: sub previous_display_javascript {
                   4106:     my ($nomenu,$current) = @_;
                   4107:     my $js = <<"JSONE";
                   4108: <script type="text/javascript">
                   4109: // <![CDATA[
                   4110: function previousVersion(uname,udom,symb) {
                   4111:     var current = '$current';
                   4112:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   4113:     var prevstr = new RegExp("^\\\\d+\$");
                   4114:     if (!prevstr.test(version)) {
                   4115:         return false;
                   4116:     }
                   4117:     var url = '';
                   4118:     if (version == current) {
                   4119:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   4120:     } else {
                   4121:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   4122:     }
                   4123: JSONE
                   4124:     if ($nomenu) {
                   4125:         $js .= <<"JSTWO";
                   4126:     document.location.href = url;
                   4127: JSTWO
                   4128:     } else {
                   4129:         $js .= <<"JSTHREE";
                   4130:     var newwin = 0;
                   4131:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   4132:         if (document.getprev.prevwin[i].checked == true) {
                   4133:             newwin = document.getprev.prevwin[i].value;
                   4134:         }
                   4135:     }
                   4136:     if (newwin == 1) {
                   4137:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   4138:         url = url+'&inhibitmenu=yes';
                   4139:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   4140:             previousWin = window.open(url,'',options,1);
                   4141:         } else {
                   4142:             previousWin.location.href = url;
                   4143:         }
                   4144:         previousWin.focus();
                   4145:         return false;
                   4146:     } else {
                   4147:         document.location.href = url;
                   4148:         return false;
                   4149:     }
                   4150: JSTHREE
                   4151:     }
                   4152:     $js .= <<"ENDJS";
                   4153:     return false;
                   4154: }
                   4155: // ]]>
                   4156: </script>
                   4157: ENDJS
                   4158: 
                   4159: }
                   4160: 
1.44      ng       4161: #--- Called from submission routine
1.38      ng       4162: sub processHandGrade {
1.608     www      4163:     my ($request,$symb) = @_;
1.324     albertel 4164:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 4165:     my $button = $env{'form.gradeOpt'};
                   4166:     my $ngrade = $env{'form.NCT'};
                   4167:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 4168:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4169:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.786     raeburn  4170:     my ($res_error,%queueable);
                   4171:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   4172:     if ($res_error) {
                   4173:         $request->print(&navmap_errormsg());
                   4174:         return;
                   4175:     } else {
                   4176:         foreach my $part (@{$partlist}) {
                   4177:             if (ref($responseType->{$part}) eq 'HASH') {
                   4178:                 foreach my $id (keys(%{$responseType->{$part}})) {
                   4179:                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   4180:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   4181:                         $queueable{$part} = 1;
                   4182:                         last;
                   4183:                     }
                   4184:                 }
                   4185:             }
                   4186:         }
                   4187:     }
1.301     albertel 4188: 
1.44      ng       4189:     if ($button eq 'Save & Next') {
1.798     raeburn  4190:         my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   4191:         my (%skip_passback,%pbsave,%pbcollab);
1.44      ng       4192: 	my $ctr = 0;
                   4193: 	while ($ctr < $ngrade) {
1.257     albertel 4194: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  4195: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
1.798     raeburn  4196:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable,\%needpb,\%skip_passback,\%pbsave);
1.71      ng       4197: 	    if ($errorflag eq 'no_score') {
                   4198: 		$ctr++;
                   4199: 		next;
                   4200: 	    }
1.104     albertel 4201: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   4202: 		$request->print(
                   4203:                     '<span class="LC_error">'
                   4204:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   4205:                    .'</span>');
1.104     albertel 4206: 		$ctr++;
                   4207: 		next;
                   4208: 	    }
1.726     raeburn  4209:             if ($numhidden) {
                   4210:                 $request->print(
                   4211:                     '<span class="LC_info">'
                   4212:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   4213:                    .'</span><br />');
                   4214:             }
1.257     albertel 4215: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       4216: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 4217: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   4218:             my ($feedurl,$showsymb) =
                   4219: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   4220: 	    my $messagetail;
1.62      albertel 4221: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      4222: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      4223: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  4224: 		$subject.=' ['.$restitle.']';
1.44      ng       4225: 		my (@msgnum) = split(/,/,$includemsg);
                   4226: 		foreach (@msgnum) {
1.257     albertel 4227: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       4228: 		}
1.80      ng       4229: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      4230: 		if ($env{'form.withgrades'.$ctr}) {
                   4231: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  4232: 		    $messagetail = " for <a href=\"".
1.605     www      4233: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  4234: 		}
                   4235: 		$msgstatus = 
                   4236:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   4237: 						     $message.$messagetail,
1.418     albertel 4238:                                                      undef,$feedurl,undef,
1.386     raeburn  4239:                                                      undef,undef,$showsymb,
                   4240:                                                      $restitle);
1.574     bisitz   4241: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  4242: 				$msgstatus.'<br />');
1.44      ng       4243: 	    }
1.257     albertel 4244: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 4245: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 4246: 		foreach my $collabstr (@collabstrs) {
                   4247: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 4248: 		    foreach my $collaborator (@collaborators) {
1.803     raeburn  4249: 			my ($errorflag,$pts,$wgt,$numchg,$numupdate) = 
1.324     albertel 4250: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.803     raeburn  4251: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 4252: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 4253: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 4254: 			    next;
1.798     raeburn  4255: 			} else {
1.803     raeburn  4256:                             if ($numchg || $numupdate) { 
                   4257:                                 $pbcollab{$collaborator}{$part} = [$pts,$wgt];
                   4258:                             }
1.798     raeburn  4259:                             if ($message ne '') {
1.800     raeburn  4260: 			        my ($baseurl,$showsymb) = 
                   4261: 				    &get_feedurl_and_symb($symb,$collaborator,
1.801     raeburn  4262: 						          $udom);
1.800     raeburn  4263: 			        if ($env{'form.withgrades'.$ctr}) {
                   4264: 				    $messagetail = " for <a href=\"".
                   4265:                                         $baseurl."?symb=$showsymb\">$restitle</a>";
                   4266: 			        }
                   4267: 			        $msgstatus =
                   4268: 				    &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.150     albertel 4269: 			    }
1.800     raeburn  4270: 		        }
1.44      ng       4271: 		    }
                   4272: 		}
                   4273: 	    }
                   4274: 	    $ctr++;
                   4275: 	}
1.798     raeburn  4276:         if ((keys(%pbcollab)) && (keys(%needpb))) {
1.803     raeburn  4277:             foreach my $user (keys(%pbcollab)) {
                   4278:                 my ($clbuname,$clbudom) = split(/:/,$user);
                   4279:                 my $clbusec = &Apache::lonnet::getsection($clbudom,$clbuname,$cdom.'_'.$cnum); 
                   4280:                 if (ref($pbcollab{$user}) eq 'HASH') {
                   4281:                     my @clparts = keys(%{$pbcollab{$user}});
                   4282:                     if (@clparts) {
                   4283:                         my $navmap = Apache::lonnavmaps::navmap->new($clbuname,$clbudom,$clbusec);
                   4284:                         if (ref($navmap)) {
                   4285:                             my $res = $navmap->getBySymb($symb);
                   4286:                             if (ref($res)) {
                   4287:                                 my $partlist = $res->parts();
                   4288:                                 if (ref($partlist) eq 'ARRAY') {
                   4289:                                     my (%weights,%awardeds,%excuseds);
                   4290:                                     foreach my $part (@{$partlist}) {
                   4291:                                         if ($res->status($part) eq $res->EXCUSED) {
                   4292:                                             $excuseds{$symb}{$part} = 1;
                   4293:                                         } else { 
                   4294:                                             $excuseds{$symb}{$part} = '';
                   4295:                                         }
                   4296:                                         if ((exists($pbcollab{$user}{$part})) && (ref($pbcollab{$user}{$part}) eq 'ARRAY')) {
                   4297:                                             my $pts = $pbcollab{$user}{$part}[0];
                   4298:                                             my $wt = $pbcollab{$user}{$part}[1];
                   4299:                                             if ($wt) {
                   4300:                                                 $awardeds{$symb}{$part} = $pts/$wt;
                   4301:                                                 $weights{$symb}{$part} = $wt;
                   4302:                                             } else {
                   4303:                                                 $awardeds{$symb}{$part} = 0;
                   4304:                                                 $weights{$symb}{$part} = 0;
                   4305:                                             }
                   4306:                                         } else {
                   4307:                                             $awardeds{$symb}{$part} = $res->awarded($part);
                   4308:                                             $weights{$symb}{$part} = $res->weight($part);
                   4309:                                         }
                   4310:                                     }
                   4311:                                     &process_passbacks('handgrade',[$symb],$cdom,$cnum,$clbudom,$clbuname,$clbusec,\%weights,
                   4312:                                                        \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   4313:                                 }
                   4314:                             }
                   4315:                         }
                   4316:                     }
                   4317:                 }
                   4318:             }
1.798     raeburn  4319:         }
1.44      ng       4320:     }
                   4321: 
1.773     raeburn  4322:     my %keyhash = ();
                   4323:     if ($numessay) {
1.119     ng       4324: 	# Keywords sorted in alphabatical order
1.257     albertel 4325: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   4326: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  4327: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 4328: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   4329: 	$env{'form.keywords'} = join(' ',@keywords);
                   4330: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   4331: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   4332: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   4333: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   4334: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  4335:     }
1.119     ng       4336: 
1.773     raeburn  4337:     if ($env{'form.compmsg'}) {
1.119     ng       4338: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 4339: 	# New messages are saved in env for the next student.
1.119     ng       4340: 	# All messages are saved in nohist_handgrade.db
                   4341: 	my ($ctr,$idx) = (1,1);
1.257     albertel 4342: 	while ($ctr <= $env{'form.savemsgN'}) {
                   4343: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   4344: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       4345: 		$idx++;
                   4346: 	    }
                   4347: 	    $ctr++;
1.41      ng       4348: 	}
1.119     ng       4349: 	$ctr = 0;
                   4350: 	while ($ctr < $ngrade) {
1.257     albertel 4351: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  4352: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4353: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4354: 	        $idx++;
1.119     ng       4355: 	    }
                   4356: 	    $ctr++;
1.41      ng       4357: 	}
1.257     albertel 4358: 	$env{'form.savemsgN'} = --$idx;
                   4359: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       4360:     }
1.773     raeburn  4361:     if (($numessay) || ($env{'form.compmsg'})) {
                   4362:         my $putresult = &Apache::lonnet::put
                   4363:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   4364:     }
                   4365: 
1.44      ng       4366:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 4367:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   4368:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       4369: 	my ($ctr,$total) = (0,0);
                   4370: 	while ($ctr < $ngrade) {
1.257     albertel 4371: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       4372: 	    $ctr++;
                   4373: 	}
1.257     albertel 4374: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       4375: 	$ctr = 0;
                   4376: 	while ($ctr < $total) {
1.257     albertel 4377: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   4378: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   4379: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      4380: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       4381: 	    $ctr++;
                   4382: 	}
                   4383: 	return '';
                   4384:     }
1.36      ng       4385: 
1.44      ng       4386:     # Get the next/previous one or group of students
1.257     albertel 4387:     my $firststu = $env{'form.unamedom0'};
                   4388:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       4389:     my $ctr = 2;
1.41      ng       4390:     while ($laststu eq '') {
1.257     albertel 4391: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       4392: 	$ctr++;
                   4393: 	$laststu = $firststu if ($ctr > $ngrade);
                   4394:     }
1.44      ng       4395: 
1.41      ng       4396:     my (@parsedlist,@nextlist);
                   4397:     my ($nextflg) = 0;
1.524     raeburn  4398:     foreach my $item (sort 
1.294     albertel 4399: 	     {
                   4400: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4401: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4402: 		 }
                   4403: 		 return $a cmp $b;
                   4404: 	     } (keys(%$fullname))) {
1.41      ng       4405: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  4406: 	    push(@parsedlist,$item);
1.41      ng       4407: 	}
1.524     raeburn  4408: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       4409: 	if ($button eq 'Previous') {
1.524     raeburn  4410: 	    last if ($item eq $firststu);
                   4411: 	    push(@parsedlist,$item);
1.41      ng       4412: 	}
                   4413:     }
                   4414:     $ctr = 0;
                   4415:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   4416:     foreach my $student (@parsedlist) {
1.257     albertel 4417: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       4418: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 4419: 	
                   4420: 	if ($submitonly eq 'queued') {
                   4421: 	    my %queue_status = 
                   4422: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4423: 							$udom,$uname);
                   4424: 	    next if (!defined($queue_status{'gradingqueue'}));
                   4425: 	}
                   4426: 
1.156     albertel 4427: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 4428: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 4429: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 4430: 	    my $submitted = 0;
1.248     albertel 4431: 	    my $ungraded = 0;
                   4432: 	    my $incorrect = 0;
1.524     raeburn  4433: 	    foreach my $item (keys(%status)) {
                   4434: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   4435: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   4436: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   4437: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 4438: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   4439: 		    $submitted = 0;
                   4440: 		}
1.41      ng       4441: 	    }
1.156     albertel 4442: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   4443: 				     $submitonly eq 'incorrect' ||
                   4444: 				     $submitonly eq 'graded'));
1.248     albertel 4445: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   4446: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       4447: 	}
1.524     raeburn  4448: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       4449: 	last if ($ctr == $ntstu);
1.41      ng       4450: 	$ctr++;
                   4451:     }
1.36      ng       4452: 
1.41      ng       4453:     $ctr = 0;
                   4454:     my $total = scalar(@nextlist)-1;
1.39      ng       4455: 
1.524     raeburn  4456:     foreach (sort(@nextlist)) {
1.41      ng       4457: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 4458: 	$env{'form.student'}  = $uname;
                   4459: 	$env{'form.userdom'}  = $udom;
                   4460: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      4461: 	&submission($request,$ctr,$total,$symb);
1.41      ng       4462: 	$ctr++;
                   4463:     }
                   4464:     if ($total < 0) {
1.653     raeburn  4465: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       4466: 	$request->print($the_end);
                   4467:     }
                   4468:     return '';
1.38      ng       4469: }
1.36      ng       4470: 
1.44      ng       4471: #---- Save the score and award for each student, if changed
1.38      ng       4472: sub saveHandGrade {
1.808     raeburn  4473:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,
                   4474:         $part,$queueable,$needpb,$skip_passback,$pbsave) = @_;
1.342     banghart 4475:     my @version_parts;
1.104     albertel 4476:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 4477: 					   $env{'request.course.id'});
1.104     albertel 4478:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 4479:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 4480:     my @parts_graded;
1.77      ng       4481:     my %newrecord  = ();
1.809     raeburn  4482:     my ($pts,$wgt,$totchg,$sendupdate,$poss_pb) = ('','',0,0,0);
1.269     raeburn  4483:     my %aggregate = ();
                   4484:     my $aggregateflag = 0;
1.726     raeburn  4485:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  4486:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  4487:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  4488:         $totchg += $numchgs;
                   4489:     }
1.808     raeburn  4490:     if ((ref($needpb) eq 'HASH') && (keys(%{$needpb}))) {
                   4491:         $poss_pb = 1;
                   4492:     }
1.798     raeburn  4493:     my (%weights,%awardeds,%excuseds);
1.301     albertel 4494:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   4495:     foreach my $new_part (@parts) {
1.803     raeburn  4496: 	#collaborator ($submitter may vary for different parts)
1.259     banghart 4497: 	if ($submitter && $new_part ne $part) { next; }
                   4498: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.808     raeburn  4499:         if ($poss_pb) {
                   4500:             $weights{$symb}{$new_part} =
1.810     raeburn  4501:                 &Apache::lonnet::EXT('resource.'.$new_part.'.weight',$symb,$domain,$stuname);
1.808     raeburn  4502:         } elsif ($env{'form.WGT'.$newflg.'_'.$new_part} eq '') {
1.798     raeburn  4503:             $weights{$symb}{$new_part} = 1;
                   4504:         } else {
                   4505:             $weights{$symb}{$new_part} = $env{'form.WGT'.$newflg.'_'.$new_part};
                   4506:         }
1.125     ng       4507: 	if ($dropMenu eq 'excused') {
1.798     raeburn  4508:             $excuseds{$symb}{$new_part} = 1;
                   4509:             $awardeds{$symb}{$new_part} = '';
1.259     banghart 4510: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   4511: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   4512: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   4513: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 4514: 		}
1.364     banghart 4515: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.803     raeburn  4516:                 $sendupdate ++;
1.58      albertel 4517: 	    }
1.125     ng       4518: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 4519: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  4520: 	    foreach my $key (keys(%record)) {
1.259     banghart 4521: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 4522: 	    }
1.259     banghart 4523: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4524: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 4525:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   4526: 
                   4527:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   4528: 					       [$new_part]);
                   4529:             my $aggtries =$totaltries;
1.269     raeburn  4530:             if ($last_resets{$new_part}) {
1.270     albertel 4531:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   4532: 					   $new_part);
1.269     raeburn  4533:             }
1.270     albertel 4534: 
                   4535:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  4536:             if ($aggtries > 0) {
1.327     albertel 4537:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  4538:                 $aggregateflag = 1;
                   4539:             }
1.803     raeburn  4540:             $sendupdate ++;
1.798     raeburn  4541:             $excuseds{$symb}{$new_part} = '';
                   4542:             $awardeds{$symb}{$new_part} = '';
1.125     ng       4543: 	} elsif ($dropMenu eq '') {
1.259     banghart 4544: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   4545: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   4546: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   4547: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 4548: 		next;
                   4549: 	    }
1.259     banghart 4550: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   4551: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       4552: 	    my $partial= $pts/$wgt;
1.798     raeburn  4553:             $awardeds{$symb}{$new_part} = $partial;
                   4554:             $excuseds{$symb}{$new_part} = '';
1.259     banghart 4555: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 4556: 		#do not update score for part if not changed.
1.346     banghart 4557:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 4558: 		next;
1.251     banghart 4559: 	    } else {
1.524     raeburn  4560: 	        push(@parts_graded,$new_part);
1.803     raeburn  4561:                 $sendupdate ++;
1.153     albertel 4562: 	    }
1.259     banghart 4563: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   4564: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 4565: 	    }
1.259     banghart 4566: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       4567: 	    if ($partial == 0) {
1.153     albertel 4568: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   4569: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   4570: 		}
1.41      ng       4571: 	    } else {
1.153     albertel 4572: 		if ($record{$reckey} ne 'correct_by_override') {
                   4573: 		    $newrecord{$reckey} = 'correct_by_override';
                   4574: 		}
                   4575: 	    }	    
                   4576: 	    if ($submitter && 
1.259     banghart 4577: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   4578: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       4579: 	    }
1.259     banghart 4580: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4581: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       4582: 	}
1.259     banghart 4583: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 4584: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   4585: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   4586: 	        $dropMenu eq 'reset status')
                   4587: 	   {
1.524     raeburn  4588: 	    push(@version_parts,$new_part);
1.259     banghart 4589: 	}
1.41      ng       4590:     }
1.301     albertel 4591:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4592:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4593: 
1.344     albertel 4594:     if (%newrecord) {
                   4595:         if (@version_parts) {
1.364     banghart 4596:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   4597:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 4598: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 4599: 	    foreach my $new_part (@version_parts) {
                   4600: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   4601: 				$new_part,\%newrecord);
                   4602: 	    }
1.259     banghart 4603:         }
1.44      ng       4604: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 4605: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 4606: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.786     raeburn  4607: 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       4608:     }
1.269     raeburn  4609:     if ($aggregateflag) {
                   4610:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4611: 			      $cdom,$cnum);
1.269     raeburn  4612:     }
1.808     raeburn  4613:     if (($sendupdate || $totchg) && (!$submitter) && ($poss_pb)) {
                   4614:         &process_passbacks('handgrade',[$symb],$cdom,$cnum,$domain,$stuname,$usec,\%weights,
                   4615:                            \%awardeds,\%excuseds,$needpb,$skip_passback,$pbsave);
1.798     raeburn  4616:     }
1.803     raeburn  4617:     return ('',$pts,$wgt,$totchg,$sendupdate);
1.726     raeburn  4618: }
                   4619: 
                   4620: sub makehidden {
1.728     raeburn  4621:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  4622:     return unless (ref($record) eq 'HASH');
                   4623:     my %modified;
                   4624:     my $numchanged = 0;
                   4625:     if (exists($record->{$version.':keys'})) {
                   4626:         my $partsregexp = $parts;
                   4627:         $partsregexp =~ s/,/|/g;
                   4628:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   4629:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   4630:                  my $item = $1;
                   4631:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   4632:                      $modified{$key} = $record->{$version.':'.$key};
                   4633:                  }
                   4634:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   4635:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   4636:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   4637:                 $modified{$key} = $record->{$version.':'.$key};
                   4638:             }
                   4639:         }
                   4640:         if (keys(%modified)) {
                   4641:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  4642:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  4643:                 $numchanged ++;
                   4644:             }
                   4645:         }
                   4646:     }
                   4647:     return $numchanged;
1.36      ng       4648: }
1.322     albertel 4649: 
1.380     albertel 4650: sub check_and_remove_from_queue {
1.786     raeburn  4651:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 4652:     my @ungraded_parts;
                   4653:     foreach my $part (@{$parts}) {
                   4654: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   4655: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   4656: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   4657: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   4658: 		) {
1.786     raeburn  4659:             if ($queueable->{$part}) {
                   4660: 	        push(@ungraded_parts, $part);
                   4661:             }
1.380     albertel 4662: 	}
                   4663:     }
                   4664:     if ( !@ungraded_parts ) {
                   4665: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   4666: 					       $cnum,$domain,$stuname);
                   4667:     }
                   4668: }
                   4669: 
1.337     banghart 4670: sub handback_files {
                   4671:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  4672:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  4673:     my $res_error;
                   4674:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4675:     if ($res_error) {
                   4676:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   4677:         return;
                   4678:     }
1.654     raeburn  4679:     my @handedback;
                   4680:     my $file_msg;
1.375     albertel 4681:     my @part_response_id = &flatten_responseType($responseType);
                   4682:     foreach my $part_response_id (@part_response_id) {
                   4683:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   4684: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  4685:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   4686:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   4687:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   4688:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   4689:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 4690:                     my ($directory,$answer_file) = 
1.654     raeburn  4691:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 4692:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  4693: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 4694: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  4695:                     my $getpropath = 1;
1.773     raeburn  4696:                     my ($dir_list,$listerror) =
1.662     raeburn  4697:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   4698:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  4699: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   4700:                     # fix filename
1.355     banghart 4701:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   4702:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  4703:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 4704:             	                                $save_file_name);
1.337     banghart 4705:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  4706:                         $request->print('<br /><span class="LC_error">'.
                   4707:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  4708:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  4709:                                         '</span>');
1.356     banghart 4710:                     } else {
1.360     banghart 4711:                         # mark the file as read only
1.654     raeburn  4712:                         push(@handedback,$save_file_name);
1.367     albertel 4713: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   4714: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   4715: 			}
                   4716:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  4717: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 4718:                     }
1.686     bisitz   4719:                     $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 4720:                 }
                   4721:             }
                   4722:         }
1.654     raeburn  4723:     }
                   4724:     if (@handedback > 0) {
                   4725:         $request->print('<br />');
                   4726:         my @what = ($symb,$env{'request.course.id'},'handback');
                   4727:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   4728:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   4729:         my ($subject,$message);
                   4730:         if (scalar(@handedback) == 1) {
                   4731:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   4732:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   4733:         } else {
                   4734:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   4735:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   4736:         }
                   4737:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   4738:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   4739:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   4740:         my ($feedurl,$showsymb) =
                   4741:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   4742:         my $restitle = &Apache::lonnet::gettitle($symb);
                   4743:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   4744:         my $msgstatus =
                   4745:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   4746:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   4747:                  $restitle);
                   4748:         if ($msgstatus) {
                   4749:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   4750:         }
                   4751:     }
1.338     banghart 4752:     return;
1.337     banghart 4753: }
                   4754: 
1.418     albertel 4755: sub get_feedurl_and_symb {
                   4756:     my ($symb,$uname,$udom) = @_;
                   4757:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   4758:     $url = &Apache::lonnet::clutter($url);
                   4759:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   4760: 					$symb,$udom,$uname);
                   4761:     if ($encrypturl =~ /^yes$/i) {
                   4762: 	&Apache::lonenc::encrypted(\$url,1);
                   4763: 	&Apache::lonenc::encrypted(\$symb,1);
                   4764:     }
                   4765:     return ($url,$symb);
                   4766: }
                   4767: 
1.313     banghart 4768: sub get_submitted_files {
                   4769:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   4770:     my @files;
                   4771:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   4772:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   4773:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   4774:     	    push(@files,$file_url.$file);
                   4775:         }
                   4776:     }
                   4777:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   4778:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   4779:     }
                   4780:     return (\@files);
                   4781: }
1.322     albertel 4782: 
1.269     raeburn  4783: # ----------- Provides number of tries since last reset.
                   4784: sub get_num_tries {
                   4785:     my ($record,$last_reset,$part) = @_;
                   4786:     my $timestamp = '';
                   4787:     my $num_tries = 0;
                   4788:     if ($$record{'version'}) {
                   4789:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   4790:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   4791:                 $timestamp = $$record{$version.':timestamp'};
                   4792:                 if ($timestamp > $last_reset) {
                   4793:                     $num_tries ++;
                   4794:                 } else {
                   4795:                     last;
                   4796:                 }
                   4797:             }
                   4798:         }
                   4799:     }
                   4800:     return $num_tries;
                   4801: }
                   4802: 
                   4803: # ----------- Determine decrements required in aggregate totals 
                   4804: sub decrement_aggs {
                   4805:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   4806:     my %decrement = (
                   4807:                         attempts => 0,
                   4808:                         users => 0,
                   4809:                         correct => 0
                   4810:                     );
                   4811:     $decrement{'attempts'} = $aggtries;
                   4812:     if ($solvedstatus =~ /^correct/) {
                   4813:         $decrement{'correct'} = 1;
                   4814:     }
                   4815:     if ($aggtries == $totaltries) {
                   4816:         $decrement{'users'} = 1;
                   4817:     }
1.524     raeburn  4818:     foreach my $type (keys(%decrement)) {
1.269     raeburn  4819:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   4820:     }
                   4821:     return;
                   4822: }
                   4823: 
                   4824: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   4825: sub get_last_resets {
1.270     albertel 4826:     my ($symb,$courseid,$partids) =@_;
                   4827:     my %last_resets;
1.269     raeburn  4828:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   4829:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 4830:     my @keys;
                   4831:     foreach my $part (@{$partids}) {
                   4832: 	push(@keys,"$symb\0$part\0resettime");
                   4833:     }
                   4834:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   4835: 				     $cdom,$cname);
                   4836:     foreach my $part (@{$partids}) {
                   4837: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  4838:     }
1.270     albertel 4839:     return %last_resets;
1.269     raeburn  4840: }
                   4841: 
1.251     banghart 4842: # ----------- Handles creating versions for portfolio files as answers
                   4843: sub version_portfiles {
1.343     banghart 4844:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 4845:     my $version_parts = join('|',@$v_flag);
1.343     banghart 4846:     my @returned_keys;
1.255     banghart 4847:     my $parts = join('|', @$parts_graded);
1.277     albertel 4848:     foreach my $key (keys(%$record)) {
1.259     banghart 4849:         my $new_portfiles;
1.263     banghart 4850:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 4851:             my @versioned_portfiles;
1.367     albertel 4852:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  4853:             if (@portfiles) {
                   4854:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   4855:                                                       \@versioned_portfiles);
1.252     banghart 4856:             }
1.343     banghart 4857:             $$record{$key} = join(',',@versioned_portfiles);
                   4858:             push(@returned_keys,$key);
1.251     banghart 4859:         }
1.794     raeburn  4860:     }
                   4861:     return (@returned_keys);
1.305     banghart 4862: }
                   4863: 
1.44      ng       4864: #--------------------------------------------------------------------------------------
                   4865: #
                   4866: #-------------------------- Next few routines handles grading by section or whole class
                   4867: #
                   4868: #--- Javascript to handle grading by section or whole class
1.42      ng       4869: sub viewgrades_js {
                   4870:     my ($request) = shift;
                   4871: 
1.539     riegler  4872:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  4873:     &js_escape(\$alertmsg);
1.597     wenzelju 4874:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       4875:    function writePoint(partid,weight,point) {
1.125     ng       4876: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   4877: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       4878: 	if (point == "textval") {
1.125     ng       4879: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  4880: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4881: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       4882: 		var resetbox = false;
                   4883: 		for (var i=0; i<radioButton.length; i++) {
                   4884: 		    if (radioButton[i].checked) {
                   4885: 			textbox.value = i;
                   4886: 			resetbox = true;
                   4887: 		    }
                   4888: 		}
                   4889: 		if (!resetbox) {
                   4890: 		    textbox.value = "";
                   4891: 		}
                   4892: 		return;
                   4893: 	    }
1.109     matthew  4894: 	    if (parseFloat(point) > parseFloat(weight)) {
                   4895: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4896: 				   ") greater than the weight for the part. Accept?");
                   4897: 		if (resp == false) {
                   4898: 		    textbox.value = "";
                   4899: 		    return;
                   4900: 		}
                   4901: 	    }
1.42      ng       4902: 	    for (var i=0; i<radioButton.length; i++) {
                   4903: 		radioButton[i].checked=false;
1.109     matthew  4904: 		if (parseFloat(point) == i) {
1.42      ng       4905: 		    radioButton[i].checked=true;
                   4906: 		}
                   4907: 	    }
1.41      ng       4908: 
1.42      ng       4909: 	} else {
1.125     ng       4910: 	    textbox.value = parseFloat(point);
1.42      ng       4911: 	}
1.41      ng       4912: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4913: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 4914: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4915: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4916: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4917: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4918: 	    if (saveval != "correct") {
                   4919: 		scorename.value = point;
1.43      ng       4920: 		if (selname[0].selected != true) {
                   4921: 		    selname[0].selected = true;
                   4922: 		}
1.42      ng       4923: 	    }
                   4924: 	}
1.125     ng       4925: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       4926:     }
                   4927: 
                   4928:     function writeRadText(partid,weight) {
1.125     ng       4929: 	var selval   = document.classgrade["SELVAL_"+partid];
                   4930: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      4931:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       4932: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   4933: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       4934: 	    for (var i=0; i<radioButton.length; i++) {
                   4935: 		radioButton[i].checked=false;
                   4936: 
                   4937: 	    }
                   4938: 	    textbox.value = "";
                   4939: 
                   4940: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4941: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4942: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4943: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4944: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4945: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4946: 		if ((saveval != "correct") || override) {
1.42      ng       4947: 		    scorename.value = "";
1.125     ng       4948: 		    if (selval[1].selected) {
                   4949: 			selname[1].selected = true;
                   4950: 		    } else {
                   4951: 			selname[2].selected = true;
                   4952: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   4953: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   4954: 		    }
1.42      ng       4955: 		}
                   4956: 	    }
1.43      ng       4957: 	} else {
                   4958: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4959: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4960: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4961: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4962: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4963: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4964: 		if ((saveval != "correct") || override) {
1.125     ng       4965: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       4966: 		    selname[0].selected = true;
                   4967: 		}
                   4968: 	    }
                   4969: 	}	    
1.42      ng       4970:     }
                   4971: 
                   4972:     function changeSelect(partid,user) {
1.125     ng       4973: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4974: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       4975: 	var point  = textbox.value;
1.125     ng       4976: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       4977: 
1.109     matthew  4978: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4979: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       4980: 	    textbox.value = "";
                   4981: 	    return;
                   4982: 	}
1.109     matthew  4983: 	if (parseFloat(point) > parseFloat(weight)) {
                   4984: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4985: 			       ") greater than the weight of the part. Accept?");
                   4986: 	    if (resp == false) {
                   4987: 		textbox.value = "";
                   4988: 		return;
                   4989: 	    }
                   4990: 	}
1.42      ng       4991: 	selval[0].selected = true;
                   4992:     }
                   4993: 
                   4994:     function changeOneScore(partid,user) {
1.125     ng       4995: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4996: 	if (selval[1].selected || selval[2].selected) {
                   4997: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   4998: 	    if (selval[2].selected) {
                   4999: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   5000: 	    }
1.269     raeburn  5001:         }
1.42      ng       5002:     }
                   5003: 
                   5004:     function resetEntry(numpart) {
                   5005: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       5006: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   5007: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   5008: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   5009: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       5010: 	    for (var i=0; i<radioButton.length; i++) {
                   5011: 		radioButton[i].checked=false;
                   5012: 
                   5013: 	    }
                   5014: 	    textbox.value = "";
                   5015: 	    selval[0].selected = true;
                   5016: 
                   5017: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       5018: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 5019: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       5020: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   5021: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   5022: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   5023: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   5024: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   5025: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       5026: 		if (saveselval == "excused") {
1.43      ng       5027: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       5028: 		} else {
1.43      ng       5029: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       5030: 		}
                   5031: 	    }
1.41      ng       5032: 	}
1.42      ng       5033:     }
                   5034: 
1.41      ng       5035: VIEWJAVASCRIPT
1.42      ng       5036: }
                   5037: 
1.44      ng       5038: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       5039: sub viewgrades {
1.608     www      5040:     my ($request,$symb) = @_;
1.745     raeburn  5041:     my ($is_tool,$toolsymb);
                   5042:     if ($symb =~ /ext\.tool$/) {
                   5043:         $is_tool = 1;
                   5044:         $toolsymb = $symb;
                   5045:     }
1.42      ng       5046:     &viewgrades_js($request);
1.41      ng       5047: 
1.168     albertel 5048:     #need to make sure we have the correct data for later EXT calls, 
                   5049:     #thus invalidate the cache
                   5050:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5051:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5052:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5053:     &Apache::lonnet::clear_EXT_cache_status();
                   5054: 
1.398     albertel 5055:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       5056: 
                   5057:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 5058:     $result.=&jscriptNform($symb);
1.41      ng       5059: 
1.44      ng       5060:     #beginning of class grading form
1.442     banghart 5061:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       5062:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 5063: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       5064: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 5065: 	&build_section_inputs().
1.442     banghart 5066: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       5067: 
1.738     raeburn  5068:     #retrieve selected groups
                   5069:     my (@groups,$group_display);
                   5070:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   5071:     if (grep(/^all$/,@groups)) {
                   5072:         @groups = ('all');
                   5073:     } elsif (grep(/^none$/,@groups)) {
                   5074:         @groups = ('none');
                   5075:     } elsif (@groups > 0) {
                   5076:         $group_display = join(', ',@groups);
                   5077:     }
                   5078: 
                   5079:     my ($common_header,$specific_header,@sections,$section_display);
1.780     raeburn  5080:     if ($env{'request.course.sec'} ne '') {
                   5081:         @sections = ($env{'request.course.sec'});
                   5082:     } else {
                   5083:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   5084:     }
                   5085: 
                   5086: # Check if Save button should be usable
                   5087:     my $disabled = ' disabled="disabled"';
                   5088:     if ($perm{'mgr'}) {
                   5089:         if (grep(/^all$/,@sections)) {
                   5090:             undef($disabled);
                   5091:         } else {
                   5092:             foreach my $sec (@sections) {
                   5093:                 if (&canmodify($sec)) {
                   5094:                     undef($disabled);
                   5095:                     last;
                   5096:                 }
                   5097:             }
                   5098:         }
                   5099:     }
1.738     raeburn  5100:     if (grep(/^all$/,@sections)) {
                   5101:         @sections = ('all');
                   5102:         if ($group_display) {
                   5103:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   5104:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   5105:         } elsif (grep(/^none$/,@groups)) {
                   5106:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   5107:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   5108:         } else {
                   5109: 	    $common_header = &mt('Assign Common Grade to Class');
                   5110:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   5111:         }
                   5112:     } elsif (grep(/^none$/,@sections)) {
                   5113:         @sections = ('none');
                   5114:         if ($group_display) {
                   5115:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   5116:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   5117:         } elsif (grep(/^none$/,@groups)) {
                   5118:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   5119:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   5120:         } else {
                   5121:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   5122: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   5123:         }
                   5124:     } else {
                   5125:         $section_display = join (", ",@sections);
                   5126:         if ($group_display) {
                   5127:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   5128:                                  $section_display,$group_display);
                   5129:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   5130:                                    $section_display,$group_display);
                   5131:         } elsif (grep(/^none$/,@groups)) {
                   5132:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   5133:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   5134:         } else {
                   5135:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   5136: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   5137:         }
                   5138:     }
                   5139:     my %submit_types = &substatus_options();
                   5140:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   5141: 
                   5142:     if ($env{'form.submitonly'} eq 'all') {
                   5143:         $result.= '<h3>'.$common_header.'</h3>';
                   5144:     } else {
1.745     raeburn  5145:         my $text;
                   5146:         if ($is_tool) {
                   5147:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5148:         } else {
                   5149:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5150:         }
                   5151:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 5152:     }
1.738     raeburn  5153:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       5154:     #radio buttons/text box for assigning points for a section or class.
                   5155:     #handles different parts of a problem
1.582     raeburn  5156:     my $res_error;
                   5157:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   5158:     if ($res_error) {
                   5159:         return &navmap_errormsg();
                   5160:     }
1.42      ng       5161:     my %weight = ();
                   5162:     my $ctsparts = 0;
1.45      ng       5163:     my %seen = ();
1.745     raeburn  5164:     my @part_response_id;
                   5165:     if ($is_tool) {
                   5166:         @part_response_id = ([0,'']);
                   5167:     } else {
                   5168:         @part_response_id = &flatten_responseType($responseType);
                   5169:     }
1.375     albertel 5170:     foreach my $part_response_id (@part_response_id) {
                   5171:     	my ($partid,$respid) = @{ $part_response_id };
                   5172: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       5173: 	next if $seen{$partid};
                   5174: 	$seen{$partid}++;
1.42      ng       5175: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   5176: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   5177: 
1.324     albertel 5178: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 5179: 	my $radio.='<table border="0"><tr>';  
1.41      ng       5180: 	my $ctr = 0;
1.42      ng       5181: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 5182: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 5183: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 5184: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       5185: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   5186: 	    $ctr++;
                   5187: 	}
1.485     albertel 5188: 	$radio.='</tr></table>';
                   5189: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   5190: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 5191: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  5192: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   5193:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   5194:             '<select name="SELVAL_'.$partid.'" '.
                   5195:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   5196:                 $weight{$partid}.')"> '.
1.401     albertel 5197: 	    '<option selected="selected"> </option>'.
1.485     albertel 5198: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   5199: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   5200: 	    '</select></td>'.
                   5201:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   5202: 	$line.='<input type="hidden" name="partid_'.
                   5203: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   5204: 	$line.='<input type="hidden" name="weight_'.
                   5205: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   5206: 
                   5207: 	$result.=
                   5208: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   5209: 	    '<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 5210: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       5211: 	$ctsparts++;
1.41      ng       5212:     }
1.474     albertel 5213:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 5214: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 5215:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   5216: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       5217: 
1.44      ng       5218:     #table listing all the students in a section/class
                   5219:     #header of table
1.738     raeburn  5220:     if ($env{'form.submitonly'} eq 'all') {
                   5221:         $result.= '<h3>'.$specific_header.'</h3>';
                   5222:     } else {
1.745     raeburn  5223:         my $text;
                   5224:         if ($is_tool) {
                   5225:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5226:         } else {
                   5227:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5228:         }
                   5229:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  5230:     }
                   5231:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  5232: 	      &Apache::loncommon::start_data_table_header_row().
                   5233: 	      '<th>'.&mt('No.').'</th>'.
                   5234: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  5235:     my $partserror;
                   5236:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5237:     if ($partserror) {
                   5238:         return &navmap_errormsg();
                   5239:     }
1.324     albertel 5240:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  5241:     my @partids = ();
1.41      ng       5242:     foreach my $part (@parts) {
1.745     raeburn  5243: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  5244:         my $narrowtext = &mt('Tries');
                   5245: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  5246: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 5247: 	my ($partid) = &split_part_type($part);
1.524     raeburn  5248:         push(@partids,$partid);
1.628     www      5249: #
                   5250: # FIXME: Looks like $display looks at English text
                   5251: #
1.324     albertel 5252: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       5253: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 5254: 	    $result.='<th>'.
1.697     bisitz   5255: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   5256: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       5257: 	    next;
1.485     albertel 5258: 	    
1.207     albertel 5259: 	} else {
1.485     albertel 5260: 	    if ($display =~ /Problem Status/) {
                   5261: 		my $grade_status_mt = &mt('Grade Status');
                   5262: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   5263: 	    }
                   5264: 	    my $part_mt = &mt('Part:');
                   5265: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       5266: 	}
1.485     albertel 5267: 
1.474     albertel 5268: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       5269:     }
1.474     albertel 5270:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       5271: 
1.270     albertel 5272:     my %last_resets = 
                   5273: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  5274: 
1.41      ng       5275:     #get info for each student
1.44      ng       5276:     #list all the students - with points and grade status
1.738     raeburn  5277:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       5278:     my $ctr = 0;
1.294     albertel 5279:     foreach (sort 
                   5280: 	     {
                   5281: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5282: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5283: 		 }
                   5284: 		 return $a cmp $b;
                   5285: 	     } (keys(%$fullname))) {
1.324     albertel 5286: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  5287: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       5288:     }
1.474     albertel 5289:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       5290:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.780     raeburn  5291:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5292: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  5293:     if ($ctr == 0) {
1.442     banghart 5294:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  5295:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   5296:                 '<span class="LC_warning">';
                   5297:         if ($env{'form.submitonly'} eq 'all') {
                   5298:             if (grep(/^all$/,@sections)) {
                   5299:                 if (grep(/^all$/,@groups)) {
                   5300:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   5301:                                    $stu_status);
                   5302:                 } elsif (grep(/^none$/,@groups)) {
                   5303:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   5304:                                    $stu_status); 
                   5305:                 } else {
                   5306:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5307:                                    $group_display,$stu_status);
                   5308:                 }
                   5309:             } elsif (grep(/^none$/,@sections)) {
                   5310:                 if (grep(/^all$/,@groups)) {
                   5311:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   5312:                                    $stu_status);
                   5313:                 } elsif (grep(/^none$/,@groups)) {
                   5314:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   5315:                                    $stu_status);
                   5316:                 } else {
                   5317:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5318:                                    $group_display,$stu_status);
                   5319:                 }
                   5320:             } else {
                   5321:                 if (grep(/^all$/,@groups)) {
                   5322:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   5323:                                    $section_display,$stu_status);
                   5324:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  5325:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  5326:                                    $section_display,$stu_status);
                   5327:                 } else {
                   5328:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   5329:                                    $section_display,$group_display,$stu_status);
                   5330:                 }
                   5331:             }
                   5332:         } else {
                   5333:             if (grep(/^all$/,@sections)) {
                   5334:                 if (grep(/^all$/,@groups)) {
                   5335:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5336:                                    $stu_status,$submission_status);
                   5337:                 } elsif (grep(/^none$/,@groups)) {
                   5338:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5339:                                    $stu_status,$submission_status);
                   5340:                 } else {
                   5341:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5342:                                    $group_display,$stu_status,$submission_status);
                   5343:                 }
                   5344:             } elsif (grep(/^none$/,@sections)) {
                   5345:                 if (grep(/^all$/,@groups)) {
                   5346:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5347:                                    $stu_status,$submission_status);
                   5348:                 } elsif (grep(/^none$/,@groups)) {
                   5349:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5350:                                    $stu_status,$submission_status);
                   5351:                 } else {
                   5352:                     $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.',
                   5353:                                    $group_display,$stu_status,$submission_status);
                   5354:                 }
                   5355:             } else {
                   5356:                 if (grep(/^all$/,@groups)) {
                   5357: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5358: 	                           $section_display,$stu_status,$submission_status);
                   5359:                 } elsif (grep(/^none$/,@groups)) {
                   5360:                     $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.',
                   5361:                                    $section_display,$stu_status,$submission_status);
                   5362:                 } else {
                   5363:                     $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.',
                   5364:                                    $section_display,$group_display,$stu_status,$submission_status);
                   5365:                 }
                   5366:             }
                   5367:         }
                   5368: 	$result .= '</span><br />';
1.96      albertel 5369:     }
1.41      ng       5370:     return $result;
                   5371: }
                   5372: 
1.738     raeburn  5373: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       5374: sub viewstudentgrade {
1.745     raeburn  5375:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       5376:     my ($uname,$udom) = split(/:/,$student);
                   5377:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  5378:     my $submitonly = $env{'form.submitonly'};
                   5379:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   5380:         my %partstatus = ();
                   5381:         if (ref($parts) eq 'ARRAY') {
                   5382:             foreach my $apart (@{$parts}) {
                   5383:                 my ($part,$type) = &split_part_type($apart);
                   5384:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   5385:                 $status = 'nothing' if ($status eq '');
                   5386:                 $partstatus{$part}      = $status;
                   5387:                 my $subkey = "resource.$part.submitted_by";
                   5388:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   5389:             }
                   5390:             my $submitted = 0;
                   5391:             my $graded = 0;
                   5392:             my $incorrect = 0;
                   5393:             foreach my $key (keys(%partstatus)) {
                   5394:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   5395:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   5396:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   5397: 
                   5398:                 my $partid = (split(/\./,$key))[1];
                   5399:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   5400:                     $submitted = 0;
                   5401:                 }
                   5402:             }
                   5403:             return if (!$submitted && ($submitonly eq 'yes' ||
                   5404:                                        $submitonly eq 'incorrect' ||
                   5405:                                        $submitonly eq 'graded'));
                   5406:             return if (!$graded && ($submitonly eq 'graded'));
                   5407:             return if (!$incorrect && $submitonly eq 'incorrect');
                   5408:         }
                   5409:     }
                   5410:     if ($submitonly eq 'queued') {
                   5411:         my ($cdom,$cnum) = split(/_/,$courseid);
                   5412:         my %queue_status =
                   5413:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   5414:                                                     $udom,$uname);
                   5415:         return if (!defined($queue_status{'gradingqueue'}));
                   5416:     }
                   5417:     $$ctr++;
                   5418:     my %aggregates = ();
1.474     albertel 5419:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  5420: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   5421: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       5422: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 5423: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 5424: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 5425:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 5426:     foreach my $apart (@$parts) {
                   5427: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       5428: 	my $score=$record{"resource.$part.$type"};
1.811   ! raeburn  5429:         my $latefrac=$record{"resource.$part.latefrac"};
1.276     albertel 5430:         $result.='<td align="center">';
1.269     raeburn  5431:         my ($aggtries,$totaltries);
                   5432:         unless (exists($aggregates{$part})) {
1.270     albertel 5433: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   5434: 	    $aggtries = $totaltries;
1.269     raeburn  5435:             if ($$last_resets{$part}) {  
1.270     albertel 5436:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   5437: 					   $part);
                   5438:             }
1.269     raeburn  5439:             $result.='<input type="hidden" name="'.
                   5440:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   5441:             $result.='<input type="hidden" name="'.
                   5442:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   5443:             $aggregates{$part} = 1;
                   5444:         }
1.41      ng       5445: 	if ($type eq 'awarded') {
1.811   ! raeburn  5446: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part},$latefrac);
1.42      ng       5447: 	    $result.='<input type="hidden" name="'.
1.89      albertel 5448: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 5449: 	    $result.='<input type="text" name="'.
1.89      albertel 5450: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   5451:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       5452: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       5453: 	} elsif ($type eq 'solved') {
                   5454: 	    my ($status,$foo)=split(/_/,$score,2);
                   5455: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 5456: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 5457: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 5458: 	    $result.='&nbsp;<select name="'.
1.89      albertel 5459: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   5460:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 5461: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   5462: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   5463: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       5464: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       5465: 	} else {
                   5466: 	    $result.='<input type="hidden" name="'.
                   5467: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   5468: 		    "\n";
1.233     albertel 5469: 	    $result.='<input type="text" name="'.
1.122     ng       5470: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   5471: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       5472: 	}
                   5473:     }
1.474     albertel 5474:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       5475:     return $result;
1.38      ng       5476: }
                   5477: 
1.44      ng       5478: #--- change scores for all the students in a section/class
                   5479: #    record does not get update if unchanged
1.38      ng       5480: sub editgrades {
1.608     www      5481:     my ($request,$symb) = @_;
1.745     raeburn  5482:     my $toolsymb;
                   5483:     if ($symb =~ /ext\.tool$/) {
                   5484:         $toolsymb = $symb;
                   5485:     }
1.41      ng       5486: 
1.433     banghart 5487:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 5488:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  5489:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       5490: 
1.477     albertel 5491:     my $result= &Apache::loncommon::start_data_table().
                   5492: 	&Apache::loncommon::start_data_table_header_row().
                   5493: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   5494: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       5495:     my %scoreptr = (
                   5496: 		    'correct'  =>'correct_by_override',
                   5497: 		    'incorrect'=>'incorrect_by_override',
                   5498: 		    'excused'  =>'excused',
                   5499: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  5500:                     'credited' =>'credit_attempted',
1.43      ng       5501: 		    'nothing'  => '',
                   5502: 		    );
1.257     albertel 5503:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       5504: 
1.798     raeburn  5505:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5506:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5507:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   5508: 
1.44      ng       5509:     my (@partid);
                   5510:     my %weight = ();
1.54      albertel 5511:     my %columns = ();
1.44      ng       5512:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 5513: 
1.582     raeburn  5514:     my $partserror;
                   5515:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5516:     if ($partserror) {
                   5517:         return &navmap_errormsg();
                   5518:     }
1.54      albertel 5519:     my $header;
1.257     albertel 5520:     while ($ctr < $env{'form.totalparts'}) {
                   5521: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  5522: 	push(@partid,$partid);
1.257     albertel 5523: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       5524: 	$ctr++;
1.54      albertel 5525:     }
1.324     albertel 5526:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  5527:     my $totcolspan = 0;
1.54      albertel 5528:     foreach my $partid (@partid) {
1.478     albertel 5529: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   5530: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 5531: 	$columns{$partid}=2;
                   5532: 	foreach my $stores (@parts) {
                   5533: 	    my ($part,$type) = &split_part_type($stores);
                   5534: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   5535: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  5536: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  5537: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  5538:             my $narrowtext = &mt('Tries');
                   5539: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   5540: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   5541: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 5542: 	    $columns{$partid}+=2;
                   5543: 	}
1.748     raeburn  5544:         $totcolspan += $columns{$partid};
1.54      albertel 5545:     }
                   5546:     foreach my $partid (@partid) {
1.324     albertel 5547: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 5548: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   5549: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   5550: 	    '</th>';
1.54      albertel 5551: 
1.44      ng       5552:     }
1.477     albertel 5553:     $result .= &Apache::loncommon::end_data_table_header_row().
                   5554: 	&Apache::loncommon::start_data_table_header_row().
                   5555: 	$header.
                   5556: 	&Apache::loncommon::end_data_table_header_row();
                   5557:     my @noupdate;
1.126     ng       5558:     my ($updateCtr,$noupdateCtr) = (1,1);
1.798     raeburn  5559:     my ($got_types,%queueable,%pbsave,%skip_passback);
1.257     albertel 5560:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   5561: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 5562: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       5563: 	my %newrecord;
                   5564: 	my $updateflag = 0;
1.108     albertel 5565: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  5566: 	my $canmodify = &canmodify($usec);
                   5567: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   5568: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   5569: 	if (!$canmodify) {
1.477     albertel 5570: 	    push(@noupdate,
1.748     raeburn  5571: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   5572: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 5573: 	    next;
                   5574: 	}
1.269     raeburn  5575:         my %aggregate = ();
                   5576:         my $aggregateflag = 0;
1.281     albertel 5577: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.798     raeburn  5578:         my (%weights,%awardeds,%excuseds);
1.44      ng       5579: 	foreach (@partid) {
1.257     albertel 5580: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 5581: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   5582: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 5583: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   5584: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 5585: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   5586: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.798     raeburn  5587:             $awardeds{$symb}{$_} = $partial;
1.44      ng       5588: 	    my $score;
                   5589: 	    if ($partial eq '') {
1.257     albertel 5590: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       5591: 	    } elsif ($partial > 0) {
                   5592: 		$score = 'correct_by_override';
                   5593: 	    } elsif ($partial == 0) {
                   5594: 		$score = 'incorrect_by_override';
                   5595: 	    }
1.257     albertel 5596: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       5597: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   5598: 
1.292     albertel 5599: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   5600: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5601: 	    if ($dropMenu eq 'reset status' &&
                   5602: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 5603: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       5604: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   5605: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 5606: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       5607: 		$updateflag = 1;
1.269     raeburn  5608:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   5609:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   5610:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   5611:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   5612:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5613:                     $aggregateflag = 1;
                   5614:                 }
1.139     albertel 5615: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   5616: 		$updateflag = 1;
                   5617: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   5618: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   5619: 		$rec_update++;
1.125     ng       5620: 	    }
                   5621: 
1.93      albertel 5622: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       5623: 		'<td align="center">'.$awarded.
                   5624: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 5625: 
1.54      albertel 5626: 
                   5627: 	    my $partid=$_;
1.798     raeburn  5628:             if ($score eq 'excused') {
                   5629:                 $excuseds{$symb}{$partid} = 1;
                   5630:             } else {
                   5631:                 $excuseds{$symb}{$partid} = '';
                   5632:             }
1.54      albertel 5633: 	    foreach my $stores (@parts) {
                   5634: 		my ($part,$type) = &split_part_type($stores);
                   5635: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   5636: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 5637: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   5638: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 5639: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   5640: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 5641: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 5642: 		    $updateflag=1;
                   5643: 		}
1.93      albertel 5644: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 5645: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   5646: 	    }
1.44      ng       5647: 	}
1.477     albertel 5648: 	$line.="\n";
1.301     albertel 5649: 
1.44      ng       5650: 	if ($updateflag) {
                   5651: 	    $count++;
1.257     albertel 5652: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 5653: 				    $udom,$uname);
1.301     albertel 5654: 
                   5655: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   5656: 					      $cnum,$udom,$uname)) {
                   5657: 		# need to figure out if should be in queue.
                   5658: 		my %record =  
                   5659: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   5660: 					     $udom,$uname);
                   5661: 		my $all_graded = 1;
                   5662: 		my $none_graded = 1;
1.786     raeburn  5663:                 unless ($got_types) {
                   5664:                     my $error;
                   5665:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   5666:                     unless ($error) {
                   5667:                         foreach my $part (@parts) {
                   5668:                             if (ref($resptype->{$part}) eq 'HASH') {
                   5669:                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   5670:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   5671:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   5672:                                         $queueable{$part} = 1;
                   5673:                                         last;
                   5674:                                     }
                   5675:                                 }
                   5676:                             }
                   5677:                         }
                   5678:                     }
                   5679:                     $got_types = 1;
                   5680:                 }
1.301     albertel 5681: 		foreach my $part (@parts) {
1.786     raeburn  5682:                     if ($queueable{$part}) {
                   5683: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   5684: 			    $all_graded = 0;
                   5685: 		        } else {
                   5686: 			    $none_graded = 0;
                   5687: 		        }
1.301     albertel 5688: 		    }
1.786     raeburn  5689:                 }
1.301     albertel 5690: 		if ($all_graded || $none_graded) {
                   5691: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   5692: 							   $symb,$cdom,$cnum,
                   5693: 							   $udom,$uname);
                   5694: 		}
                   5695: 	    }
                   5696: 
1.477     albertel 5697: 	    $result.=&Apache::loncommon::start_data_table_row().
                   5698: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   5699: 		&Apache::loncommon::end_data_table_row();
1.126     ng       5700: 	    $updateCtr++;
1.798     raeburn  5701:             if (keys(%needpb)) {
                   5702:                 $weights{$symb} = \%weight;
1.802     raeburn  5703:                 &process_passbacks('editgrades',[$symb],$cdom,$cnum,$udom,$uname,$usec,\%weights,
1.798     raeburn  5704:                                    \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   5705:             }
1.93      albertel 5706: 	} else {
1.477     albertel 5707: 	    push(@noupdate,
                   5708: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       5709: 	    $noupdateCtr++;
1.44      ng       5710: 	}
1.269     raeburn  5711:         if ($aggregateflag) {
                   5712:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 5713: 				  $cdom,$cnum);
1.269     raeburn  5714:         }
1.93      albertel 5715:     }
1.477     albertel 5716:     if (@noupdate) {
1.748     raeburn  5717:         my $numcols=$totcolspan+2;
1.477     albertel 5718: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 5719: 	    '<td align="center" colspan="'.$numcols.'">'.
                   5720: 	    &mt('No Changes Occurred For the Students Below').
                   5721: 	    '</td>'.
1.477     albertel 5722: 	    &Apache::loncommon::end_data_table_row();
                   5723: 	foreach my $line (@noupdate) {
                   5724: 	    $result.=
                   5725: 		&Apache::loncommon::start_data_table_row().
                   5726: 		$line.
                   5727: 		&Apache::loncommon::end_data_table_row();
                   5728: 	}
1.44      ng       5729:     }
1.614     www      5730:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 5731:     my $msg = '<p><b>'.
                   5732: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   5733: 	    $rec_update,$count).'</b><br />'.
                   5734: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   5735: 	'</b></p>';
1.44      ng       5736:     return $title.$msg.$result;
1.5       albertel 5737: }
1.54      albertel 5738: 
                   5739: sub split_part_type {
                   5740:     my ($partstr) = @_;
                   5741:     my ($temp,@allparts)=split(/_/,$partstr);
                   5742:     my $type=pop(@allparts);
1.439     albertel 5743:     my $part=join('_',@allparts);
1.54      albertel 5744:     return ($part,$type);
                   5745: }
                   5746: 
1.44      ng       5747: #------------- end of section for handling grading by section/class ---------
                   5748: #
                   5749: #----------------------------------------------------------------------------
                   5750: 
1.5       albertel 5751: 
1.44      ng       5752: #----------------------------------------------------------------------------
                   5753: #
                   5754: #-------------------------- Next few routines handles grading by csv upload
                   5755: #
                   5756: #--- Javascript to handle csv upload
1.27      albertel 5757: sub csvupload_javascript_reverse_associate {
1.743     raeburn  5758:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5759:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5760:   &js_escape(\$error1);
                   5761:   &js_escape(\$error2);
1.27      albertel 5762:   return(<<ENDPICK);
                   5763:   function verify(vf) {
                   5764:     var foundsomething=0;
                   5765:     var founduname=0;
1.243     albertel 5766:     var foundID=0;
1.743     raeburn  5767:     var foundclicker=0;
1.27      albertel 5768:     for (i=0;i<=vf.nfields.value;i++) {
                   5769:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5770:       if (i==0 && tw!=0) { foundID=1; }
                   5771:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  5772:       if (i==2 && tw!=0) { foundclicker=1; }
                   5773:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 5774:     }
1.743     raeburn  5775:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 5776: 	alert('$error1');
                   5777: 	return;
1.27      albertel 5778:     }
                   5779:     if (foundsomething==0) {
1.246     albertel 5780: 	alert('$error2');
                   5781: 	return;
1.27      albertel 5782:     }
                   5783:     vf.submit();
                   5784:   }
                   5785:   function flip(vf,tf) {
                   5786:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5787:     var i;
                   5788:     for (i=0;i<=vf.nfields.value;i++) {
                   5789:       //can not pick the same destination field for both name and domain
                   5790:       if (((i ==0)||(i ==1)) && 
                   5791:           ((tf==0)||(tf==1)) && 
                   5792:           (i!=tf) &&
                   5793:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5794:         eval('vf.f'+i+'.selectedIndex=0;')
                   5795:       }
                   5796:     }
                   5797:   }
                   5798: ENDPICK
                   5799: }
                   5800: 
                   5801: sub csvupload_javascript_forward_associate {
1.743     raeburn  5802:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5803:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5804:   &js_escape(\$error1);
                   5805:   &js_escape(\$error2);
1.27      albertel 5806:   return(<<ENDPICK);
                   5807:   function verify(vf) {
                   5808:     var foundsomething=0;
                   5809:     var founduname=0;
1.243     albertel 5810:     var foundID=0;
1.743     raeburn  5811:     var foundclicker=0;
1.27      albertel 5812:     for (i=0;i<=vf.nfields.value;i++) {
                   5813:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5814:       if (tw==1) { foundID=1; }
                   5815:       if (tw==2) { founduname=1; }
1.745     raeburn  5816:       if (tw==3) { foundclicker=1; }
1.743     raeburn  5817:       if (tw>4) { foundsomething=1; }
1.27      albertel 5818:     }
1.743     raeburn  5819:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 5820: 	alert('$error1');
                   5821: 	return;
1.27      albertel 5822:     }
                   5823:     if (foundsomething==0) {
1.246     albertel 5824: 	alert('$error2');
                   5825: 	return;
1.27      albertel 5826:     }
                   5827:     vf.submit();
                   5828:   }
                   5829:   function flip(vf,tf) {
                   5830:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5831:     var i;
                   5832:     //can not pick the same destination field twice
                   5833:     for (i=0;i<=vf.nfields.value;i++) {
                   5834:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5835:         eval('vf.f'+i+'.selectedIndex=0;')
                   5836:       }
                   5837:     }
                   5838:   }
                   5839: ENDPICK
                   5840: }
                   5841: 
1.26      albertel 5842: sub csvuploadmap_header {
1.324     albertel 5843:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       5844:     my $javascript;
1.257     albertel 5845:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       5846: 	$javascript=&csvupload_javascript_reverse_associate();
                   5847:     } else {
                   5848: 	$javascript=&csvupload_javascript_forward_associate();
                   5849:     }
1.45      ng       5850: 
1.418     albertel 5851:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      5852:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   5853:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   5854:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   5855:     my $reverse=&mt("Reverse Association");
1.41      ng       5856:     $request->print(<<ENDPICK);
1.632     www      5857: <br />
                   5858: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 5859: <input type="hidden" name="associate"  value="" />
                   5860: <input type="hidden" name="phase"      value="three" />
                   5861: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 5862: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   5863: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 5864: <input type="hidden" name="upfile_associate" 
1.257     albertel 5865:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 5866: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 5867: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 5868: <hr />
                   5869: ENDPICK
1.597     wenzelju 5870:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       5871:     return '';
1.26      albertel 5872: 
                   5873: }
                   5874: 
                   5875: sub csvupload_fields {
1.582     raeburn  5876:     my ($symb,$errorref) = @_;
1.745     raeburn  5877:     my $toolsymb;
                   5878:     if ($symb =~ /ext\.tool$/) {
                   5879:         $toolsymb = $symb;
                   5880:     }
1.582     raeburn  5881:     my (@parts) = &getpartlist($symb,$errorref);
                   5882:     if (ref($errorref)) {
                   5883:         if ($$errorref) {
                   5884:             return;
                   5885:         }
                   5886:     }
                   5887: 
1.556     weissno  5888:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 5889: 		['username','Student Username'],
1.743     raeburn  5890: 		['clicker','Clicker ID'],
1.243     albertel 5891: 		['domain','Student Domain']);
1.324     albertel 5892:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       5893:     foreach my $part (sort(@parts)) {
                   5894: 	my @datum;
1.745     raeburn  5895: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       5896: 	my $name=$part;
1.745     raeburn  5897: 	if (!$display) { $display = $name; }
1.41      ng       5898: 	@datum=($name,$display);
1.244     albertel 5899: 	if ($name=~/^stores_(.*)_awarded/) {
                   5900: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   5901: 	}
1.41      ng       5902: 	push(@fields,\@datum);
                   5903:     }
                   5904:     return (@fields);
1.26      albertel 5905: }
                   5906: 
                   5907: sub csvuploadmap_footer {
1.41      ng       5908:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   5909:     my $buttontext = &mt('Assign Grades');
1.41      ng       5910:     $request->print(<<ENDPICK);
1.26      albertel 5911: </table>
                   5912: <input type="hidden" name="nfields" value="$i" />
                   5913: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   5914: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 5915: </form>
                   5916: ENDPICK
                   5917: }
                   5918: 
1.283     albertel 5919: sub checkforfile_js {
1.638     www      5920:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  5921:     &js_escape(\$alertmsg);
1.597     wenzelju 5922:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       5923:     function checkUpload(formname) {
                   5924: 	if (formname.upfile.value == "") {
1.539     riegler  5925: 	    alert("$alertmsg");
1.86      ng       5926: 	    return false;
                   5927: 	}
                   5928: 	formname.submit();
                   5929:     }
                   5930: CSVFORMJS
1.283     albertel 5931:     return $result;
                   5932: }
                   5933: 
                   5934: sub upcsvScores_form {
1.608     www      5935:     my ($request,$symb) = @_;
1.283     albertel 5936:     if (!$symb) {return '';}
                   5937:     my $result=&checkforfile_js();
1.632     www      5938:     $result.=&Apache::loncommon::start_data_table().
                   5939:              &Apache::loncommon::start_data_table_header_row().
                   5940:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   5941:              &Apache::loncommon::end_data_table_header_row().
                   5942:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      5943:     my $upload=&mt("Upload Scores");
1.86      ng       5944:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 5945:     my $ignore=&mt('Ignore First Line');
1.418     albertel 5946:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       5947:     $result.=<<ENDUPFORM;
1.106     albertel 5948: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       5949: <input type="hidden" name="symb" value="$symb" />
                   5950: <input type="hidden" name="command" value="csvuploadmap" />
                   5951: $upfile_select
1.589     bisitz   5952: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       5953: </form>
                   5954: ENDUPFORM
1.370     www      5955:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      5956:                            &mt("How do I create a CSV file from a spreadsheet")).
                   5957:              '</td>'.
                   5958:             &Apache::loncommon::end_data_table_row().
                   5959:             &Apache::loncommon::end_data_table();
1.86      ng       5960:     return $result;
                   5961: }
                   5962: 
                   5963: 
1.26      albertel 5964: sub csvuploadmap {
1.768     raeburn  5965:     my ($request,$symb) = @_;
1.41      ng       5966:     if (!$symb) {return '';}
1.72      ng       5967: 
1.41      ng       5968:     my $datatoken;
1.257     albertel 5969:     if (!$env{'form.datatoken'}) {
1.41      ng       5970: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 5971:     } else {
1.742     raeburn  5972: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5973:         if ($datatoken ne '') {
                   5974: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5975:         }
1.26      albertel 5976:     }
1.41      ng       5977:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 5978:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       5979:     my ($i,$keyfields);
                   5980:     if (@records) {
1.582     raeburn  5981:         my $fieldserror;
                   5982: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   5983:         if ($fieldserror) {
                   5984:             $request->print(&navmap_errormsg());
                   5985:             return;
                   5986:         }
1.257     albertel 5987: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       5988: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   5989: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   5990: 							  \@fields);
                   5991: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   5992: 	    chop($keyfields);
                   5993: 	} else {
                   5994: 	    unshift(@fields,['none','']);
                   5995: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   5996: 							    \@fields);
1.311     banghart 5997:             foreach my $rec (@records) {
                   5998:                 my %temp = &Apache::loncommon::record_sep($rec);
                   5999:                 if (%temp) {
                   6000:                     $keyfields=join(',',sort(keys(%temp)));
                   6001:                     last;
                   6002:                 }
                   6003:             }
1.41      ng       6004: 	}
                   6005:     }
                   6006:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       6007: 
1.41      ng       6008:     return '';
1.27      albertel 6009: }
                   6010: 
1.246     albertel 6011: sub csvuploadoptions {
1.608     www      6012:     my ($request,$symb)= @_;
1.632     www      6013:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 6014:     $request->print(<<ENDPICK);
                   6015: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   6016: <input type="hidden" name="command"    value="csvuploadassign" />
                   6017: <p>
                   6018: <label>
                   6019:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      6020:    $overwrite
1.246     albertel 6021: </label>
                   6022: </p>
                   6023: ENDPICK
                   6024:     my %fields=&get_fields();
                   6025:     if (!defined($fields{'domain'})) {
1.257     albertel 6026: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      6027: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 6028:     }
1.257     albertel 6029:     foreach my $key (sort(keys(%env))) {
1.246     albertel 6030: 	if ($key !~ /^form\.(.*)$/) { next; }
                   6031: 	my $cleankey=$1;
                   6032: 	if ($cleankey eq 'command') { next; }
                   6033: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 6034: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 6035:     }
                   6036:     # FIXME do a check for any duplicated user ids...
                   6037:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   6038:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 6039: <hr /></form>'."\n");
1.246     albertel 6040:     return '';
                   6041: }
                   6042: 
                   6043: sub get_fields {
                   6044:     my %fields;
1.257     albertel 6045:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   6046:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   6047: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   6048: 	    if ($env{'form.f'.$i} ne 'none') {
                   6049: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       6050: 	    }
                   6051: 	} else {
1.257     albertel 6052: 	    if ($env{'form.f'.$i} ne 'none') {
                   6053: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       6054: 	    }
                   6055: 	}
1.27      albertel 6056:     }
1.246     albertel 6057:     return %fields;
                   6058: }
                   6059: 
                   6060: sub csvuploadassign {
1.766     raeburn  6061:     my ($request,$symb) = @_;
1.246     albertel 6062:     if (!$symb) {return '';}
1.345     bowersj2 6063:     my $error_msg = '';
1.742     raeburn  6064:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   6065:     if ($datatoken ne '') { 
                   6066:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   6067:     }
1.246     albertel 6068:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   6069:     my %fields=&get_fields();
1.257     albertel 6070:     my $courseid=$env{'request.course.id'};
1.798     raeburn  6071:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6072:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.97      albertel 6073:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 6074:     my @notallowed;
1.41      ng       6075:     my @skipped;
1.657     raeburn  6076:     my @warnings;
1.41      ng       6077:     my $countdone=0;
1.798     raeburn  6078:     my @parts;
                   6079:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   6080:     my $passback;
                   6081:     if (keys(%needpb)) {
                   6082:         $passback = 1;
                   6083:         my $navmap = Apache::lonnavmaps::navmap->new();
                   6084:         if (ref($navmap)) {
                   6085:             my $res = $navmap->getBySymb($symb);
                   6086:             if (ref($res)) {
                   6087:                 my $partlist = $res->parts();
                   6088:                 if (ref($partlist) eq 'ARRAY') {
                   6089:                     @parts = sort(@{$partlist});
                   6090:                 }
                   6091:             }
                   6092:         } else {
                   6093:             return &navmap_errormsg();
                   6094:         }
                   6095:     }
                   6096:     my (%skip_passback,%pbsave,%weights,%awardeds,%excuseds);
                   6097: 
1.41      ng       6098:     foreach my $grade (@gradedata) {
                   6099: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 6100: 	my $domain;
                   6101: 	if ($entries{$fields{'domain'}}) {
                   6102: 	    $domain=$entries{$fields{'domain'}};
                   6103: 	} else {
1.257     albertel 6104: 	    $domain=$env{'form.default_domain'};
1.246     albertel 6105: 	}
1.243     albertel 6106: 	$domain=~s/\s//g;
1.41      ng       6107: 	my $username=$entries{$fields{'username'}};
1.160     albertel 6108: 	$username=~s/\s//g;
1.243     albertel 6109: 	if (!$username) {
                   6110: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 6111: 	    $id=~s/\s//g;
1.737     raeburn  6112:             if ($id ne '') {
                   6113: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   6114: 	        $username=$ids{$id};
                   6115:             } else {
                   6116:                 if ($entries{$fields{'clicker'}}) {
                   6117:                     my $clicker = $entries{$fields{'clicker'}};
                   6118:                     $clicker=~s/\s//g;
                   6119:                     if ($clicker ne '') {
                   6120:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   6121:                         if ($clickers{$clicker} ne '') {  
                   6122:                             my $match = 0;
                   6123:                             my @inclass;
                   6124:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   6125:                                 if (exists($$classlist{"$poss:$domain"})) {
                   6126:                                     $username = $poss;
                   6127:                                     push(@inclass,$poss);
                   6128:                                     $match ++;
                   6129:                                     
                   6130:                                 }
                   6131:                             }
                   6132:                             if ($match > 1) {
                   6133:                                 undef($username); 
                   6134:                                 $request->print('<p class="LC_warning">'.
                   6135:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   6136:                                                 $clicker,join(', ',@inclass)).'</p>');
                   6137:                             }
                   6138:                         }
                   6139:                     }
                   6140:                 }
                   6141:             }
1.243     albertel 6142: 	}
1.41      ng       6143: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 6144: 	    my $id=$entries{$fields{'ID'}};
                   6145: 	    $id=~s/\s//g;
1.737     raeburn  6146:             my $clicker = $entries{$fields{'clicker'}};
                   6147:             $clicker=~s/\s//g;
                   6148:             if ($clicker) {
                   6149:                 push(@skipped,"$clicker:$domain");
                   6150: 	    } elsif ($id) {
1.247     albertel 6151: 		push(@skipped,"$id:$domain");
                   6152: 	    } else {
                   6153: 		push(@skipped,"$username:$domain");
                   6154: 	    }
1.41      ng       6155: 	    next;
                   6156: 	}
1.108     albertel 6157: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 6158: 	if (!&canmodify($usec)) {
                   6159: 	    push(@notallowed,"$username:$domain");
                   6160: 	    next;
                   6161: 	}
1.244     albertel 6162: 	my %points;
1.41      ng       6163: 	my %grades;
                   6164: 	foreach my $dest (keys(%fields)) {
1.244     albertel 6165: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   6166: 		$dest eq 'domain') { next; }
                   6167: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   6168: 	    if ($dest=~/stores_(.*)_points/) {
                   6169: 		my $part=$1;
                   6170: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6171: 					      $symb,$domain,$username);
1.798     raeburn  6172:                 $weights{$symb}{$part} = $wgt;
1.345     bowersj2 6173:                 if ($wgt) {
                   6174:                     $entries{$fields{$dest}}=~s/\s//g;
                   6175:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.798     raeburn  6176:                     if ($passback) {
                   6177:                         $awardeds{$symb}{$part} = $pcr;
                   6178:                         $excuseds{$symb}{$part} = '';
                   6179:                     }
1.463     albertel 6180:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   6181:                                           : 'correct_by_override';
1.638     www      6182:                     if ($pcr>1) {
1.657     raeburn  6183:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      6184:                     }
1.345     bowersj2 6185:                     $grades{"resource.$part.awarded"}=$pcr;
                   6186:                     $grades{"resource.$part.solved"}=$award;
                   6187:                     $points{$part}=1;
                   6188:                 } else {
                   6189:                     $error_msg = "<br />" .
                   6190:                         &mt("Some point values were assigned"
                   6191:                             ." for problems with a weight "
                   6192:                             ."of zero. These values were "
                   6193:                             ."ignored.");
                   6194:                 }
1.244     albertel 6195: 	    } else {
                   6196: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   6197: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   6198: 		my $store_key=$dest;
1.798     raeburn  6199:                 if ($passback) {
                   6200:                     if ($store_key=~/stores_(.*)_(awarded|solved)/) {
                   6201:                         my ($part,$key) = ($1,$2);
                   6202:                         unless ((ref($weights{$symb}) eq 'HASH') && (exists($weights{$symb}{$part}))) {
                   6203:                             $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6204:                                                                           $symb,$domain,$username);
                   6205:                         }
                   6206:                         if ($key eq 'awarded') {
                   6207:                             $awardeds{$symb}{$part} = $entries{$fields{$dest}};
                   6208:                         } elsif ($key eq 'solved') {
                   6209:                             if ($entries{$fields{$dest}} =~ /^excused/) {
                   6210:                                 $excuseds{$symb}{$part} = 1;
                   6211:                             }
                   6212:                         }
                   6213:                     }
                   6214:                 }
1.244     albertel 6215: 		$store_key=~s/^stores/resource/;
                   6216: 		$store_key=~s/_/\./g;
                   6217: 		$grades{$store_key}=$entries{$fields{$dest}};
                   6218: 	    }
1.41      ng       6219: 	}
1.766     raeburn  6220: 	if (! %grades) {
1.508     www      6221:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   6222:         } else {
                   6223: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   6224: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 6225: 					   $env{'request.course.id'},
                   6226: 					   $domain,$username);
1.508     www      6227: 	   if ($result eq 'ok') {
1.627     www      6228: # Successfully stored
1.508     www      6229: 	      $request->print('.');
1.627     www      6230: # Remove from grading queue
1.798     raeburn  6231:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,$cnum,
1.801     raeburn  6232: 						     $domain,$username);
1.627     www      6233:               $countdone++;
1.798     raeburn  6234:               if ($passback) {
                   6235:                   my @parts_in_upload;
                   6236:                   if (ref($weights{$symb}) eq 'HASH') {
                   6237:                       @parts_in_upload = sort(keys(%{$weights{$symb}}));
                   6238:                   }
                   6239:                   my @diffs = &Apache::loncommon::compare_arrays(\@parts_in_upload,\@parts);
                   6240:                   if (@diffs > 0) {
                   6241:                       my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$username);
                   6242:                       foreach my $part (@parts) {
                   6243:                           next if (grep(/^\Q$part\E$/,@parts_in_upload));
                   6244:                           $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6245:                                                                         $symb,$domain,$username);
                   6246:                           if ($record{"resource.$part.solved"} =~/^excused/) {
                   6247:                               $excuseds{$symb}{$part} = 1;
                   6248:                           } else {
                   6249:                               $excuseds{$symb}{$part} = '';
                   6250:                           }
                   6251:                           $awardeds{$symb}{$part} = $record{"resource.$part.awarded"};
                   6252:                       }
                   6253:                   }
1.802     raeburn  6254:                   &process_passbacks('csvupload',[$symb],$cdom,$cnum,$domain,$username,$usec,\%weights,
1.798     raeburn  6255:                                      \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   6256:               }
1.627     www      6257:            } else {
1.508     www      6258: 	      $request->print("<p><span class=\"LC_error\">".
                   6259:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   6260:                                   "$username:$domain",$result)."</span></p>");
                   6261: 	   }
                   6262: 	   $request->rflush();
                   6263:         }
1.41      ng       6264:     }
1.570     www      6265:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  6266:     if (@warnings) {
                   6267:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   6268:         $request->print(join(', ',@warnings));
                   6269:     }
1.41      ng       6270:     if (@skipped) {
1.571     www      6271: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   6272:         $request->print(join(', ',@skipped));
1.106     albertel 6273:     }
                   6274:     if (@notallowed) {
1.571     www      6275: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   6276: 	$request->print(join(', ',@notallowed));
1.41      ng       6277:     }
1.106     albertel 6278:     $request->print("<br />\n");
1.345     bowersj2 6279:     return $error_msg;
1.26      albertel 6280: }
1.44      ng       6281: #------------- end of section for handling csv file upload ---------
                   6282: #
                   6283: #-------------------------------------------------------------------
                   6284: #
1.122     ng       6285: #-------------- Next few routines handle grading by page/sequence
1.72      ng       6286: #
                   6287: #--- Select a page/sequence and a student to grade
1.68      ng       6288: sub pickStudentPage {
1.608     www      6289:     my ($request,$symb) = @_;
1.68      ng       6290: 
1.539     riegler  6291:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  6292:     &js_escape(\$alertmsg);
1.597     wenzelju 6293:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       6294: 
                   6295: function checkPickOne(formname) {
1.76      ng       6296:     if (radioSelection(formname.student) == null) {
1.539     riegler  6297: 	alert("$alertmsg");
1.68      ng       6298: 	return;
                   6299:     }
1.125     ng       6300:     ptr = pullDownSelection(formname.selectpage);
                   6301:     formname.page.value = formname["page"+ptr].value;
                   6302:     formname.title.value = formname["title"+ptr].value;
1.68      ng       6303:     formname.submit();
                   6304: }
                   6305: 
                   6306: LISTJAVASCRIPT
1.118     ng       6307:     &commonJSfunctions($request);
1.608     www      6308: 
1.257     albertel 6309:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6310:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6311:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  6312:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       6313: 
1.398     albertel 6314:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 6315: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       6316: 
1.80      ng       6317:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  6318:     my $map_error;
                   6319:     my ($titles,$symbx) = &getSymbMap($map_error);
                   6320:     if ($map_error) {
                   6321:         $request->print(&navmap_errormsg());
                   6322:         return; 
                   6323:     }
1.137     albertel 6324:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   6325: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   6326: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   6327: 
                   6328:     # Collection of hidden fields
1.70      ng       6329:     my $ctr=0;
1.68      ng       6330:     foreach (@$titles) {
1.700     bisitz   6331:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   6332:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   6333:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   6334:         $ctr++;
1.68      ng       6335:     }
1.700     bisitz   6336:     $result.='<input type="hidden" name="page" />'."\n".
                   6337:         '<input type="hidden" name="title" />'."\n";
                   6338: 
                   6339:     $result.=&build_section_inputs();
                   6340:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   6341:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   6342: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   6343: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 6344: 
1.700     bisitz   6345:     # Show grading options
                   6346:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   6347:     my $select = '<select name="selectpage">'."\n";
1.70      ng       6348:     $ctr=0;
                   6349:     foreach (@$titles) {
                   6350: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   6351: 	$select.='<option value="'.$ctr.'"'.
                   6352: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   6353: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       6354: 	$ctr++;
                   6355:     }
1.700     bisitz   6356:     $select.= '</select>';
1.68      ng       6357: 
1.700     bisitz   6358:     $result.=
                   6359:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   6360:        .$select
                   6361:        .&Apache::lonhtmlcommon::row_closure();
                   6362: 
                   6363:     $result.=
                   6364:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   6365:        .'<label><input type="radio" name="vProb" value="no"'
                   6366:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   6367:        .'<label><input type="radio" name="vProb" value="yes" />'
                   6368:            .&mt('yes').'</label>'."\n"
                   6369:        .&Apache::lonhtmlcommon::row_closure();
                   6370: 
                   6371:     $result.=
                   6372:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   6373:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   6374:            .&mt('none').' </label>'."\n"
                   6375:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   6376:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   6377:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   6378:            .&mt('all submissions with details').' </label>'
                   6379:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 6380:     
1.700     bisitz   6381:     $result.=
                   6382:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   6383:        .'<input type="text" name="CODE" value="" />'
                   6384:        .&Apache::lonhtmlcommon::row_closure(1)
                   6385:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 6386: 
1.700     bisitz   6387:     # Show list of students to select for grading
                   6388:     $result.='<br /><input type="button" '.
1.589     bisitz   6389:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       6390: 
1.68      ng       6391:     $request->print($result);
                   6392: 
1.485     albertel 6393:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 6394: 	&Apache::loncommon::start_data_table().
                   6395: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6396: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6397: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 6398: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6399: 	'<th>'.&nameUserString('header').'</th>'.
                   6400: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       6401:  
1.761     raeburn  6402:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       6403:     my $ptr = 1;
1.294     albertel 6404:     foreach my $student (sort 
                   6405: 			 {
                   6406: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   6407: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   6408: 			     }
                   6409: 			     return $a cmp $b;
                   6410: 			 } (keys(%$fullname))) {
1.68      ng       6411: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 6412: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   6413:                                   : '</td>');
1.126     ng       6414: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 6415: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   6416: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 6417: 	$studentTable.=
                   6418: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   6419:                          : '');
1.68      ng       6420: 	$ptr++;
                   6421:     }
1.484     albertel 6422:     if ($ptr%2 == 0) {
                   6423: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   6424: 	    &Apache::loncommon::end_data_table_row();
                   6425:     }
                   6426:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       6427:     $studentTable.='<input type="button" '.
1.589     bisitz   6428:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       6429: 
                   6430:     $request->print($studentTable);
                   6431: 
                   6432:     return '';
                   6433: }
                   6434: 
                   6435: sub getSymbMap {
1.582     raeburn  6436:     my ($map_error) = @_;
1.132     bowersj2 6437:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6438:     unless (ref($navmap)) {
                   6439:         if (ref($map_error)) {
                   6440:             $$map_error = 'navmap';
                   6441:         }
                   6442:         return;
                   6443:     }
1.68      ng       6444:     my %symbx = ();
                   6445:     my @titles = ();
1.117     bowersj2 6446:     my $minder = 0;
                   6447: 
                   6448:     # Gather every sequence that has problems.
1.240     albertel 6449:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   6450: 					       1,0,1);
1.117     bowersj2 6451:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  6452: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 6453: 	    my $title = $minder.'.'.
                   6454: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   6455: 	    push(@titles, $title); # minder in case two titles are identical
                   6456: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 6457: 	    $minder++;
1.241     albertel 6458: 	}
1.68      ng       6459:     }
                   6460:     return \@titles,\%symbx;
                   6461: }
                   6462: 
1.72      ng       6463: #
                   6464: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       6465: sub displayPage {
1.608     www      6466:     my ($request,$symb) = @_;
1.257     albertel 6467:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6468:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6469:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6470:     my $pageTitle = $env{'form.page'};
1.103     albertel 6471:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6472:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6473:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 6474: 
                   6475:     #need to make sure we have the correct data for later EXT calls, 
                   6476:     #thus invalidate the cache
                   6477:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 6478:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   6479:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 6480:     &Apache::lonnet::clear_EXT_cache_status();
                   6481: 
1.103     albertel 6482:     if (!&canview($usec)) {
1.712     bisitz   6483:         $request->print(
                   6484:             '<span class="LC_warning">'.
                   6485:             &mt('Unable to view requested student. ([_1])',
                   6486:                     $env{'form.student'}).
                   6487:             '</span>');
                   6488:         return;
1.103     albertel 6489:     }
1.398     albertel 6490:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 6491:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       6492: 	'</h3>'."\n";
1.500     albertel 6493:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     6494:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 6495: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 6496:     } else {
                   6497: 	delete($env{'form.CODE'});
                   6498:     }
1.71      ng       6499:     &sub_page_js($request);
                   6500:     $request->print($result);
                   6501: 
1.132     bowersj2 6502:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6503:     unless (ref($navmap)) {
                   6504:         $request->print(&navmap_errormsg());
                   6505:         return;
                   6506:     }
1.257     albertel 6507:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       6508:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6509:     if (!$map) {
1.485     albertel 6510: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 6511: 	return; 
                   6512:     }
1.68      ng       6513:     my $iterator = $navmap->getIterator($map->map_start(),
                   6514: 					$map->map_finish());
                   6515: 
1.71      ng       6516:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       6517: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 6518: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   6519: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       6520: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 6521: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 6522: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      6523: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       6524: 
1.382     albertel 6525:     if (defined($env{'form.CODE'})) {
                   6526: 	$studentTable.=
                   6527: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   6528:     }
1.381     albertel 6529:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 6530: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       6531: 
1.594     bisitz   6532:     $studentTable.='&nbsp;<span class="LC_info">'.
                   6533:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   6534:         '</span>'."\n".
1.484     albertel 6535: 	&Apache::loncommon::start_data_table().
                   6536: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   6537: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 6538: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 6539: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6540: 
1.329     albertel 6541:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 6542:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       6543:     $iterator->next(); # skip the first BEGIN_MAP
                   6544:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 6545:     while ($depth > 0) {
1.68      ng       6546:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6547:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       6548: 
1.745     raeburn  6549:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 6550: 	    my $parts = $curRes->parts();
1.68      ng       6551:             my $title = $curRes->compTitle();
1.71      ng       6552: 	    my $symbx = $curRes->symb();
1.746     raeburn  6553:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 6554: 	    $studentTable.=
                   6555: 		&Apache::loncommon::start_data_table_row().
                   6556: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6557: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  6558: 		                        : '<br />('.&mt('[_1]parts',
                   6559: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 6560: 		 ).
                   6561: 		 '</td>';
1.71      ng       6562: 	    $studentTable.='<td valign="top">';
1.382     albertel 6563: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  6564:             if ($is_tool) {
                   6565:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   6566:             } else {
1.745     raeburn  6567: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   6568: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   6569: 					         undef,'both',\%form);
                   6570: 	        } else {
                   6571: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   6572: 		    $companswer =~ s|<form(.*?)>||g;
                   6573: 		    $companswer =~ s|</form>||g;
                   6574: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   6575: #		        $companswer =~ s/$1/ /ms;
                   6576: #		        $request->print('match='.$1."<br />\n");
                   6577: #		    }
                   6578: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   6579: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   6580: 		}
1.71      ng       6581: 	    }
                   6582: 
1.257     albertel 6583: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       6584: 
1.257     albertel 6585: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       6586: 		if ($record{'version'} eq '') {
1.745     raeburn  6587:                     my $msg = &mt('No recorded submission for this problem.');
                   6588:                     if ($is_tool) {
                   6589:                         $msg = &mt('No recorded transactions for this external tool');
                   6590:                     }
                   6591: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       6592: 		} else {
1.116     ng       6593: 		    my %responseType = ();
                   6594: 		    foreach my $partid (@{$parts}) {
1.147     albertel 6595: 			my @responseIds =$curRes->responseIds($partid);
                   6596: 			my @responseType =$curRes->responseType($partid);
                   6597: 			my %responseIds;
                   6598: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   6599: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   6600: 			}
                   6601: 			$responseType{$partid} = \%responseIds;
1.116     ng       6602: 		    }
1.148     albertel 6603: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       6604: 		}
1.257     albertel 6605: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   6606: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  6607:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       6608: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 6609: 									$env{'request.course.id'},
1.726     raeburn  6610: 									'','.submission',undef,
                   6611:                                                                         $usec,$identifier);
1.71      ng       6612:  
                   6613: 	    }
1.103     albertel 6614: 	    if (&canmodify($usec)) {
1.585     bisitz   6615:             $studentTable.=&gradeBox_start();
1.103     albertel 6616: 		foreach my $partid (@{$parts}) {
                   6617: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   6618: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   6619: 		    $question++;
                   6620: 		}
1.585     bisitz   6621:             $studentTable.=&gradeBox_end();
1.196     albertel 6622: 		$prob++;
1.71      ng       6623: 	    }
                   6624: 	    $studentTable.='</td></tr>';
1.68      ng       6625: 
1.103     albertel 6626: 	}
1.68      ng       6627:         $curRes = $iterator->next();
                   6628:     }
1.780     raeburn  6629:     my $disabled;
                   6630:     unless (&canmodify($usec)) {
                   6631:         $disabled = ' disabled="disabled"';
                   6632:     }
1.68      ng       6633: 
1.589     bisitz   6634:     $studentTable.=
                   6635:         '</table>'."\n".
1.780     raeburn  6636:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   6637:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   6638:         '</form>'."\n";
1.71      ng       6639:     $request->print($studentTable);
                   6640: 
                   6641:     return '';
1.119     ng       6642: }
                   6643: 
                   6644: sub displaySubByDates {
1.148     albertel 6645:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 6646:     my $isCODE=0;
1.335     albertel 6647:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  6648:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 6649:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 6650:     my $studentTable=&Apache::loncommon::start_data_table().
                   6651: 	&Apache::loncommon::start_data_table_header_row().
                   6652: 	'<th>'.&mt('Date/Time').'</th>'.
                   6653: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  6654:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  6655: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 6656: 	'<th>'.&mt('Status').'</th>'.
                   6657: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       6658:     my ($version);
                   6659:     my %mark;
1.148     albertel 6660:     my %orders;
1.119     ng       6661:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 6662:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  6663:         if ($is_tool) {
                   6664:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   6665:         } else {
                   6666:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   6667:         }
1.147     albertel 6668:     }
1.335     albertel 6669: 
                   6670:     my $interaction;
1.525     raeburn  6671:     my $no_increment = 1;
1.735     raeburn  6672:     my (%lastrndseed,%lasttype);
1.119     ng       6673:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 6674: 	my $timestamp = 
                   6675: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 6676: 	if (exists($$record{$version.':resource.0.version'})) {
                   6677: 	    $interaction = $$record{$version.':resource.0.version'};
                   6678: 	}
1.671     raeburn  6679:         if ($isTask && $env{'form.previousversion'}) {
                   6680:             next unless ($interaction == $env{'form.previousversion'});
                   6681:         }
1.335     albertel 6682: 	my $where = ($isTask ? "$version:resource.$interaction"
                   6683: 		             : "$version:resource");
1.467     albertel 6684: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   6685: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 6686: 	if ($isCODE) {
                   6687: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   6688: 	}
1.671     raeburn  6689:         if ($isTask) {
                   6690:             $studentTable.='<td>'.$interaction.'</td>';
                   6691:         }
1.119     ng       6692: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   6693: 	my @displaySub = ();
                   6694: 	foreach my $partid (@{$parts}) {
1.640     raeburn  6695:             my ($hidden,$type);
                   6696:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   6697:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  6698:                 $hidden = 1;
                   6699:             }
1.749     raeburn  6700:             my @matchKey;
                   6701:             if ($isTask) {
1.769     raeburn  6702:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  6703:             } elsif ($is_tool) {
1.769     raeburn  6704:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  6705:             } else {
1.769     raeburn  6706:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  6707:             }
1.122     ng       6708: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 6709: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 6710: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 6711: 		if (exists($$record{$version.':'.$matchKey}) &&
                   6712: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  6713:                     if ($is_tool) {
                   6714:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  6715:                     } else {
1.749     raeburn  6716: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   6717: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   6718:                         $displaySub[0].='<span class="LC_nobreak">';
                   6719:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   6720:                                        .' <span class="LC_internal_info">'
                   6721:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   6722:                                        .'</span>'
                   6723:                                        .' <b>';
                   6724:                         if ($hidden) {
                   6725:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   6726:                         } else {
                   6727:                             my ($trial,$rndseed,$newvariation);
                   6728:                             if ($type eq 'randomizetry') {
                   6729:                                 $trial = $$record{"$where.$partid.tries"};
                   6730:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   6731:                             }
                   6732: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   6733: 			        $displaySub[0].=&mt('Trial not counted');
                   6734: 		            } else {
                   6735: 			        $displaySub[0].=&mt('Trial: [_1]',
                   6736: 					        $$record{"$where.$partid.tries"});
                   6737:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   6738:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   6739:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   6740:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   6741:                                     }
1.640     raeburn  6742:                                 }
1.749     raeburn  6743:                                 $lastrndseed{$partid} = $rndseed;
                   6744:                                 $lasttype{$partid} = $type;
                   6745: 		            }
                   6746: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 6747:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  6748: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   6749: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   6750: 			        $orders{$partid}->{$responseId}=
                   6751: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   6752:                                                $no_increment,$type,$trial,$rndseed);
                   6753: 		            }
                   6754: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   6755: 		            $displaySub[0].='&nbsp; '.
                   6756: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   6757:                         }
1.596     raeburn  6758:                     }
1.147     albertel 6759: 		}
                   6760: 	    }
1.335     albertel 6761: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 6762: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   6763: 				    $$record{"$where.$partid.checkedin"},
                   6764: 				    $$record{"$where.$partid.checkedin.slot"}).
                   6765: 					'<br />';
1.335     albertel 6766: 	    }
                   6767: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 6768: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 6769: 		    lc($$record{"$where.$partid.award"}).' '.
                   6770: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 6771: 		    '<br />';
1.749     raeburn  6772: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   6773: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   6774: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   6775: 		}
1.147     albertel 6776: 	    }
1.335     albertel 6777: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  6778: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   6779: 		unless ($is_tool) {
                   6780: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6781: 		}
1.335     albertel 6782: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   6783: 		$displaySub[2].=
1.749     raeburn  6784: 		    $$record{"$version:resource.$partid.regrader"};
                   6785:                 unless ($is_tool) {
                   6786: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6787:                 }
1.147     albertel 6788: 	    }
                   6789: 	}
                   6790: 	# needed because old essay regrader has not parts info
                   6791: 	if (exists $$record{"$version:resource.regrader"}) {
                   6792: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   6793: 	}
                   6794: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   6795: 	if ($displaySub[2]) {
1.467     albertel 6796: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 6797: 	}
1.467     albertel 6798: 	$studentTable.='&nbsp;</td>'.
                   6799: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       6800:     }
1.467     albertel 6801:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       6802:     return $studentTable;
1.71      ng       6803: }
                   6804: 
                   6805: sub updateGradeByPage {
1.608     www      6806:     my ($request,$symb) = @_;
1.71      ng       6807: 
1.257     albertel 6808:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6809:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6810:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6811:     my $pageTitle = $env{'form.page'};
1.103     albertel 6812:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6813:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6814:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 6815:     if (!&canmodify($usec)) {
1.526     raeburn  6816: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 6817: 	return;
                   6818:     }
1.398     albertel 6819:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  6820:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       6821: 	'</h3>'."\n";
1.70      ng       6822: 
1.68      ng       6823:     $request->print($result);
                   6824: 
1.582     raeburn  6825: 
1.132     bowersj2 6826:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6827:     unless (ref($navmap)) {
                   6828:         $request->print(&navmap_errormsg());
                   6829:         return;
                   6830:     }
1.257     albertel 6831:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       6832:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6833:     if (!$map) {
1.527     raeburn  6834: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 6835: 	return; 
                   6836:     }
1.71      ng       6837:     my $iterator = $navmap->getIterator($map->map_start(),
                   6838: 					$map->map_finish());
1.70      ng       6839: 
1.484     albertel 6840:     my $studentTable=
                   6841: 	&Apache::loncommon::start_data_table().
                   6842: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6843: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   6844: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   6845: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   6846: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 6847: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6848: 
                   6849:     $iterator->next(); # skip the first BEGIN_MAP
                   6850:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  6851:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.798     raeburn  6852:     my (@updates,%weights,%excuseds,%awardeds,@symbs_in_map);
1.101     albertel 6853:     while ($depth > 0) {
1.71      ng       6854:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6855:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       6856: 
1.385     albertel 6857:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 6858: 	    my $parts = $curRes->parts();
1.71      ng       6859:             my $title = $curRes->compTitle();
                   6860: 	    my $symbx = $curRes->symb();
1.798     raeburn  6861:             push(@symbs_in_map,$symbx);
1.484     albertel 6862: 	    $studentTable.=
                   6863: 		&Apache::loncommon::start_data_table_row().
                   6864: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6865: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  6866:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  6867: 		.')').'</td>';
1.71      ng       6868: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   6869: 
                   6870: 	    my %newrecord=();
                   6871: 	    my @displayPts=();
1.269     raeburn  6872:             my %aggregate = ();
                   6873:             my $aggregateflag = 0;
1.787     raeburn  6874:             my %queueable;
1.726     raeburn  6875:             if ($env{'form.HIDE'.$prob}) {
                   6876:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  6877:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  6878:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.798     raeburn  6879:                 if ($numchgs) {
                   6880:                     push(@updates,$symbx);
                   6881:                 }
1.726     raeburn  6882:                 $hideflag += $numchgs;
                   6883:             }
1.71      ng       6884: 	    foreach my $partid (@{$parts}) {
1.257     albertel 6885: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   6886: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.787     raeburn  6887:                 my @types = $curRes->responseType($partid);
1.786     raeburn  6888:                 if (grep(/^essay$/,@types)) {
                   6889:                     $queueable{$partid} = 1;
                   6890:                 } else {
1.787     raeburn  6891:                     my @ids = $curRes->responseIds($partid);
1.786     raeburn  6892:                     for (my $i=0; $i < scalar(@ids); $i++) {
1.787     raeburn  6893:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
1.786     raeburn  6894:                                                           '.handgrade',$symb);
                   6895:                         if (lc($hndgrd) eq 'yes') {
                   6896:                             $queueable{$partid} = 1;
                   6897:                             last;
                   6898:                         }
                   6899:                     }
                   6900:                 }
1.257     albertel 6901: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   6902: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.798     raeburn  6903:                 $weights{$symbx}{$partid} = $wgt;
                   6904:                 $excuseds{$symbx}{$partid} = '';
1.71      ng       6905: 		my $partial = $newpts/$wgt;
                   6906: 		my $score;
                   6907: 		if ($partial > 0) {
                   6908: 		    $score = 'correct_by_override';
1.125     ng       6909: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       6910: 		    $score = 'incorrect_by_override';
                   6911: 		}
1.257     albertel 6912: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       6913: 		if ($dropMenu eq 'excused') {
1.71      ng       6914: 		    $partial = '';
                   6915: 		    $score = 'excused';
1.798     raeburn  6916:                     $excuseds{$symbx}{$partid} = 1;
1.125     ng       6917: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 6918: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       6919: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   6920: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   6921: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   6922: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 6923: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       6924: 		    $changeflag++;
                   6925: 		    $newpts = '';
1.269     raeburn  6926:                     
                   6927:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   6928:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   6929:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   6930:                     if ($aggtries > 0) {
                   6931:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   6932:                         $aggregateflag = 1;
                   6933:                     }
1.71      ng       6934: 		}
1.324     albertel 6935: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 6936: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  6937: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       6938: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 6939: 		    '&nbsp;<br />';
1.526     raeburn  6940: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       6941: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 6942: 		    '&nbsp;<br />';
1.71      ng       6943: 		$question++;
1.798     raeburn  6944:                 if (($newpts eq '') || ($partial eq '')) {
                   6945:                     $awardeds{$symbx}{$partid} = 0;
                   6946:                 } else {
                   6947:                     $awardeds{$symbx}{$partid} = $partial;
                   6948:                 }
1.380     albertel 6949: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       6950: 
1.71      ng       6951: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       6952: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 6953: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       6954: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       6955: 
                   6956: 		$changeflag++;
                   6957: 	    }
                   6958: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 6959: 		my %record = 
                   6960: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   6961: 					     $udom,$uname);
                   6962: 
                   6963: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   6964: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   6965: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   6966: 		    $newrecord{'resource.CODE'} = '';
                   6967: 		}
1.257     albertel 6968: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       6969: 					$udom,$uname);
1.382     albertel 6970: 		%record = &Apache::lonnet::restore($symbx,
                   6971: 						   $env{'request.course.id'},
                   6972: 						   $udom,$uname);
1.380     albertel 6973: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.786     raeburn  6974: 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       6975: 	    }
1.380     albertel 6976: 	    
1.269     raeburn  6977:             if ($aggregateflag) {
                   6978:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   6979:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   6980:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   6981:             }
1.125     ng       6982: 
1.71      ng       6983: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   6984: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 6985: 		&Apache::loncommon::end_data_table_row();
1.68      ng       6986: 
1.196     albertel 6987: 	    $prob++;
1.798     raeburn  6988:             if ($changeflag) {
                   6989:                 push(@updates,$symbx);
                   6990:             }
1.68      ng       6991: 	}
1.71      ng       6992:         $curRes = $iterator->next();
1.68      ng       6993:     }
1.98      albertel 6994: 
1.484     albertel 6995:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  6996:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   6997: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  6998: 		  $changeflag).'<br />');
                   6999:     my $hidemsg=($hideflag == 0 ? '' :
                   7000:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   7001:                      $hideflag).'<br />');
                   7002:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       7003: 
1.798     raeburn  7004:     if (@updates) {
                   7005:         my (@allsymbs,$mapsymb,@recurseup,%parentmapsymbs,%possmappb,%possrespb);
                   7006:         @allsymbs = @updates;
                   7007:         if (ref($map)) {
                   7008:             $mapsymb = $map->symb();
                   7009:             push(@allsymbs,$mapsymb);
                   7010:             @recurseup = $navmap->recurseup_maps($map->src,1);
                   7011:         }
                   7012:         if (@recurseup) {
                   7013:             push(@allsymbs,@recurseup);
                   7014:             map { $parentmapsymbs{$_} = 1; } @recurseup;
                   7015:         }
                   7016:         my %passback = &Apache::lonnet::get('nohist_linkprot_passback',\@allsymbs,$cdom,$cnum);
1.806     raeburn  7017:         my (%uniqsymbs,$use_symbs_in_map,%launch_to_symb);
1.798     raeburn  7018:         if (keys(%passback)) {
                   7019:             foreach my $possible (keys(%passback)) {
                   7020:                 if (ref($passback{$possible}) eq 'HASH') {
                   7021:                     if ($possible eq $mapsymb) {
                   7022:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7023:                             $possmappb{$launcher} = 1;
1.806     raeburn  7024:                             $launch_to_symb{$launcher} = $possible;
1.798     raeburn  7025:                         }
                   7026:                         $use_symbs_in_map = 1;
                   7027:                     } elsif (exists($parentmapsymbs{$possible})) {
                   7028:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7029:                             my ($linkuri,$linkprotector,$scope) = split(/\0/,$launcher);
                   7030:                             if ($scope eq 'rec') {
                   7031:                                 $possmappb{$launcher} = 1;
                   7032:                                 $use_symbs_in_map = 1;
1.806     raeburn  7033:                                 $launch_to_symb{$launcher} = $possible;
1.798     raeburn  7034:                             }
                   7035:                         }
                   7036:                     } elsif (grep(/^\Q$possible$\E$/,@updates)) {
                   7037:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7038:                             $possrespb{$launcher} = 1;
1.806     raeburn  7039:                             $launch_to_symb{$launcher} = $possible;
1.798     raeburn  7040:                         }
                   7041:                         $uniqsymbs{$possible} = 1;
                   7042:                     }
                   7043:                 }
                   7044:             }
                   7045:         }
                   7046:         if ($use_symbs_in_map) {
                   7047:             map { $uniqsymbs{$_} = 1; } @symbs_in_map;
                   7048:         }
                   7049:         my @posslaunchers;
                   7050:         if (keys(%possmappb)) {
                   7051:             push(@posslaunchers,keys(%possmappb));
                   7052:         }
                   7053:         if (keys(%possrespb)) {
                   7054:             push(@posslaunchers,keys(%possrespb));
                   7055:         }
                   7056:         if (@posslaunchers) {
                   7057:             my (%pbsave,%skip_passback,%needpb);
                   7058:             my %pbids = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@posslaunchers,$udom,$uname);
                   7059:             foreach my $key (keys(%pbids)) {
                   7060:                 if (ref($pbids{$key}) eq 'ARRAY') {
1.806     raeburn  7061:                     if ($launch_to_symb{$key}) {
                   7062:                         $needpb{$key} = $launch_to_symb{$key};
                   7063:                     }
1.798     raeburn  7064:                 }
                   7065:             }
                   7066:             my @symbs = keys(%uniqsymbs);
1.802     raeburn  7067:             &process_passbacks('updatebypage',\@symbs,$cdom,$cnum,$udom,$uname,$usec,\%weights,
1.798     raeburn  7068:                                \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave,\%pbids);
1.801     raeburn  7069:             if (@Apache::grades::ltipassback) {
1.798     raeburn  7070:                 unless ($registered_cleanup) {
                   7071:                     my $handlers = $request->get_handlers('PerlCleanupHandler');
                   7072:                     $request->set_handlers('PerlCleanupHandler' =>
1.801     raeburn  7073:                                            [\&Apache::grades::make_passback,@{$handlers}]);
                   7074:                     $registered_cleanup=1;
1.798     raeburn  7075:                 }
                   7076:             }
                   7077:         }
                   7078:     }
1.70      ng       7079:     return '';
                   7080: }
                   7081: 
1.801     raeburn  7082: sub make_passback {
                   7083:     if (@Apache::grades::ltipassback) {
                   7084:         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7085:         my $ip = &Apache::lonnet::get_host_ip($lonhost);
                   7086:         foreach my $item (@Apache::grades::ltipassback) {
                   7087:             &Apache::lonhomework::run_passback($item,$lonhost,$ip);
                   7088:         }
                   7089:         undef(@Apache::grades::ltipassback);
                   7090:     }
                   7091: }
                   7092: 
1.72      ng       7093: #-------- end of section for handling grading by page/sequence ---------
                   7094: #
                   7095: #-------------------------------------------------------------------
                   7096: 
1.581     www      7097: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 7098: #
                   7099: #------ start of section for handling grading by page/sequence ---------
                   7100: 
1.423     albertel 7101: =pod
                   7102: 
                   7103: =head1 Bubble sheet grading routines
                   7104: 
1.424     albertel 7105:   For this documentation:
                   7106: 
                   7107:    'scanline' refers to the full line of characters
                   7108:    from the file that we are parsing that represents one entire sheet
                   7109: 
                   7110:    'bubble line' refers to the data
1.659     raeburn  7111:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 7112: 
                   7113: 
1.659     raeburn  7114: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 7115: into a course. When a user wants to grade, they select a
1.659     raeburn  7116: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 7117: one of the predefined configurations for what each scanline looks
                   7118: like.
                   7119: 
                   7120: Next each scanline is checked for any errors of either 'missing
1.435     foxr     7121: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 7122: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   7123: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  7124: invalid student/employee ID
1.424     albertel 7125: 
                   7126: If the CODE option is used that determines the randomization of the
1.556     weissno  7127: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 7128: username:domain.
                   7129: 
                   7130: During the validation phase the instructor can choose to skip scanlines. 
                   7131: 
1.659     raeburn  7132: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 7133: 
                   7134:   scantron_original_filename (unmodified original file)
                   7135:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   7136:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   7137: 
                   7138: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  7139: correction information that isn't representable in the bubblesheet
1.424     albertel 7140: file (see &scantron_getfile() for more information)
                   7141: 
                   7142: After all scanlines are either valid, marked as valid or skipped, then
                   7143: foreach line foreach problem in the picked sequence, an ssi request is
                   7144: made that simulates a user submitting their selected letter(s) against
                   7145: the homework problem.
1.423     albertel 7146: 
                   7147: =over 4
                   7148: 
                   7149: 
                   7150: 
                   7151: =item defaultFormData
                   7152: 
                   7153:   Returns html hidden inputs used to hold context/default values.
                   7154: 
                   7155:  Arguments:
                   7156:   $symb - $symb of the current resource 
                   7157: 
                   7158: =cut
1.422     foxr     7159: 
1.81      albertel 7160: sub defaultFormData {
1.324     albertel 7161:     my ($symb)=@_;
1.766     raeburn  7162:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 7163: }
                   7164: 
1.447     foxr     7165: 
1.423     albertel 7166: =pod 
                   7167: 
                   7168: =item getSequenceDropDown
                   7169: 
                   7170:    Return html dropdown of possible sequences to grade
                   7171:  
                   7172:  Arguments:
1.582     raeburn  7173:    $symb - $symb of the current resource
                   7174:    $map_error - ref to scalar which will container error if
                   7175:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 7176: 
                   7177: =cut
1.422     foxr     7178: 
1.75      albertel 7179: sub getSequenceDropDown {
1.582     raeburn  7180:     my ($symb,$map_error)=@_;
1.75      albertel 7181:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  7182:     my ($titles,$symbx) = &getSymbMap($map_error);
                   7183:     if (ref($map_error)) {
                   7184:         return if ($$map_error);
                   7185:     }
1.137     albertel 7186:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 7187:     my $ctr=0;
                   7188:     foreach (@$titles) {
                   7189: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   7190: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 7191: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 7192: 	    '>'.$showtitle.'</option>'."\n";
                   7193: 	$ctr++;
                   7194:     }
                   7195:     $result.= '</select>';
                   7196:     return $result;
                   7197: }
                   7198: 
1.495     albertel 7199: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  7200:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 7201: 
                   7202: my %first_bubble_line;             # First bubble line no. for each bubble.
                   7203: 
1.509     raeburn  7204: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   7205:                                    # matchresponse or rankresponse, where 
                   7206:                                    # an individual response can have multiple 
                   7207:                                    # lines
1.503     raeburn  7208: 
                   7209: my %responsetype_per_response;     # responsetype for each response
                   7210: 
1.691     raeburn  7211: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   7212:                                    # numbered response. Needed when randomorder
                   7213:                                    # or randompick are in use. Key is ID, value 
                   7214:                                    # is response number.
                   7215: 
1.495     albertel 7216: # Save and restore the bubble lines array to the form env.
                   7217: 
                   7218: 
                   7219: sub save_bubble_lines {
                   7220:     foreach my $line (keys(%bubble_lines_per_response)) {
                   7221: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   7222: 	$env{"form.scantron.first_bubble_line.$line"} =
                   7223: 	    $first_bubble_line{$line};
1.503     raeburn  7224:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   7225:             $subdivided_bubble_lines{$line};
                   7226:         $env{"form.scantron.responsetype.$line"} =
                   7227:             $responsetype_per_response{$line};
1.495     albertel 7228:     }
1.691     raeburn  7229:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   7230:         my $line = $masterseq_id_responsenum{$resid};
                   7231:         $env{"form.scantron.residpart.$line"} = $resid;
                   7232:     }
1.495     albertel 7233: }
                   7234: 
                   7235: 
                   7236: sub restore_bubble_lines {
                   7237:     my $line = 0;
                   7238:     %bubble_lines_per_response = ();
1.691     raeburn  7239:     %masterseq_id_responsenum = ();
1.495     albertel 7240:     while ($env{"form.scantron.bubblelines.$line"}) {
                   7241: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   7242: 	$bubble_lines_per_response{$line} = $value;
                   7243: 	$first_bubble_line{$line}  =
                   7244: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  7245:         $subdivided_bubble_lines{$line} =
                   7246:             $env{"form.scantron.sub_bubblelines.$line"};
                   7247:         $responsetype_per_response{$line} =
                   7248:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  7249:         my $id = $env{"form.scantron.residpart.$line"};
                   7250:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 7251: 	$line++;
                   7252:     }
                   7253: }
                   7254: 
1.423     albertel 7255: =pod 
                   7256: 
                   7257: =item scantron_filenames
                   7258: 
                   7259:    Returns a list of the scantron files in the current course 
                   7260: 
                   7261: =cut
1.422     foxr     7262: 
1.202     albertel 7263: sub scantron_filenames {
1.257     albertel 7264:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7265:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  7266:     my $getpropath = 1;
1.662     raeburn  7267:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   7268:                                                         $cname,$getpropath);
1.202     albertel 7269:     my @possiblenames;
1.662     raeburn  7270:     if (ref($dirlist) eq 'ARRAY') {
                   7271:         foreach my $filename (sort(@{$dirlist})) {
                   7272: 	    ($filename)=split(/&/,$filename);
                   7273: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   7274: 	    $filename=~s/^scantron_orig_//;
                   7275: 	    push(@possiblenames,$filename);
                   7276:         }
1.202     albertel 7277:     }
                   7278:     return @possiblenames;
                   7279: }
                   7280: 
1.423     albertel 7281: =pod 
                   7282: 
                   7283: =item scantron_uploads
                   7284: 
                   7285:    Returns  html drop-down list of scantron files in current course.
                   7286: 
                   7287:  Arguments:
                   7288:    $file2grade - filename to set as selected in the dropdown
                   7289: 
                   7290: =cut
1.422     foxr     7291: 
1.202     albertel 7292: sub scantron_uploads {
1.209     ng       7293:     my ($file2grade) = @_;
1.202     albertel 7294:     my $result=	'<select name="scantron_selectfile">';
                   7295:     $result.="<option></option>";
                   7296:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 7297: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 7298:     }
                   7299:     $result.="</select>";
                   7300:     return $result;
                   7301: }
                   7302: 
1.423     albertel 7303: =pod 
                   7304: 
                   7305: =item scantron_scantab
                   7306: 
                   7307:   Returns html drop down of the scantron formats in the scantronformat.tab
                   7308:   file.
                   7309: 
                   7310: =cut
1.422     foxr     7311: 
1.82      albertel 7312: sub scantron_scantab {
                   7313:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 7314:     $result.='<option></option>'."\n";
1.754     raeburn  7315:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  7316:     if (@lines > 0) {
                   7317:         foreach my $line (@lines) {
                   7318:             next if (($line =~ /^\#/) || ($line eq ''));
                   7319: 	    my ($name,$descrip)=split(/:/,$line);
                   7320: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   7321:         }
1.82      albertel 7322:     }
                   7323:     $result.='</select>'."\n";
1.518     raeburn  7324:     return $result;
                   7325: }
                   7326: 
1.423     albertel 7327: =pod 
                   7328: 
                   7329: =item scantron_CODElist
                   7330: 
                   7331:   Returns html drop down of the saved CODE lists from current course,
                   7332:   generated from earlier printings.
                   7333: 
                   7334: =cut
1.422     foxr     7335: 
1.186     albertel 7336: sub scantron_CODElist {
1.257     albertel 7337:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7338:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 7339:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   7340:     my $namechoice='<option></option>';
1.225     albertel 7341:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 7342: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 7343: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 7344: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   7345:     }
                   7346:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   7347:     return $namechoice;
                   7348: }
                   7349: 
1.423     albertel 7350: =pod 
                   7351: 
                   7352: =item scantron_CODEunique
                   7353: 
                   7354:   Returns the html for "Each CODE to be used once" radio.
                   7355: 
                   7356: =cut
1.422     foxr     7357: 
1.186     albertel 7358: sub scantron_CODEunique {
1.532     bisitz   7359:     my $result='<span class="LC_nobreak">
1.272     albertel 7360:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7361:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 7362:                 </span>
1.532     bisitz   7363:                 <span class="LC_nobreak">
1.272     albertel 7364:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7365:                         value="no" />'.&mt('No').' </label>
1.381     albertel 7366:                 </span>';
1.186     albertel 7367:     return $result;
                   7368: }
1.423     albertel 7369: 
                   7370: =pod 
                   7371: 
                   7372: =item scantron_selectphase
                   7373: 
1.659     raeburn  7374:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 7375:   Allows for - starting a grading run.
1.424     albertel 7376:              - downloading existing scan data (original, corrected
1.423     albertel 7377:                                                 or skipped info)
                   7378: 
                   7379:              - uploading new scan data
                   7380: 
                   7381:  Arguments:
                   7382:   $r          - The Apache request object
                   7383:   $file2grade - name of the file that contain the scanned data to score
                   7384: 
                   7385: =cut
1.186     albertel 7386: 
1.75      albertel 7387: sub scantron_selectphase {
1.608     www      7388:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 7389:     if (!$symb) {return '';}
1.582     raeburn  7390:     my $map_error;
                   7391:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   7392:     if ($map_error) {
                   7393:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   7394:         return;
                   7395:     }
1.324     albertel 7396:     my $default_form_data=&defaultFormData($symb);
1.209     ng       7397:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 7398:     my $format_selector=&scantron_scantab();
1.186     albertel 7399:     my $CODE_selector=&scantron_CODElist();
                   7400:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 7401:     my $result;
1.422     foxr     7402: 
1.513     foxr     7403:     $ssi_error = 0;
                   7404: 
1.770     raeburn  7405:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 7406: 
                   7407: 	# Chunk of form to prompt for a scantron file upload.
                   7408: 
                   7409:         $r->print('
1.754     raeburn  7410:     <br />');
1.606     wenzelju 7411:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7412:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  7413:     my $csec= $env{'request.course.sec'};
1.736     damieng  7414:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   7415:     &js_escape(\$alertmsg);
1.754     raeburn  7416:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 7417:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   7418:     function checkUpload(formname) {
                   7419: 	if (formname.upfile.value == "") {
1.736     damieng  7420: 	    alert("'.$alertmsg.'");
1.606     wenzelju 7421: 	    return false;
                   7422: 	}
                   7423: 	formname.submit();
1.756     raeburn  7424:     }'."\n".$formatjs));
1.606     wenzelju 7425:     $r->print('
                   7426:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7427:                 '.$default_form_data.'
                   7428:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  7429:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 7430:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   7431:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  7432:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7433:               '.&Apache::loncommon::start_data_table_header_row().'
                   7434:                 <th>
                   7435:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   7436:                 </th>
                   7437:               '.&Apache::loncommon::end_data_table_header_row().'
                   7438:               '.&Apache::loncommon::start_data_table_row().'
                   7439:             <td>
                   7440:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   7441:     if ($formatoptions) {
                   7442:         $r->print('</td>
                   7443:                  '.&Apache::loncommon::end_data_table_row().'
                   7444:                  '.&Apache::loncommon::start_data_table_row().'
                   7445:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   7446:                  </td>
                   7447:                  '.&Apache::loncommon::end_data_table_row().'
                   7448:                  '.&Apache::loncommon::start_data_table_row().'
                   7449:                  <td>'
                   7450:         );
                   7451:     } else {
                   7452:         $r->print(' <br />');
                   7453:     }
                   7454:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   7455:               </td>
                   7456:              '.&Apache::loncommon::end_data_table_row().'
                   7457:              '.&Apache::loncommon::end_data_table().'
                   7458:              </form>'
                   7459:     );
1.606     wenzelju 7460: 
                   7461:     }
                   7462: 
1.422     foxr     7463:     # Chunk of form to prompt for a file to grade and how:
                   7464: 
1.489     albertel 7465:     $result.= '
                   7466:     <br />
                   7467:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   7468:     <input type="hidden" name="command" value="scantron_warning" />
                   7469:     '.$default_form_data.'
                   7470:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7471:        '.&Apache::loncommon::start_data_table_header_row().'
                   7472:             <th colspan="2">
1.492     albertel 7473:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 7474:             </th>
                   7475:        '.&Apache::loncommon::end_data_table_header_row().'
                   7476:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7477:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 7478:        '.&Apache::loncommon::end_data_table_row().'
                   7479:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      7480:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 7481:        '.&Apache::loncommon::end_data_table_row().'
                   7482:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      7483:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 7484:        '.&Apache::loncommon::end_data_table_row().'
                   7485:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7486:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 7487:        '.&Apache::loncommon::end_data_table_row().'
                   7488:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7489:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 7490:        '.&Apache::loncommon::end_data_table_row().'
                   7491:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7492: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 7493:             <td>
1.492     albertel 7494: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   7495:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   7496:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 7497: 	    </td>
1.489     albertel 7498:        '.&Apache::loncommon::end_data_table_row().'
                   7499:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 7500:             <td colspan="2">
1.572     www      7501:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 7502:             </td>
1.489     albertel 7503:        '.&Apache::loncommon::end_data_table_row().'
                   7504:     '.&Apache::loncommon::end_data_table().'
                   7505:     </form>
                   7506: ';
1.162     albertel 7507:    
                   7508:     $r->print($result);
                   7509: 
1.422     foxr     7510:     # Chunk of the form that prompts to view a scoring office file,
                   7511:     # corrected file, skipped records in a file.
                   7512: 
1.489     albertel 7513:     $r->print('
                   7514:    <br />
                   7515:    <form action="/adm/grades" name="scantron_download">
                   7516:      '.$default_form_data.'
                   7517:      <input type="hidden" name="command" value="scantron_download" />
                   7518:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7519:        '.&Apache::loncommon::start_data_table_header_row().'
                   7520:               <th>
1.492     albertel 7521:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 7522:               </th>
                   7523:        '.&Apache::loncommon::end_data_table_header_row().'
                   7524:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7525:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 7526:                 <br />
1.492     albertel 7527:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 7528:        '.&Apache::loncommon::end_data_table_row().'
                   7529:      '.&Apache::loncommon::end_data_table().'
                   7530:    </form>
                   7531:    <br />
                   7532: ');
1.162     albertel 7533: 
1.457     banghart 7534:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  7535: 
1.694     bisitz   7536:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  7537:              $default_form_data."\n".
                   7538:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   7539:              &Apache::loncommon::start_data_table_header_row()."\n".
                   7540:              '<th colspan="2">
1.572     www      7541:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  7542:              '</th>'."\n".
                   7543:               &Apache::loncommon::end_data_table_header_row()."\n".
                   7544:               &Apache::loncommon::start_data_table_row()."\n".
                   7545:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   7546:               '<td> '.$sequence_selector.' </td>'.
                   7547:               &Apache::loncommon::end_data_table_row()."\n".
                   7548:               &Apache::loncommon::start_data_table_row()."\n".
                   7549:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   7550:               '<td> '.$file_selector.' </td>'."\n".
                   7551:               &Apache::loncommon::end_data_table_row()."\n".
                   7552:               &Apache::loncommon::start_data_table_row()."\n".
                   7553:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   7554:               '<td> '.$format_selector.' </td>'."\n".
                   7555:               &Apache::loncommon::end_data_table_row()."\n".
                   7556:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  7557:               '<td> '.&mt('Options').' </td>'."\n".
                   7558:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   7559:               &Apache::loncommon::end_data_table_row()."\n".
                   7560:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  7561:               '<td colspan="2">'."\n".
                   7562:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      7563:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  7564:               '</td>'."\n".
                   7565:               &Apache::loncommon::end_data_table_row()."\n".
                   7566:               &Apache::loncommon::end_data_table()."\n".
                   7567:               '</form><br />');
                   7568:     return;
1.75      albertel 7569: }
                   7570: 
1.423     albertel 7571: =pod 
                   7572: 
                   7573: =item username_to_idmap
                   7574: 
1.556     weissno  7575:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  7576:     student username:domain. If a single ID occurs for more than one student,
                   7577:     the status of the student is checked, and if Active, the value in the hash
                   7578:     will be set to the Active student.
1.423     albertel 7579: 
                   7580:   Arguments:
                   7581: 
                   7582:     $classlist - reference to the class list hash. This is a hash
                   7583:                  keyed by student name:domain  whose elements are references
1.424     albertel 7584:                  to arrays containing various chunks of information
1.423     albertel 7585:                  about the student. (See loncoursedata for more info).
                   7586: 
                   7587:   Returns
                   7588:     %idmap - the constructed hash
                   7589: 
                   7590: =cut
                   7591: 
1.82      albertel 7592: sub username_to_idmap {
                   7593:     my ($classlist)= @_;
                   7594:     my %idmap;
                   7595:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  7596:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   7597:         unless ($id eq '') {
                   7598:             if (!exists($idmap{$id})) {
                   7599:                 $idmap{$id} = $student;
                   7600:             } else {
                   7601:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   7602:                 if ($status eq 'Active') {
                   7603:                     $idmap{$id} = $student;
                   7604:                 }
                   7605:             }
                   7606:         }
1.82      albertel 7607:     }
                   7608:     return %idmap;
                   7609: }
1.423     albertel 7610: 
                   7611: =pod
                   7612: 
1.424     albertel 7613: =item scantron_fixup_scanline
1.423     albertel 7614: 
                   7615:    Process a requested correction to a scanline.
                   7616: 
                   7617:   Arguments:
1.754     raeburn  7618:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 7619:     $scan_data         - hash of correction information 
                   7620:                           (see &scantron_getfile())
                   7621:     $line              - existing scanline
                   7622:     $whichline         - line number of the passed in scanline
                   7623:     $field             - type of change to process 
                   7624:                          (either 
1.573     bisitz   7625:                           'ID'     -> correct the student/employee ID
1.423     albertel 7626:                           'CODE'   -> correct the CODE
                   7627:                           'answer' -> fixup the submitted answers)
                   7628:     
                   7629:    $args               - hash of additional info,
                   7630:                           - 'ID' 
                   7631:                                'newid' -> studentID to use in replacement
1.424     albertel 7632:                                           of existing one
1.423     albertel 7633:                           - 'CODE' 
                   7634:                                'CODE_ignore_dup' - set to true if duplicates
                   7635:                                                    should be ignored.
                   7636: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 7637:                                         if the existing unfound code should
1.423     albertel 7638:                                         be used as is
                   7639:                           - 'answer'
                   7640:                                'response' - new answer or 'none' if blank
                   7641:                                'question' - the bubble line to change
1.503     raeburn  7642:                                'questionnum' - the question identifier,
                   7643:                                                may include subquestion. 
1.423     albertel 7644: 
                   7645:   Returns:
                   7646:     $line - the modified scanline
                   7647: 
                   7648:   Side effects: 
                   7649:     $scan_data - may be updated
                   7650: 
                   7651: =cut
                   7652: 
1.82      albertel 7653: 
1.157     albertel 7654: sub scantron_fixup_scanline {
                   7655:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   7656:     if ($field eq 'ID') {
                   7657: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 7658: 	    return ($line,1,'New value too large');
1.157     albertel 7659: 	}
                   7660: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   7661: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   7662: 				     $args->{'newid'});
                   7663: 	}
                   7664: 	substr($line,$$scantron_config{'IDstart'}-1,
                   7665: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   7666: 	if ($args->{'newid'}=~/^\s*$/) {
                   7667: 	    &scan_data($scan_data,"$whichline.user",
                   7668: 		       $args->{'username'}.':'.$args->{'domain'});
                   7669: 	}
1.186     albertel 7670:     } elsif ($field eq 'CODE') {
1.192     albertel 7671: 	if ($args->{'CODE_ignore_dup'}) {
                   7672: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   7673: 	}
                   7674: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   7675: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 7676: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   7677: 		return ($line,1,'New CODE value too large');
                   7678: 	    }
                   7679: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   7680: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   7681: 	    }
                   7682: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   7683: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 7684: 	}
1.157     albertel 7685:     } elsif ($field eq 'answer') {
1.497     foxr     7686: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 7687: 	my $off=$scantron_config->{'Qoff'};
                   7688: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     7689: 	my $answer=${off}x$length;
                   7690: 	if ($args->{'response'} eq 'none') {
                   7691: 	    &scan_data($scan_data,
1.503     raeburn  7692: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     7693: 	} else {
                   7694: 	    if ($on eq 'letter') {
                   7695: 		my @alphabet=('A'..'Z');
                   7696: 		$answer=$alphabet[$args->{'response'}];
                   7697: 	    } elsif ($on eq 'number') {
                   7698: 		$answer=$args->{'response'}+1;
                   7699: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 7700: 	    } else {
1.497     foxr     7701: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 7702: 	    }
1.497     foxr     7703: 	    &scan_data($scan_data,
1.503     raeburn  7704: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 7705: 	}
1.497     foxr     7706: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   7707: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 7708:     }
                   7709:     return $line;
                   7710: }
1.423     albertel 7711: 
                   7712: =pod
                   7713: 
                   7714: =item scan_data
                   7715: 
                   7716:     Edit or look up  an item in the scan_data hash.
                   7717: 
                   7718:   Arguments:
                   7719:     $scan_data  - The hash (see scantron_getfile)
                   7720:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 7721:                   scantronfilename_key).
1.423     albertel 7722:     $data        - New value of the hash entry.
                   7723:     $delete      - If true, the entry is removed from the hash.
                   7724: 
                   7725:   Returns:
                   7726:     The new value of the hash table field (undefined if deleted).
                   7727: 
                   7728: =cut
                   7729: 
                   7730: 
1.157     albertel 7731: sub scan_data {
                   7732:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 7733:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 7734:     if (defined($value)) {
                   7735: 	$scan_data->{$filename.'_'.$key} = $value;
                   7736:     }
                   7737:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   7738:     return $scan_data->{$filename.'_'.$key};
                   7739: }
1.423     albertel 7740: 
1.495     albertel 7741: # ----- These first few routines are general use routines.----
                   7742: 
                   7743: # Return the number of occurences of a pattern in a string.
                   7744: 
                   7745: sub occurence_count {
                   7746:     my ($string, $pattern) = @_;
                   7747: 
                   7748:     my @matches = ($string =~ /$pattern/g);
                   7749: 
                   7750:     return scalar(@matches);
                   7751: }
                   7752: 
                   7753: 
                   7754: # Take a string known to have digits and convert all the
                   7755: # digits into letters in the range J,A..I.
                   7756: 
                   7757: sub digits_to_letters {
                   7758:     my ($input) = @_;
                   7759: 
                   7760:     my @alphabet = ('J', 'A'..'I');
                   7761: 
                   7762:     my @input    = split(//, $input);
                   7763:     my $output ='';
                   7764:     for (my $i = 0; $i < scalar(@input); $i++) {
                   7765: 	if ($input[$i] =~ /\d/) {
                   7766: 	    $output .= $alphabet[$input[$i]];
                   7767: 	} else {
                   7768: 	    $output .= $input[$i];
                   7769: 	}
                   7770:     }
                   7771:     return $output;
                   7772: }
                   7773: 
1.423     albertel 7774: =pod 
                   7775: 
                   7776: =item scantron_parse_scanline
                   7777: 
1.711     bisitz   7778:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 7779: 
                   7780:  Arguments:
1.711     bisitz   7781:     line             - The text of the bubblesheet file line to process
1.423     albertel 7782:     whichline        - Line number
1.711     bisitz   7783:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 7784:     scan_data        - Hash of extra information about the scanline
                   7785:                        (see scantron_getfile for more information)
                   7786:     just_header      - True if should not process question answers but only
                   7787:                        the stuff to the left of the answers.
1.691     raeburn  7788:     randomorder      - True if randomorder in use
                   7789:     randompick       - True if randompick in use
                   7790:     sequence         - Exam folder URL
                   7791:     master_seq       - Ref to array containing symbs in exam folder
                   7792:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   7793:                        (corresponding values are resource objects)
                   7794:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   7795:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   7796:                        are refs to an array of resource objects, ordered
                   7797:                        according to order used for CODE, when randomorder
                   7798:                        and or randompick are in use.
                   7799:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   7800:                        for current line to question number used for same question
                   7801:                         in "Master Sequence" (as seen by Course Coordinator).
                   7802:     startline        - Ref to hash where key is question number (0 is first)
                   7803:                        and value is number of first bubble line for current 
                   7804:                        student or code-based randompick and/or randomorder.
                   7805:     totalref         - Ref of scalar used to score total number of bubble
                   7806:                        lines needed for responses in a scan line (used when
                   7807:                        randompick in use. 
                   7808:     
1.423     albertel 7809:  Returns:
                   7810:    Hash containing the result of parsing the scanline
                   7811: 
                   7812:    Keys are all proceeded by the string 'scantron.'
                   7813: 
                   7814:        CODE    - the CODE in use for this scanline
                   7815:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   7816:                  by the operator
                   7817:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   7818:                             CODEs were selected, but the usage has been
                   7819:                             forced by the operator
1.556     weissno  7820:        ID  - student/employee ID
1.423     albertel 7821:        PaperID - if used, the ID number printed on the sheet when the 
                   7822:                  paper was scanned
                   7823:        FirstName - first name from the sheet
                   7824:        LastName  - last name from the sheet
                   7825: 
                   7826:      if just_header was not true these key may also exist
                   7827: 
1.447     foxr     7828:        missingerror - a list of bubble ranges that are considered to be answers
                   7829:                       to a single question that don't have any bubbles filled in.
                   7830:                       Of the form questionnumber:firstbubblenumber:count.
                   7831:        doubleerror  - a list of bubble ranges that are considered to be answers
                   7832:                       to a single question that have more than one bubble filled in.
                   7833:                       Of the form questionnumber::firstbubblenumber:count
                   7834:    
                   7835:                 In the above, count is the number of bubble responses in the
                   7836:                 input line needed to represent the possible answers to the question.
                   7837:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   7838:                 per line would have count = 2.
                   7839: 
1.423     albertel 7840:        maxquest     - the number of the last bubble line that was parsed
                   7841: 
                   7842:        (<number> starts at 1)
                   7843:        <number>.answer - zero or more letters representing the selected
                   7844:                          letters from the scanline for the bubble line 
                   7845:                          <number>.
                   7846:                          if blank there was either no bubble or there where
                   7847:                          multiple bubbles, (consult the keys missingerror and
                   7848:                          doubleerror if this is an error condition)
                   7849: 
                   7850: =cut
                   7851: 
1.82      albertel 7852: sub scantron_parse_scanline {
1.691     raeburn  7853:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   7854:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   7855:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     7856: 
1.82      albertel 7857:     my %record;
1.691     raeburn  7858:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 7859:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   7860: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   7861: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   7862: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   7863: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 7864: 	    $record{'scantron.CODE'}=substr($data,
                   7865: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 7866: 					    $$scantron_config{'CODElength'});
1.191     albertel 7867: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   7868: 		$record{'scantron.useCODE'}=1;
                   7869: 	    }
1.192     albertel 7870: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   7871: 		$record{'scantron.CODE_ignore_dup'}=1;
                   7872: 	    }
1.82      albertel 7873: 	} else {
                   7874: 	    #FIXME interpret first N questions
                   7875: 	}
                   7876:     }
1.83      albertel 7877:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   7878: 				  $$scantron_config{'IDlength'});
1.157     albertel 7879:     $record{'scantron.PaperID'}=
                   7880: 	substr($data,$$scantron_config{'PaperID'}-1,
                   7881: 	       $$scantron_config{'PaperIDlength'});
                   7882:     $record{'scantron.FirstName'}=
                   7883: 	substr($data,$$scantron_config{'FirstName'}-1,
                   7884: 	       $$scantron_config{'FirstNamelength'});
                   7885:     $record{'scantron.LastName'}=
                   7886: 	substr($data,$$scantron_config{'LastName'}-1,
                   7887: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 7888:     if ($just_header) { return \%record; }
1.194     albertel 7889: 
1.82      albertel 7890:     my @alphabet=('A'..'Z');
                   7891:     my $questnum=0;
1.447     foxr     7892:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   7893: 
1.691     raeburn  7894:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   7895:     if ($randompick || $randomorder) {
                   7896:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   7897:                                          $master_seq,$symb_to_resource,
                   7898:                                          $partids_by_symb,$orderedforcode,
                   7899:                                          $respnumlookup,$startline);
                   7900:         if ($total) {
                   7901:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   7902:         }
                   7903:         if (ref($totalref)) {
                   7904:             $$totalref = $total;
                   7905:         }
                   7906:     }
                   7907:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     7908:     chomp($questions);		# Get rid of any trailing \n.
                   7909:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   7910:     while (length($questions)) {
1.691     raeburn  7911:         my $answers_needed;
                   7912:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7913:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   7914:         } else {
                   7915: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   7916:         }
1.503     raeburn  7917:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   7918:                              || 1;
                   7919:         $questnum++;
                   7920:         my $quest_id = $questnum;
                   7921:         my $currentquest = substr($questions,0,$answer_length);
                   7922:         $questions       = substr($questions,$answer_length);
                   7923:         if (length($currentquest) < $answer_length) { next; }
                   7924: 
1.691     raeburn  7925:         my $subdivided;
                   7926:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7927:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   7928:         } else {
                   7929:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   7930:         }
                   7931:         if ($subdivided =~ /,/) {
1.503     raeburn  7932:             my $subquestnum = 1;
                   7933:             my $subquestions = $currentquest;
1.691     raeburn  7934:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  7935:             foreach my $subans (@subanswers_needed) {
                   7936:                 my $subans_length =
                   7937:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   7938:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   7939:                 $subquestions   = substr($subquestions,$subans_length);
                   7940:                 $quest_id = "$questnum.$subquestnum";
                   7941:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   7942:                     ($$scantron_config{'Qon'} eq 'number')) {
                   7943:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   7944:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  7945:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7946:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7947:                 } else {
                   7948:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  7949:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   7950:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7951:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7952:                 }
                   7953:                 $subquestnum ++;
                   7954:             }
                   7955:         } else {
                   7956:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   7957:                 ($$scantron_config{'Qon'} eq 'number')) {
                   7958:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   7959:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7960:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7961:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7962:             } else {
                   7963:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   7964:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7965:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7966:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7967:             }
                   7968:         }
                   7969:     }
                   7970:     $record{'scantron.maxquest'}=$questnum;
                   7971:     return \%record;
                   7972: }
1.447     foxr     7973: 
1.691     raeburn  7974: sub get_master_seq {
1.788     raeburn  7975:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
1.691     raeburn  7976:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   7977:                    (ref($symb_to_resource) eq 'HASH'));
1.788     raeburn  7978:     if ($need_symb_in_map) {
                   7979:         return unless (ref($symb_for_examcode) eq 'HASH');
                   7980:     }
1.691     raeburn  7981:     my $resource_error;
                   7982:     foreach my $resource (@{$resources}) {
                   7983:         my $ressymb;
                   7984:         if (ref($resource)) {
                   7985:             $ressymb = $resource->symb();
                   7986:             push(@{$master_seq},$ressymb);
                   7987:             $symb_to_resource->{$ressymb} = $resource;
1.788     raeburn  7988:             if ($need_symb_in_map) {
                   7989:                 unless ($resource->is_map()) {
                   7990:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   7991:                     unless (exists($symb_for_examcode->{$map})) {
                   7992:                         $symb_for_examcode->{$map} = $ressymb;
                   7993:                     }
                   7994:                 }
                   7995:             }
1.691     raeburn  7996:         } else {
                   7997:             $resource_error = 1;
                   7998:             last;
                   7999:         }
                   8000:     }
                   8001:     return $resource_error;
                   8002: }
                   8003: 
                   8004: sub get_respnum_lookups {
                   8005:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   8006:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   8007:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   8008:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   8009:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   8010:                    (ref($startline) eq 'HASH'));
                   8011:     my ($user,$scancode);
                   8012:     if ((exists($record->{'scantron.CODE'})) &&
                   8013:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   8014:         $scancode = $record->{'scantron.CODE'};
                   8015:     } else {
                   8016:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   8017:     }
                   8018:     my @mapresources =
                   8019:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   8020:                      $orderedforcode);
                   8021:     my $total = 0;
                   8022:     my $count = 0;
                   8023:     foreach my $resource (@mapresources) {
                   8024:         my $id = $resource->id();
                   8025:         my $symb = $resource->symb();
                   8026:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   8027:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   8028:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   8029:                 if ($respnum ne '') {
                   8030:                     $respnumlookup->{$count} = $respnum;
                   8031:                     $startline->{$count} = $total;
                   8032:                     $total += $bubble_lines_per_response{$respnum};
                   8033:                     $count ++;
                   8034:                 }
                   8035:             }
                   8036:         }
                   8037:     }
                   8038:     return $total;
                   8039: }
                   8040: 
1.503     raeburn  8041: sub scantron_validator_lettnum {
                   8042:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  8043:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   8044:         $randompick,$respnumlookup) = @_;
1.503     raeburn  8045: 
                   8046:     # Qon 'letter' implies for each slot in currquest we have:
                   8047:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   8048:     #    about anything else (esp. a value of Qoff) for missing
                   8049:     #    bubbles.
                   8050:     #
                   8051:     # Qon 'number' implies each slot gives a digit that indexes the
                   8052:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   8053:     #    and * or ? for double bubbles on a single line.
                   8054:     #
1.447     foxr     8055: 
1.503     raeburn  8056:     my $matchon;
                   8057:     if ($$scantron_config{'Qon'} eq 'letter') {
                   8058:         $matchon = '[A-Z]';
                   8059:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   8060:         $matchon = '\d';
                   8061:     }
                   8062:     my $occurrences = 0;
1.691     raeburn  8063:     my $responsenum = $questnum-1;
                   8064:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   8065:        $responsenum = $respnumlookup->{$questnum-1} 
                   8066:     }
                   8067:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8068:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8069:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8070:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8071:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8072:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8073:         my @singlelines = split('',$currquest);
                   8074:         foreach my $entry (@singlelines) {
                   8075:             $occurrences = &occurence_count($entry,$matchon);
                   8076:             if ($occurrences > 1) {
                   8077:                 last;
                   8078:             }
1.691     raeburn  8079:         }
1.503     raeburn  8080:     } else {
                   8081:         $occurrences = &occurence_count($currquest,$matchon); 
                   8082:     }
                   8083:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   8084:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8085:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8086:             my $bubble = substr($currquest,$ans,1);
                   8087:             if ($bubble =~ /$matchon/ ) {
                   8088:                 if ($$scantron_config{'Qon'} eq 'number') {
                   8089:                     if ($bubble == 0) {
                   8090:                         $bubble = 10; 
                   8091:                     }
                   8092:                     $record->{"scantron.$ansnum.answer"} = 
                   8093:                         $alphabet->[$bubble-1];
                   8094:                 } else {
                   8095:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   8096:                 }
                   8097:             } else {
                   8098:                 $record->{"scantron.$ansnum.answer"}='';
                   8099:             }
                   8100:             $ansnum++;
                   8101:         }
                   8102:     } elsif (!defined($currquest)
                   8103:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   8104:             || (&occurence_count($currquest,$matchon) == 0)) {
                   8105:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8106:             $record->{"scantron.$ansnum.answer"}='';
                   8107:             $ansnum++;
                   8108:         }
                   8109:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8110:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   8111:         }
                   8112:     } else {
                   8113:         if ($$scantron_config{'Qon'} eq 'number') {
                   8114:             $currquest = &digits_to_letters($currquest);            
                   8115:         }
                   8116:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8117:             my $bubble = substr($currquest,$ans,1);
                   8118:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   8119:             $ansnum++;
                   8120:         }
                   8121:     }
                   8122:     return $ansnum;
                   8123: }
1.447     foxr     8124: 
1.503     raeburn  8125: sub scantron_validator_positional {
                   8126:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  8127:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   8128:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     8129: 
1.503     raeburn  8130:     # Otherwise there's a positional notation;
                   8131:     # each bubble line requires Qlength items, and there are filled in
                   8132:     # bubbles for each case where there 'Qon' characters.
                   8133:     #
1.447     foxr     8134: 
1.503     raeburn  8135:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     8136: 
1.503     raeburn  8137:     # If the split only gives us one element.. the full length of the
                   8138:     # answer string, no bubbles are filled in:
1.447     foxr     8139: 
1.507     raeburn  8140:     if ($answers_needed eq '') {
                   8141:         return;
                   8142:     }
                   8143: 
1.503     raeburn  8144:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   8145:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8146:             $record->{"scantron.$ansnum.answer"}='';
                   8147:             $ansnum++;
                   8148:         }
                   8149:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8150:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   8151:         }
                   8152:     } elsif (scalar(@array) == 2) {
                   8153:         my $location = length($array[0]);
                   8154:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   8155:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   8156:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8157:             if ($ans eq $line_num) {
                   8158:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   8159:             } else {
                   8160:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   8161:             }
                   8162:             $ansnum++;
                   8163:          }
                   8164:     } else {
                   8165:         #  If there's more than one instance of a bubble character
                   8166:         #  That's a double bubble; with positional notation we can
                   8167:         #  record all the bubbles filled in as well as the
                   8168:         #  fact this response consists of multiple bubbles.
                   8169:         #
1.691     raeburn  8170:         my $responsenum = $questnum-1;
                   8171:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   8172:             $responsenum = $respnumlookup->{$questnum-1}
                   8173:         }
                   8174:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8175:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8176:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8177:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8178:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8179:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8180:             my $doubleerror = 0;
                   8181:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   8182:                    (!$doubleerror)) {
                   8183:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   8184:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   8185:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   8186:                if (length(@currarray) > 2) {
                   8187:                    $doubleerror = 1;
                   8188:                } 
                   8189:             }
                   8190:             if ($doubleerror) {
                   8191:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8192:             }
                   8193:         } else {
                   8194:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8195:         }
                   8196:         my $item = $ansnum;
                   8197:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8198:             $record->{"scantron.$item.answer"} = '';
                   8199:             $item ++;
                   8200:         }
1.447     foxr     8201: 
1.503     raeburn  8202:         my @ans=@array;
                   8203:         my $i=0;
                   8204:         my $increment = 0;
                   8205:         while ($#ans) {
                   8206:             $i+=length($ans[0]) + $increment;
                   8207:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   8208:             my $bubble = $i%$$scantron_config{'Qlength'};
                   8209:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   8210:             shift(@ans);
                   8211:             $increment = 1;
                   8212:         }
                   8213:         $ansnum += $answers_needed;
1.82      albertel 8214:     }
1.503     raeburn  8215:     return $ansnum;
1.82      albertel 8216: }
                   8217: 
1.423     albertel 8218: =pod
                   8219: 
                   8220: =item scantron_add_delay
                   8221: 
                   8222:    Adds an error message that occurred during the grading phase to a
                   8223:    queue of messages to be shown after grading pass is complete
                   8224: 
                   8225:  Arguments:
1.424     albertel 8226:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 8227:    $scanline    - the scanline that caused the error
                   8228:    $errormesage - the error message
                   8229:    $errorcode   - a numeric code for the error
                   8230: 
                   8231:  Side Effects:
1.424     albertel 8232:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 8233: 
                   8234: =cut
                   8235: 
1.82      albertel 8236: sub scantron_add_delay {
1.140     albertel 8237:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   8238:     push(@$delayqueue,
                   8239: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   8240: 	  'ecode' => $errorcode }
                   8241: 	 );
1.82      albertel 8242: }
                   8243: 
1.423     albertel 8244: =pod
                   8245: 
                   8246: =item scantron_find_student
                   8247: 
1.424     albertel 8248:    Finds the username for the current scanline
                   8249: 
                   8250:   Arguments:
                   8251:    $scantron_record - hash result from scantron_parse_scanline
                   8252:    $scan_data       - hash of correction information 
                   8253:                       (see &scantron_getfile() form more information)
                   8254:    $idmap           - hash from &username_to_idmap()
                   8255:    $line            - number of current scanline
                   8256:  
                   8257:   Returns:
                   8258:    Either 'username:domain' or undef if unknown
                   8259: 
1.423     albertel 8260: =cut
                   8261: 
1.82      albertel 8262: sub scantron_find_student {
1.157     albertel 8263:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 8264:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 8265:     if ($scanID =~ /^\s*$/) {
                   8266:  	return &scan_data($scan_data,"$line.user");
                   8267:     }
1.83      albertel 8268:     foreach my $id (keys(%$idmap)) {
1.157     albertel 8269:  	if (lc($id) eq lc($scanID)) {
                   8270:  	    return $$idmap{$id};
                   8271:  	}
1.83      albertel 8272:     }
                   8273:     return undef;
                   8274: }
                   8275: 
1.423     albertel 8276: =pod
                   8277: 
                   8278: =item scantron_filter
                   8279: 
1.424     albertel 8280:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   8281:    hidden resources was selected
                   8282: 
1.423     albertel 8283: =cut
                   8284: 
1.83      albertel 8285: sub scantron_filter {
                   8286:     my ($curres)=@_;
1.331     albertel 8287: 
                   8288:     if (ref($curres) && $curres->is_problem()) {
                   8289: 	# if the user has asked to not have either hidden
                   8290: 	# or 'randomout' controlled resources to be graded
                   8291: 	# don't include them
                   8292: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   8293: 	    && $curres->randomout) {
                   8294: 	    return 0;
                   8295: 	}
1.83      albertel 8296: 	return 1;
                   8297:     }
                   8298:     return 0;
1.82      albertel 8299: }
                   8300: 
1.423     albertel 8301: =pod
                   8302: 
                   8303: =item scantron_process_corrections
                   8304: 
1.424     albertel 8305:    Gets correction information out of submitted form data and corrects
                   8306:    the scanline
                   8307: 
1.423     albertel 8308: =cut
                   8309: 
1.157     albertel 8310: sub scantron_process_corrections {
                   8311:     my ($r) = @_;
1.754     raeburn  8312:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8313:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8314:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 8315:     my $which=$env{'form.scantron_line'};
1.200     albertel 8316:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 8317:     my ($skip,$err,$errmsg);
1.257     albertel 8318:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 8319: 	$skip=1;
1.257     albertel 8320:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   8321: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   8322: 	    $env{'form.scantron_domain'};
1.157     albertel 8323: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   8324: 	($line,$err,$errmsg)=
                   8325: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   8326: 				     'ID',{'newid'=>$newid,
1.257     albertel 8327: 				    'username'=>$env{'form.scantron_username'},
                   8328: 				    'domain'=>$env{'form.scantron_domain'}});
                   8329:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   8330: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 8331: 	my $newCODE;
1.192     albertel 8332: 	my %args;
1.190     albertel 8333: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 8334: 	    $newCODE='use_unfound';
1.190     albertel 8335: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 8336: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 8337: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 8338: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 8339: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 8340: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 8341: 	}
1.257     albertel 8342: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 8343: 	    $args{'CODE_ignore_dup'}=1;
                   8344: 	}
                   8345: 	$args{'CODE'}=$newCODE;
1.186     albertel 8346: 	($line,$err,$errmsg)=
                   8347: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 8348: 				     'CODE',\%args);
1.257     albertel 8349:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   8350: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 8351: 	    ($line,$err,$errmsg)=
                   8352: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   8353: 					 $which,'answer',
                   8354: 					 { 'question'=>$question,
1.503     raeburn  8355: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   8356:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 8357: 	    if ($err) { last; }
                   8358: 	}
                   8359:     }
                   8360:     if ($err) {
1.703     bisitz   8361:         $r->print(
                   8362:             '<p class="LC_error">'
                   8363:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   8364:                 $errmsg)
1.704     raeburn  8365:            .'</p>');
1.157     albertel 8366:     } else {
1.200     albertel 8367: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 8368: 	&scantron_putfile($scanlines,$scan_data);
                   8369:     }
                   8370: }
                   8371: 
1.423     albertel 8372: =pod
                   8373: 
                   8374: =item reset_skipping_status
                   8375: 
1.424     albertel 8376:    Forgets the current set of remember skipped scanlines (and thus
                   8377:    reverts back to considering all lines in the
                   8378:    scantron_skipped_<filename> file)
                   8379: 
1.423     albertel 8380: =cut
                   8381: 
1.200     albertel 8382: sub reset_skipping_status {
                   8383:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8384:     &scan_data($scan_data,'remember_skipping',undef,1);
                   8385:     &scantron_putfile(undef,$scan_data);
                   8386: }
                   8387: 
1.423     albertel 8388: =pod
                   8389: 
                   8390: =item start_skipping
                   8391: 
1.424     albertel 8392:    Marks a scanline to be skipped. 
                   8393: 
1.423     albertel 8394: =cut
                   8395: 
1.376     albertel 8396: sub start_skipping {
1.200     albertel 8397:     my ($scan_data,$i)=@_;
                   8398:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8399:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   8400: 	$remembered{$i}=2;
                   8401:     } else {
                   8402: 	$remembered{$i}=1;
                   8403:     }
1.200     albertel 8404:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   8405: }
                   8406: 
1.423     albertel 8407: =pod
                   8408: 
                   8409: =item should_be_skipped
                   8410: 
1.424     albertel 8411:    Checks whether a scanline should be skipped.
                   8412: 
1.423     albertel 8413: =cut
                   8414: 
1.200     albertel 8415: sub should_be_skipped {
1.376     albertel 8416:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 8417:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 8418: 	# not redoing old skips
1.376     albertel 8419: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 8420: 	return 0;
                   8421:     }
                   8422:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8423: 
                   8424:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   8425: 	return 0;
                   8426:     }
1.200     albertel 8427:     return 1;
                   8428: }
                   8429: 
1.423     albertel 8430: =pod
                   8431: 
                   8432: =item remember_current_skipped
                   8433: 
1.424     albertel 8434:    Discovers what scanlines are in the scantron_skipped_<filename>
                   8435:    file and remembers them into scan_data for later use.
                   8436: 
1.423     albertel 8437: =cut
                   8438: 
1.200     albertel 8439: sub remember_current_skipped {
                   8440:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8441:     my %to_remember;
                   8442:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8443: 	if ($scanlines->{'skipped'}[$i]) {
                   8444: 	    $to_remember{$i}=1;
                   8445: 	}
                   8446:     }
1.376     albertel 8447: 
1.200     albertel 8448:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   8449:     &scantron_putfile(undef,$scan_data);
                   8450: }
                   8451: 
1.423     albertel 8452: =pod
                   8453: 
                   8454: =item check_for_error
                   8455: 
1.424     albertel 8456:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  8457:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 8458:     something went wrong.
                   8459: 
1.423     albertel 8460: =cut
                   8461: 
1.200     albertel 8462: sub check_for_error {
                   8463:     my ($r,$result)=@_;
                   8464:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 8465: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 8466:     }
                   8467: }
1.157     albertel 8468: 
1.423     albertel 8469: =pod
                   8470: 
                   8471: =item scantron_warning_screen
                   8472: 
1.424     albertel 8473:    Interstitial screen to make sure the operator has selected the
                   8474:    correct options before we start the validation phase.
                   8475: 
1.423     albertel 8476: =cut
                   8477: 
1.203     albertel 8478: sub scantron_warning_screen {
1.650     raeburn  8479:     my ($button_text,$symb)=@_;
1.257     albertel 8480:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  8481:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 8482:     my $CODElist;
1.284     albertel 8483:     if ($scantron_config{'CODElocation'} &&
                   8484: 	$scantron_config{'CODEstart'} &&
                   8485: 	$scantron_config{'CODElength'}) {
                   8486: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   8487: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 8488: 	$CODElist=
1.492     albertel 8489: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 8490: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 8491:     }
1.663     raeburn  8492:     my $lastbubblepoints;
                   8493:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8494:         $lastbubblepoints =
                   8495:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   8496:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   8497:     }
1.770     raeburn  8498:     return '
1.203     albertel 8499: <p>
1.492     albertel 8500: <span class="LC_warning">
1.705     raeburn  8501: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 8502: </p>
                   8503: <table>
1.492     albertel 8504: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   8505: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  8506: '.$CODElist.$lastbubblepoints.'
1.203     albertel 8507: </table>
1.680     raeburn  8508: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  8509: '.&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.770     raeburn  8510: ';
1.203     albertel 8511: }
                   8512: 
1.423     albertel 8513: =pod
                   8514: 
                   8515: =item scantron_do_warning
                   8516: 
1.424     albertel 8517:    Check if the operator has picked something for all required
                   8518:    fields. Error out if something is missing.
                   8519: 
1.423     albertel 8520: =cut
                   8521: 
1.203     albertel 8522: sub scantron_do_warning {
1.608     www      8523:     my ($r,$symb)=@_;
1.203     albertel 8524:     if (!$symb) {return '';}
1.324     albertel 8525:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 8526:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 8527:     if ( $env{'form.selectpage'} eq '' ||
                   8528: 	 $env{'form.scantron_selectfile'} eq '' ||
                   8529: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  8530: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 8531: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 8532: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 8533: 	} 
1.257     albertel 8534: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  8535: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
1.770     raeburn  8536: 	}
1.257     albertel 8537: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  8538: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
1.770     raeburn  8539: 	}
1.237     albertel 8540:     } else {
1.650     raeburn  8541: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  8542:         my ($checksec,@possibles) = &gradable_sections();
                   8543:         my $gradesections;
                   8544:         if ($checksec) {
                   8545:             my $file=$env{'form.scantron_selectfile'};
                   8546:             if (&valid_file($file)) {
                   8547:                 my %bysec = &scantron_get_sections();
                   8548:                 my $table;
                   8549:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   8550:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   8551:                     $table = &Apache::loncommon::start_data_table()."\n".
                   8552:                              &Apache::loncommon::start_data_table_header_row().
                   8553:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   8554:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   8555:                     if ($bysec{'none'}) {
                   8556:                         $table .= &Apache::loncommon::start_data_table_row().
                   8557:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   8558:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8559:                     }
                   8560:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   8561:                         next if ($sec eq 'none');
                   8562:                         $table .= &Apache::loncommon::start_data_table_row().
                   8563:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   8564:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8565:                     }
                   8566:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   8567:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   8568:                                       '<p>'.$table.'</p>';
                   8569:                     if (@possibles) {
                   8570:                         $gradesections .= '<p>'.
                   8571:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   8572:                                               scalar(@possibles)).'<br />'.
                   8573:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   8574:                                               '<i>'.$checksec.'</i>').' ';
                   8575:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   8576:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   8577:                         }
                   8578:                         $gradesections .= '</p>';
                   8579:                     }
                   8580:                 }
                   8581:             } else {
                   8582:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   8583:             }
                   8584:         }
1.663     raeburn  8585:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 8586: 	$r->print('
1.770     raeburn  8587: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 8588: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 8589: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 8590: ');
1.237     albertel 8591:     }
1.614     www      8592:     $r->print("</form><br />");
1.203     albertel 8593:     return '';
                   8594: }
                   8595: 
1.423     albertel 8596: =pod
                   8597: 
                   8598: =item scantron_form_start
                   8599: 
1.424     albertel 8600:     html hidden input for remembering all selected grading options
                   8601: 
1.423     albertel 8602: =cut
                   8603: 
1.203     albertel 8604: sub scantron_form_start {
                   8605:     my ($max_bubble)=@_;
                   8606:     my $result= <<SCANTRONFORM;
                   8607: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 8608:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   8609:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   8610:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 8611:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 8612:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   8613:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   8614:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   8615:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 8616:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 8617: SCANTRONFORM
1.447     foxr     8618: 
                   8619:   my $line = 0;
                   8620:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   8621:        my $chunk =
                   8622: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     8623:        $chunk .=
                   8624: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  8625:        $chunk .= 
                   8626:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  8627:        $chunk .=
                   8628:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  8629:        $chunk .=
                   8630:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     8631:        $result .= $chunk;
                   8632:        $line++;
1.691     raeburn  8633:     }
1.203     albertel 8634:     return $result;
                   8635: }
                   8636: 
1.423     albertel 8637: =pod
                   8638: 
                   8639: =item scantron_validate_file
                   8640: 
1.659     raeburn  8641:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 8642: 
                   8643:     Also processes any necessary information resets that need to
                   8644:     occur before validation begins (ignore previous corrections,
                   8645:     restarting the skipped records processing)
                   8646: 
1.423     albertel 8647: =cut
                   8648: 
1.157     albertel 8649: sub scantron_validate_file {
1.608     www      8650:     my ($r,$symb) = @_;
1.157     albertel 8651:     if (!$symb) {return '';}
1.324     albertel 8652:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 8653:     
1.703     bisitz   8654:     # do the detection of only doing skipped records first before we delete
1.424     albertel 8655:     # them when doing the corrections reset
1.257     albertel 8656:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 8657: 	&reset_skipping_status();
                   8658:     }
1.257     albertel 8659:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 8660: 	&remember_current_skipped();
1.257     albertel 8661: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 8662:     }
                   8663: 
1.257     albertel 8664:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 8665: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   8666: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   8667: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 8668: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 8669:     }
1.200     albertel 8670: 
1.257     albertel 8671:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 8672: 	&scantron_process_corrections($r);
                   8673:     }
1.770     raeburn  8674: 
                   8675:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   8676:     my ($checksec,@gradable);
                   8677:     if ($env{'request.course.sec'}) {
                   8678:         ($checksec,my @possibles) = &gradable_sections();
                   8679:         if ($checksec) {
                   8680:             if (@possibles) {
                   8681:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   8682:                 if (@chosensecs) {
                   8683:                     foreach my $sec (@chosensecs) {
                   8684:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   8685:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   8686:                                 push(@gradable,$sec);
                   8687:                             }
                   8688:                         }
                   8689:                     }
                   8690:                 }
                   8691:             }
                   8692:             $r->print('<p><table>');
                   8693:             if (@gradable) {
                   8694:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   8695:                 $r->print(
                   8696:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   8697:             } else {
                   8698:                 $r->print(
                   8699:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   8700:             }
                   8701:             $r->print('</table></p>');
                   8702:         }
                   8703:     }
                   8704:     $r->rflush();
                   8705: 
1.157     albertel 8706:     #get the student pick code ready
                   8707:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  8708:     my $nav_error;
1.754     raeburn  8709:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8710:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8711:     if ($nav_error) {
                   8712:         $r->print(&navmap_errormsg());
                   8713:         return '';
                   8714:     }
1.203     albertel 8715:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  8716:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8717:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   8718:     }
1.157     albertel 8719:     $r->print($result);
                   8720:     
1.334     albertel 8721:     my @validate_phases=( 'sequence',
                   8722: 			  'ID',
1.157     albertel 8723: 			  'CODE',
                   8724: 			  'doublebubble',
                   8725: 			  'missingbubbles');
1.257     albertel 8726:     if (!$env{'form.validatepass'}) {
                   8727: 	$env{'form.validatepass'} = 0;
1.157     albertel 8728:     }
1.257     albertel 8729:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  8730:     my %skipbysec=();
1.448     foxr     8731: 
1.157     albertel 8732:     my $stop=0;
                   8733:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  8734: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 8735: 	$r->rflush();
1.691     raeburn  8736:      
1.157     albertel 8737: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   8738: 	{
                   8739: 	    no strict 'refs';
1.770     raeburn  8740:             my @extras=();
                   8741:             if ($validate_phases[$currentphase] eq 'ID') {
                   8742:                 @extras = (\%skipbysec,$checksec,@gradable);
                   8743:             }
                   8744: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 8745: 	}
                   8746:     }
                   8747:     if (!$stop) {
1.650     raeburn  8748: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  8749:         my $secinfo;
                   8750:         if (keys(%skipbysec) > 0) {
                   8751:             my $seclist = '<ul>';
                   8752:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   8753:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   8754:             }
                   8755:             $seclist .= '</ul>';
                   8756:             $secinfo = '<p class="LC_info">'.
                   8757:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   8758:                            $seclist).
                   8759:                        '</p>';
                   8760:         }
1.542     raeburn  8761: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  8762:                   $secinfo.$warning.
1.542     raeburn  8763:                   &mt('Perform verification for each student after storage of submissions?').
                   8764:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   8765:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   8766:                   ('&nbsp;'x3).'<label>'.
                   8767:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   8768:                   '</label></span><br />'.
                   8769:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  8770:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  8771:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   8772:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 8773:     } else {
                   8774: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   8775: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   8776:     }
                   8777:     if ($stop) {
1.334     albertel 8778: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  8779: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 8780: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 8781: 
1.650     raeburn  8782: 	    $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 8783: 	} else {
1.503     raeburn  8784:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  8785: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  8786:             } else {
1.539     riegler  8787:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  8788:             }
1.492     albertel 8789: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   8790: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   8791: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 8792: 	}
1.157     albertel 8793:     }
1.614     www      8794:     $r->print(" </form><br />");
1.157     albertel 8795:     return '';
                   8796: }
                   8797: 
1.423     albertel 8798: 
                   8799: =pod
                   8800: 
                   8801: =item scantron_remove_file
                   8802: 
1.659     raeburn  8803:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 8804:    scantron_original_<filename> is never removed
                   8805: 
                   8806: 
1.423     albertel 8807: =cut
                   8808: 
1.200     albertel 8809: sub scantron_remove_file {
1.192     albertel 8810:     my ($which)=@_;
1.257     albertel 8811:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8812:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8813:     my $file='scantron_';
1.200     albertel 8814:     if ($which eq 'corrected' || $which eq 'skipped') {
                   8815: 	$file.=$which.'_';
1.192     albertel 8816:     } else {
                   8817: 	return 'refused';
                   8818:     }
1.257     albertel 8819:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 8820:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   8821: }
                   8822: 
1.423     albertel 8823: 
                   8824: =pod
                   8825: 
                   8826: =item scantron_remove_scan_data
                   8827: 
1.659     raeburn  8828:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 8829:    data file.  (In the case that both the are doing skipped records we need
                   8830:    to remember the old skipped lines for the time being so that element
                   8831:    persists for a while.)
                   8832: 
1.423     albertel 8833: =cut
                   8834: 
1.200     albertel 8835: sub scantron_remove_scan_data {
1.257     albertel 8836:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8837:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8838:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   8839:     my @todelete;
1.257     albertel 8840:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 8841:     foreach my $key (@keys) {
                   8842: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 8843: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 8844: 		$key=~/remember_skipping/) {
                   8845: 		next;
                   8846: 	    }
1.192     albertel 8847: 	    push(@todelete,$key);
                   8848: 	}
                   8849:     }
1.200     albertel 8850:     my $result;
1.192     albertel 8851:     if (@todelete) {
1.491     albertel 8852: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   8853: 				       \@todelete,$cdom,$cname);
                   8854:     } else {
                   8855: 	$result = 'ok';
1.192     albertel 8856:     }
                   8857:     return $result;
                   8858: }
                   8859: 
1.423     albertel 8860: 
                   8861: =pod
                   8862: 
                   8863: =item scantron_getfile
                   8864: 
1.659     raeburn  8865:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 8866:     the scan_data hash
                   8867:   
                   8868:   Arguments:
                   8869:     None
                   8870: 
                   8871:   Returns:
                   8872:     2 hash references
                   8873: 
                   8874:      - first one has 
                   8875:          orig      -
                   8876:          corrected -
                   8877:          skipped   -  each of which points to an array ref of the specified
                   8878:                       file broken up into individual lines
                   8879:          count     - number of scanlines
                   8880:  
                   8881:      - second is the scan_data hash possible keys are
1.425     albertel 8882:        ($number refers to scanline numbered $number and thus the key affects
                   8883:         only that scanline
                   8884:         $bubline refers to the specific bubble line element and the aspects
                   8885:         refers to that specific bubble line element)
                   8886: 
                   8887:        $number.user - username:domain to use
                   8888:        $number.CODE_ignore_dup 
                   8889:                     - ignore the duplicate CODE error 
                   8890:        $number.useCODE
                   8891:                     - use the CODE in the scanline as is
                   8892:        $number.no_bubble.$bubline
                   8893:                     - it is valid that there is no bubbled in bubble
                   8894:                       at $number $bubline
                   8895:        remember_skipping
                   8896:                     - a frozen hash containing keys of $number and values
                   8897:                       of either 
                   8898:                         1 - we are on a 'do skipped records pass' and plan
                   8899:                             on processing this line
                   8900:                         2 - we are on a 'do skipped records pass' and this
                   8901:                             scanline has been marked to skip yet again
1.424     albertel 8902: 
1.423     albertel 8903: =cut
                   8904: 
1.157     albertel 8905: sub scantron_getfile {
1.200     albertel 8906:     #FIXME really would prefer a scantron directory
1.257     albertel 8907:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8908:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 8909:     my $lines;
                   8910:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8911: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 8912:     my %scanlines;
                   8913:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   8914:     my $temp=$scanlines{'orig'};
                   8915:     $scanlines{'count'}=$#$temp;
                   8916: 
                   8917:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8918: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 8919:     if ($lines eq '-1') {
                   8920: 	$scanlines{'corrected'}=[];
                   8921:     } else {
                   8922: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   8923:     }
                   8924:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8925: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 8926:     if ($lines eq '-1') {
                   8927: 	$scanlines{'skipped'}=[];
                   8928:     } else {
                   8929: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   8930:     }
1.175     albertel 8931:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 8932:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   8933:     my %scan_data = @tmp;
                   8934:     return (\%scanlines,\%scan_data);
                   8935: }
                   8936: 
1.423     albertel 8937: =pod
                   8938: 
                   8939: =item lonnet_putfile
                   8940: 
1.424     albertel 8941:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   8942: 
                   8943:  Arguments:
                   8944:    $contents - data to store
                   8945:    $filename - filename to store $contents into
                   8946: 
                   8947:  Returns:
                   8948:    result value from &Apache::lonnet::finishuserfileupload
                   8949: 
1.423     albertel 8950: =cut
                   8951: 
1.157     albertel 8952: sub lonnet_putfile {
                   8953:     my ($contents,$filename)=@_;
1.257     albertel 8954:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8955:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8956:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 8957:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 8958: 
                   8959: }
                   8960: 
1.423     albertel 8961: =pod
                   8962: 
                   8963: =item scantron_putfile
                   8964: 
1.659     raeburn  8965:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 8966:     scan_data hash. (Does not modify the original version only the
                   8967:     corrected and skipped versions.
                   8968: 
                   8969:  Arguments:
                   8970:     $scanlines - hash ref that looks like the first return value from
                   8971:                  &scantron_getfile()
                   8972:     $scan_data - hash ref that looks like the second return value from
                   8973:                  &scantron_getfile()
                   8974: 
1.423     albertel 8975: =cut
                   8976: 
1.157     albertel 8977: sub scantron_putfile {
                   8978:     my ($scanlines,$scan_data) = @_;
1.200     albertel 8979:     #FIXME really would prefer a scantron directory
1.257     albertel 8980:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8981:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 8982:     if ($scanlines) {
                   8983: 	my $prefix='scantron_';
1.157     albertel 8984: # no need to update orig, shouldn't change
                   8985: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 8986: #		    $env{'form.scantron_selectfile'});
1.200     albertel 8987: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   8988: 			$prefix.'corrected_'.
1.257     albertel 8989: 			$env{'form.scantron_selectfile'});
1.200     albertel 8990: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   8991: 			$prefix.'skipped_'.
1.257     albertel 8992: 			$env{'form.scantron_selectfile'});
1.200     albertel 8993:     }
1.175     albertel 8994:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 8995: }
                   8996: 
1.423     albertel 8997: =pod
                   8998: 
                   8999: =item scantron_get_line
                   9000: 
1.424     albertel 9001:    Returns the correct version of the scanline
                   9002: 
                   9003:  Arguments:
                   9004:     $scanlines - hash ref that looks like the first return value from
                   9005:                  &scantron_getfile()
                   9006:     $scan_data - hash ref that looks like the second return value from
                   9007:                  &scantron_getfile()
                   9008:     $i         - number of the requested line (starts at 0)
                   9009: 
                   9010:  Returns:
                   9011:    A scanline, (either the original or the corrected one if it
                   9012:    exists), or undef if the requested scanline should be
                   9013:    skipped. (Either because it's an skipped scanline, or it's an
                   9014:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   9015:    pass.
                   9016: 
1.423     albertel 9017: =cut
                   9018: 
1.157     albertel 9019: sub scantron_get_line {
1.200     albertel 9020:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 9021:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   9022:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 9023:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   9024:     return $scanlines->{'orig'}[$i]; 
                   9025: }
                   9026: 
1.423     albertel 9027: =pod
                   9028: 
                   9029: =item scantron_todo_count
                   9030: 
1.424     albertel 9031:     Counts the number of scanlines that need processing.
                   9032: 
                   9033:  Arguments:
                   9034:     $scanlines - hash ref that looks like the first return value from
                   9035:                  &scantron_getfile()
                   9036:     $scan_data - hash ref that looks like the second return value from
                   9037:                  &scantron_getfile()
                   9038: 
                   9039:  Returns:
                   9040:     $count - number of scanlines to process
                   9041: 
1.423     albertel 9042: =cut
                   9043: 
1.200     albertel 9044: sub get_todo_count {
                   9045:     my ($scanlines,$scan_data)=@_;
                   9046:     my $count=0;
                   9047:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   9048: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   9049: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9050: 	$count++;
                   9051:     }
                   9052:     return $count;
                   9053: }
                   9054: 
1.423     albertel 9055: =pod
                   9056: 
                   9057: =item scantron_put_line
                   9058: 
1.659     raeburn  9059:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 9060:     data file.
                   9061: 
                   9062:  Arguments:
                   9063:     $scanlines - hash ref that looks like the first return value from
                   9064:                  &scantron_getfile()
                   9065:     $scan_data - hash ref that looks like the second return value from
                   9066:                  &scantron_getfile()
                   9067:     $i         - line number to update
                   9068:     $newline   - contents of the updated scanline
                   9069:     $skip      - if true make the line for skipping and update the
                   9070:                  'skipped' file
                   9071: 
1.423     albertel 9072: =cut
                   9073: 
1.157     albertel 9074: sub scantron_put_line {
1.200     albertel 9075:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 9076:     if ($skip) {
                   9077: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 9078: 	&start_skipping($scan_data,$i);
1.157     albertel 9079: 	return;
                   9080:     }
                   9081:     $scanlines->{'corrected'}[$i]=$newline;
                   9082: }
                   9083: 
1.423     albertel 9084: =pod
                   9085: 
                   9086: =item scantron_clear_skip
                   9087: 
1.424     albertel 9088:    Remove a line from the 'skipped' file
                   9089: 
                   9090:  Arguments:
                   9091:     $scanlines - hash ref that looks like the first return value from
                   9092:                  &scantron_getfile()
                   9093:     $scan_data - hash ref that looks like the second return value from
                   9094:                  &scantron_getfile()
                   9095:     $i         - line number to update
                   9096: 
1.423     albertel 9097: =cut
                   9098: 
1.376     albertel 9099: sub scantron_clear_skip {
                   9100:     my ($scanlines,$scan_data,$i)=@_;
                   9101:     if (exists($scanlines->{'skipped'}[$i])) {
                   9102: 	undef($scanlines->{'skipped'}[$i]);
                   9103: 	return 1;
                   9104:     }
                   9105:     return 0;
                   9106: }
                   9107: 
1.423     albertel 9108: =pod
                   9109: 
                   9110: =item scantron_filter_not_exam
                   9111: 
1.424     albertel 9112:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   9113:    filter out resources that are not marked as 'exam' mode
                   9114: 
1.423     albertel 9115: =cut
                   9116: 
1.334     albertel 9117: sub scantron_filter_not_exam {
                   9118:     my ($curres)=@_;
                   9119:     
                   9120:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   9121: 	# if the user has asked to not have either hidden
                   9122: 	# or 'randomout' controlled resources to be graded
                   9123: 	# don't include them
                   9124: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   9125: 	    && $curres->randomout) {
                   9126: 	    return 0;
                   9127: 	}
                   9128: 	return 1;
                   9129:     }
                   9130:     return 0;
                   9131: }
                   9132: 
1.423     albertel 9133: =pod
                   9134: 
                   9135: =item scantron_validate_sequence
                   9136: 
1.424     albertel 9137:     Validates the selected sequence, checking for resource that are
                   9138:     not set to exam mode.
                   9139: 
1.423     albertel 9140: =cut
                   9141: 
1.334     albertel 9142: sub scantron_validate_sequence {
                   9143:     my ($r,$currentphase) = @_;
                   9144: 
                   9145:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9146:     unless (ref($navmap)) {
                   9147:         $r->print(&navmap_errormsg());
                   9148:         return (1,$currentphase);
                   9149:     }
1.334     albertel 9150:     my (undef,undef,$sequence)=
                   9151: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9152: 
                   9153:     my $map=$navmap->getResourceByUrl($sequence);
                   9154: 
                   9155:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   9156:                                     value="ignore" />');
                   9157:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   9158: 	my @resources=
                   9159: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   9160: 	if (@resources) {
1.675     bisitz   9161: 	    $r->print(
                   9162:                 '<p class="LC_warning">'
                   9163:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   9164:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   9165:                    .' work correctly.')
                   9166:                .'</p>'
                   9167:             );
1.334     albertel 9168: 	    return (1,$currentphase);
                   9169: 	}
                   9170:     }
                   9171: 
                   9172:     return (0,$currentphase+1);
                   9173: }
                   9174: 
1.423     albertel 9175: 
                   9176: 
1.157     albertel 9177: sub scantron_validate_ID {
1.770     raeburn  9178:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 9179:     
                   9180:     #get student info
                   9181:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9182:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  9183:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 9184: 
                   9185:     #get scantron line setup
1.754     raeburn  9186:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9187:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  9188: 
                   9189:     my $nav_error;
1.649     raeburn  9190:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  9191:     if ($nav_error) {
                   9192:         $r->print(&navmap_errormsg());
                   9193:         return(1,$currentphase);
                   9194:     }
1.157     albertel 9195: 
                   9196:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  9197:     my $unsavedskips = 0;
1.157     albertel 9198:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9199: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9200: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9201: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9202: 						 $scan_data);
                   9203: 	my $id=$$scan_record{'scantron.ID'};
                   9204: 	my $found;
                   9205: 	foreach my $checkid (keys(%idmap)) {
                   9206: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   9207: 	}
                   9208: 	if ($found) {
                   9209: 	    my $username=$idmap{$found};
1.770     raeburn  9210:             if ($checksec) {
                   9211:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   9212:                     my $stusec = $classlist->{$username}->[$secidx];
                   9213:                     if ($stusec ne $checksec) {
                   9214:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9215:                             my $skip=1;
                   9216:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9217:                             if (ref($skipbysec) eq 'HASH') {
                   9218:                                 if ($stusec eq '') {
                   9219:                                     $skipbysec->{'none'} ++;
                   9220:                                 } else {
                   9221:                                     $skipbysec->{$stusec} ++;
                   9222:                                 }
                   9223:                             }
                   9224:                             $unsavedskips ++;
                   9225:                             next;
                   9226:                         }
                   9227:                     }
                   9228:                 }
                   9229:             }
1.157     albertel 9230: 	    if ($found{'ids'}{$found}) {
                   9231: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9232: 					 $line,'duplicateID',$found);
1.770     raeburn  9233:                 if ($unsavedskips) {
                   9234:                     &scantron_putfile($scanlines,$scan_data);
                   9235:                     $unsavedskips = 0;
                   9236:                 }
1.194     albertel 9237: 		return(1,$currentphase);
1.157     albertel 9238: 	    } elsif ($found{'usernames'}{$username}) {
                   9239: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9240: 					 $line,'duplicateID',$username);
1.770     raeburn  9241:                 if ($unsavedskips) {
                   9242:                     &scantron_putfile($scanlines,$scan_data);
                   9243:                     $unsavedskips = 0;
                   9244:                 }
1.194     albertel 9245: 		return(1,$currentphase);
1.157     albertel 9246: 	    }
1.186     albertel 9247: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 9248: 	    $found{'ids'}{$found}++;
                   9249: 	    $found{'usernames'}{$username}++;
                   9250: 	} else {
                   9251: 	    if ($id =~ /^\s*$/) {
1.158     albertel 9252: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  9253:                 if (($checksec && $username ne '')) {
                   9254:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   9255:                         my $stusec = $classlist->{$username}->[$secidx];
                   9256:                         if ($stusec ne $checksec) {
                   9257:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9258:                                 my $skip=1;
                   9259:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9260:                                 if (ref($skipbysec) eq 'HASH') {
                   9261:                                     if ($stusec eq '') {
                   9262:                                         $skipbysec->{'none'} ++;
                   9263:                                     } else {
                   9264:                                         $skipbysec->{$stusec} ++;
                   9265:                                     }
                   9266:                                 }
                   9267:                                 $unsavedskips ++;
                   9268:                                 next;
                   9269:                             }
                   9270:                         }
                   9271:                     }
                   9272: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 9273: 		    &scantron_get_correction($r,$i,$scan_record,
                   9274: 					     \%scantron_config,
                   9275: 					     $line,'duplicateID',$username);
1.770     raeburn  9276:                     if ($unsavedskips) {
                   9277:                         &scantron_putfile($scanlines,$scan_data);
                   9278:                         $unsavedskips = 0;
                   9279:                     }
1.194     albertel 9280: 		    return(1,$currentphase);
1.157     albertel 9281: 		} elsif (!defined($username)) {
                   9282: 		    &scantron_get_correction($r,$i,$scan_record,
                   9283: 					     \%scantron_config,
                   9284: 					     $line,'incorrectID');
1.770     raeburn  9285:                     if ($unsavedskips) {
                   9286:                         &scantron_putfile($scanlines,$scan_data);
                   9287:                         $unsavedskips = 0;
                   9288:                     }
1.194     albertel 9289: 		    return(1,$currentphase);
1.157     albertel 9290: 		}
                   9291: 		$found{'usernames'}{$username}++;
                   9292: 	    } else {
                   9293: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9294: 					 $line,'incorrectID');
1.770     raeburn  9295:                 if ($unsavedskips) {
                   9296:                     &scantron_putfile($scanlines,$scan_data);
                   9297:                     $unsavedskips = 0;
                   9298:                 }
1.194     albertel 9299: 		return(1,$currentphase);
1.157     albertel 9300: 	    }
                   9301: 	}
                   9302:     }
1.770     raeburn  9303:     if ($unsavedskips) {
                   9304:         &scantron_putfile($scanlines,$scan_data);
                   9305:         $unsavedskips = 0;
                   9306:     }
1.157     albertel 9307:     return (0,$currentphase+1);
                   9308: }
                   9309: 
1.770     raeburn  9310: sub scantron_get_sections {
                   9311:     my %bysec;
                   9312:     if ($env{'form.scantron_format'} ne '') {
                   9313:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   9314:         my ($scanlines,$scan_data)=&scantron_getfile();
                   9315:         my $classlist=&Apache::loncoursedata::get_classlist();
                   9316:         my %idmap=&username_to_idmap($classlist);
                   9317:         foreach my $key (keys(%idmap)) {
                   9318:             my $lckey = lc($key);
                   9319:             $idmap{$lckey} = $idmap{$key};
                   9320:         }
                   9321:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   9322:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   9323:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   9324:             if ($line=~/^[\s\cz]*$/) { next; }
                   9325:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9326:                                                      $scan_data);
                   9327:             my $id=lc($$scan_record{'scantron.ID'});
                   9328:             if (exists($idmap{$id})) {
                   9329:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9330:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9331:                     if ($stusec eq '') {
                   9332:                         $bysec{'none'} ++;
                   9333:                     } else {
                   9334:                         $bysec{$stusec} ++;
                   9335:                     }
                   9336:                 }
                   9337:             }
                   9338:         }
                   9339:     }
                   9340:     return %bysec;
                   9341: }
1.423     albertel 9342: 
1.157     albertel 9343: sub scantron_get_correction {
1.691     raeburn  9344:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   9345:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 9346: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 9347: #to show both the current line and the previous one and allow skipping
                   9348: #the previous one or the current one
                   9349: 
1.333     albertel 9350:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   9351:         $r->print(
                   9352:             '<p class="LC_warning">'
                   9353:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   9354:                 "<b>$error</b>",
                   9355:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   9356:            ."</p> \n");
1.157     albertel 9357:     } else {
1.658     bisitz   9358:         $r->print(
                   9359:             '<p class="LC_warning">'
                   9360:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   9361:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   9362:            ."</p> \n");
                   9363:     }
                   9364:     my $message =
                   9365:         '<p>'
                   9366:        .&mt('The ID on the form is [_1]',
                   9367:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   9368:        .'<br />'
1.665     raeburn  9369:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   9370:             $$scan_record{'scantron.LastName'},
                   9371:             $$scan_record{'scantron.FirstName'})
                   9372:        .'</p>';
1.242     albertel 9373: 
1.157     albertel 9374:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   9375:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  9376:                            # Array populated for doublebubble or
                   9377:     my @lines_to_correct;  # missingbubble errors to build javascript
                   9378:                            # to validate radio button checking   
                   9379: 
1.157     albertel 9380:     if ($error =~ /ID$/) {
1.186     albertel 9381: 	if ($error eq 'incorrectID') {
1.658     bisitz   9382:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 9383: 		      "</p>\n");
1.157     albertel 9384: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   9385:             $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 9386: 	}
1.242     albertel 9387: 	$r->print($message);
1.492     albertel 9388: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 9389: 	$r->print("\n<ul><li> ");
                   9390: 	#FIXME it would be nice if this sent back the user ID and
                   9391: 	#could do partial userID matches
                   9392: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   9393: 				       'scantron_username','scantron_domain'));
                   9394: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   9395: 	$r->print("\n:\n".
1.257     albertel 9396: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 9397: 
                   9398: 	$r->print('</li>');
1.186     albertel 9399:     } elsif ($error =~ /CODE$/) {
                   9400: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   9401: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 9402: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   9403: 	    $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 9404: 	}
1.658     bisitz   9405: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   9406: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   9407:                  ."</p>\n");
1.242     albertel 9408: 	$r->print($message);
1.658     bisitz   9409: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 9410: 	$r->print("\n<br /> ");
1.194     albertel 9411: 	my $i=0;
1.273     albertel 9412: 	if ($error eq 'incorrectCODE' 
                   9413: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 9414: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 9415: 	    if ($closest > 0) {
                   9416: 		foreach my $testcode (@{$closest}) {
                   9417: 		    my $checked='';
1.569     bisitz   9418: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9419: 		    $r->print("
                   9420:    <label>
1.569     bisitz   9421:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 9422:        ".&mt("Use the similar CODE [_1] instead.",
                   9423: 	    "<b><tt>".$testcode."</tt></b>")."
                   9424:     </label>
                   9425:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 9426: 		    $r->print("\n<br />");
                   9427: 		    $i++;
                   9428: 		}
1.194     albertel 9429: 	    }
                   9430: 	}
1.273     albertel 9431: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   9432: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9433: 	    $r->print("
                   9434:     <label>
1.569     bisitz   9435:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  9436:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 9437: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   9438:     </label>");
1.273     albertel 9439: 	    $r->print("\n<br />");
                   9440: 	}
1.194     albertel 9441: 
1.597     wenzelju 9442: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 9443: function change_radio(field) {
1.190     albertel 9444:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 9445:     var i;
                   9446:     for (i=0;i<slct.length;i++) {
                   9447:         if (slct[i].value==field) { slct[i].checked=true; }
                   9448:     }
                   9449: }
                   9450: ENDSCRIPT
1.187     albertel 9451: 	my $href="/adm/pickcode?".
1.359     www      9452: 	   "form=".&escape("scantronupload").
                   9453: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   9454: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   9455: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   9456: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 9457: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 9458: 	    $r->print("
                   9459:     <label>
                   9460:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   9461:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   9462: 	     "<a target='_blank' href='$href'>","</a>")."
                   9463:     </label> 
1.558     bisitz   9464:     ".&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 9465: 	    $r->print("\n<br />");
                   9466: 	}
1.492     albertel 9467: 	$r->print("
                   9468:     <label>
                   9469:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   9470:        ".&mt("Use [_1] as the CODE.",
                   9471: 	     "</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 9472: 	$r->print("\n<br /><br />");
1.157     albertel 9473:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   9474: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     9475: 
                   9476: 	# The form field scantron_questions is acutally a list of line numbers.
                   9477: 	# represented by this form so:
                   9478: 
1.691     raeburn  9479: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9480:                                                 $respnumlookup,$startline);
1.497     foxr     9481: 
1.157     albertel 9482: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9483: 		  $line_list.'" />');
1.242     albertel 9484: 	$r->print($message);
1.492     albertel 9485: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 9486: 	foreach my $question (@{$arg}) {
1.503     raeburn  9487: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9488:                                                    $scan_record, $error,
                   9489:                                                    $randomorder,$randompick,
                   9490:                                                    $respnumlookup,$startline);
1.524     raeburn  9491:             push(@lines_to_correct,@linenums);
1.157     albertel 9492: 	}
1.503     raeburn  9493:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9494:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   9495: 	$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 9496: 	$r->print($message);
1.492     albertel 9497: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  9498: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     9499: 
1.503     raeburn  9500: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     9501: 	# a list of question numbers. Therefore:
                   9502: 	#
1.691     raeburn  9503: 
                   9504: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9505:                                                 $respnumlookup,$startline);
1.497     foxr     9506: 
1.157     albertel 9507: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9508: 		  $line_list.'" />');
1.157     albertel 9509: 	foreach my $question (@{$arg}) {
1.503     raeburn  9510: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9511:                                                    $scan_record, $error,
                   9512:                                                    $randomorder,$randompick,
                   9513:                                                    $respnumlookup,$startline);
1.524     raeburn  9514:             push(@lines_to_correct,@linenums);
1.157     albertel 9515: 	}
1.503     raeburn  9516:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9517:     } else {
                   9518: 	$r->print("\n<ul>");
                   9519:     }
                   9520:     $r->print("\n</li></ul>");
1.497     foxr     9521: }
                   9522: 
1.503     raeburn  9523: sub verify_bubbles_checked {
                   9524:     my (@ansnums) = @_;
                   9525:     my $ansnumstr = join('","',@ansnums);
                   9526:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  9527:     &js_escape(\$warning);
1.767     raeburn  9528:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  9529: function verify_bubble_radio(form) {
                   9530:     var ansnumArray = new Array ("$ansnumstr");
                   9531:     var need_bubble_count = 0;
                   9532:     for (var i=0; i<ansnumArray.length; i++) {
                   9533:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   9534:             var bubble_picked = 0; 
                   9535:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   9536:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   9537:                     bubble_picked = 1;
                   9538:                 }
                   9539:             }
                   9540:             if (bubble_picked == 0) {
                   9541:                 need_bubble_count ++;
                   9542:             }
                   9543:         }
                   9544:     }
                   9545:     if (need_bubble_count) {
                   9546:         alert("$warning");
                   9547:         return;
                   9548:     }
                   9549:     form.submit(); 
                   9550: }
                   9551: ENDSCRIPT
                   9552:     return $output;
                   9553: }
                   9554: 
1.497     foxr     9555: =pod
                   9556: 
                   9557: =item  questions_to_line_list
1.157     albertel 9558: 
1.497     foxr     9559: Converts a list of questions into a string of comma separated
                   9560: line numbers in the answer sheet used by the questions.  This is
                   9561: used to fill in the scantron_questions form field.
                   9562: 
                   9563:   Arguments:
                   9564:      questions    - Reference to an array of questions.
1.691     raeburn  9565:      randomorder  - True if randomorder in use.
                   9566:      randompick   - True if randompick in use.
                   9567:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9568:                      for current line to question number used for same question
                   9569:                      in "Master Seqence" (as seen by Course Coordinator).
                   9570:      startline    - Reference to hash where key is question number (0 is first)
                   9571:                     and key is number of first bubble line for current student
                   9572:                     or code-based randompick and/or randomorder.
1.693     raeburn  9573: 
1.497     foxr     9574: =cut
                   9575: 
                   9576: 
                   9577: sub questions_to_line_list {
1.691     raeburn  9578:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     9579:     my @lines;
                   9580: 
1.503     raeburn  9581:     foreach my $item (@{$questions}) {
                   9582:         my $question = $item;
                   9583:         my ($first,$count,$last);
                   9584:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   9585:             $question = $1;
                   9586:             my $subquestion = $2;
1.691     raeburn  9587:             my $responsenum = $question-1;
                   9588:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9589:                 $responsenum = $respnumlookup->{$question-1};
                   9590:                 if (ref($startline) eq 'HASH') {
                   9591:                     $first = $startline->{$question-1} + 1;
                   9592:                 }
                   9593:             } else {
                   9594:                 $first = $first_bubble_line{$responsenum} + 1;
                   9595:             }
                   9596:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9597:             my $subcount = 1;
                   9598:             while ($subcount<$subquestion) {
                   9599:                 $first += $subans[$subcount-1];
                   9600:                 $subcount ++;
                   9601:             }
                   9602:             $count = $subans[$subquestion-1];
                   9603:         } else {
1.691     raeburn  9604:             my $responsenum = $question-1;
                   9605:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9606:                 $responsenum = $respnumlookup->{$question-1};
                   9607:                 if (ref($startline) eq 'HASH') {
                   9608:                     $first = $startline->{$question-1} + 1;
                   9609:                 }
                   9610:             } else {
                   9611:                 $first = $first_bubble_line{$responsenum} + 1;
                   9612:             }
                   9613: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9614:         }
1.506     raeburn  9615:         $last = $first+$count-1;
1.503     raeburn  9616:         push(@lines, ($first..$last));
1.497     foxr     9617:     }
                   9618:     return join(',', @lines);
                   9619: }
                   9620: 
                   9621: =pod 
                   9622: 
                   9623: =item prompt_for_corrections
                   9624: 
                   9625: Prompts for a potentially multiline correction to the
                   9626: user's bubbling (factors out common code from scantron_get_correction
                   9627: for multi and missing bubble cases).
                   9628: 
                   9629:  Arguments:
                   9630:    $r           - Apache request object.
                   9631:    $question    - The question number to prompt for.
                   9632:    $scan_config - The scantron file configuration hash.
                   9633:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  9634:    $error       - Type of error
1.691     raeburn  9635:    $randomorder - True if randomorder in use.
                   9636:    $randompick  - True if randompick in use.
                   9637:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9638:                     for current line to question number used for same question
                   9639:                     in "Master Seqence" (as seen by Course Coordinator).
                   9640:    $startline   - Reference to hash where key is question number (0 is first)
                   9641:                   and value is number of first bubble line for current student
                   9642:                   or code-based randompick and/or randomorder.
                   9643: 
1.497     foxr     9644: 
                   9645:  Implicit inputs:
                   9646:    %bubble_lines_per_response   - Starting line numbers for each question.
                   9647:                                   Numbered from 0 (but question numbers are from
                   9648:                                   1.
                   9649:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  9650:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   9651:                                   type problems render as separate sub-questions, 
1.503     raeburn  9652:                                   in exam mode. This hash contains a 
                   9653:                                   comma-separated list of the lines per 
                   9654:                                   sub-question.
1.510     raeburn  9655:    %responsetype_per_response   - essayresponse, formularesponse,
                   9656:                                   stringresponse, imageresponse, reactionresponse,
                   9657:                                   and organicresponse type problem parts can have
1.503     raeburn  9658:                                   multiple lines per response if the weight
                   9659:                                   assigned exceeds 10.  In this case, only
                   9660:                                   one bubble per line is permitted, but more 
                   9661:                                   than one line might contain bubbles, e.g.
                   9662:                                   bubbling of: line 1 - J, line 2 - J, 
                   9663:                                   line 3 - B would assign 22 points.  
1.497     foxr     9664: 
                   9665: =cut
                   9666: 
                   9667: sub prompt_for_corrections {
1.691     raeburn  9668:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   9669:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  9670:     my ($current_line,$lines);
                   9671:     my @linenums;
                   9672:     my $questionnum = $question;
1.691     raeburn  9673:     my ($first,$responsenum);
1.503     raeburn  9674:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   9675:         $question = $1;
                   9676:         my $subquestion = $2;
1.691     raeburn  9677:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9678:             $responsenum = $respnumlookup->{$question-1};
                   9679:             if (ref($startline) eq 'HASH') {
                   9680:                 $first = $startline->{$question-1};
                   9681:             }
                   9682:         } else {
                   9683:             $responsenum = $question-1;
1.714     raeburn  9684:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  9685:         }
                   9686:         $current_line = $first + 1 ;
                   9687:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9688:         my $subcount = 1;
                   9689:         while ($subcount<$subquestion) {
                   9690:             $current_line += $subans[$subcount-1];
                   9691:             $subcount ++;
                   9692:         }
                   9693:         $lines = $subans[$subquestion-1];
                   9694:     } else {
1.691     raeburn  9695:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9696:             $responsenum = $respnumlookup->{$question-1};
                   9697:             if (ref($startline) eq 'HASH') { 
                   9698:                 $first = $startline->{$question-1};
                   9699:             }
                   9700:         } else {
                   9701:             $responsenum = $question-1;
                   9702:             $first = $first_bubble_line{$responsenum};
                   9703:         }
                   9704:         $current_line = $first + 1;
                   9705:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9706:     }
1.497     foxr     9707:     if ($lines > 1) {
1.503     raeburn  9708:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  9709:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   9710:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   9711:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   9712:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   9713:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   9714:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   9715:             $r->print(
                   9716:                 &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)
                   9717:                .'<br /><br />'
                   9718:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   9719:                .'<br />'
                   9720:                .&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.')
                   9721:                .'<br />'
                   9722:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   9723:                .'<br /><br />'
                   9724:             );
1.503     raeburn  9725:         } else {
                   9726:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   9727:         }
1.497     foxr     9728:     }
                   9729:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  9730:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  9731: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  9732: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  9733:         push(@linenums,$current_line);
1.497     foxr     9734: 	$current_line++;
                   9735:     }
                   9736:     if ($lines > 1) {
                   9737: 	$r->print("<hr /><br />");
                   9738:     }
1.503     raeburn  9739:     return @linenums;
1.157     albertel 9740: }
1.423     albertel 9741: 
                   9742: =pod
                   9743: 
                   9744: =item scantron_bubble_selector
                   9745:   
                   9746:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 9747:    possibly showing the existing the selected bubbles if known
1.423     albertel 9748: 
                   9749:  Arguments:
                   9750:     $r           - Apache request object
1.754     raeburn  9751:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     9752:     $line        - Number of the line being displayed.
1.503     raeburn  9753:     $questionnum - Question number (may include subquestion)
                   9754:     $error       - Type of error.
1.497     foxr     9755:     @selected    - Array of bubbles picked on this line.
1.423     albertel 9756: 
                   9757: =cut
                   9758: 
1.157     albertel 9759: sub scantron_bubble_selector {
1.503     raeburn  9760:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 9761:     my $max=$$scan_config{'Qlength'};
1.274     albertel 9762: 
                   9763:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  9764:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   9765:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   9766:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   9767:             $max=$$scan_config{'BubblesPerRow'};
                   9768:             if (($scmode eq 'number') && ($max > 10)) {
                   9769:                 $max = 10;
                   9770:             } elsif (($scmode eq 'letter') && $max > 26) {
                   9771:                 $max = 26;
                   9772:             }
                   9773:         } else {
                   9774:             $max = 10;
                   9775:         }
                   9776:     }
1.274     albertel 9777: 
1.157     albertel 9778:     my @alphabet=('A'..'Z');
1.503     raeburn  9779:     $r->print(&Apache::loncommon::start_data_table().
                   9780:               &Apache::loncommon::start_data_table_row());
                   9781:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     9782:     for (my $i=0;$i<$max+1;$i++) {
                   9783: 	$r->print("\n".'<td align="center">');
                   9784: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   9785: 	else { $r->print('&nbsp;'); }
                   9786: 	$r->print('</td>');
                   9787:     }
1.503     raeburn  9788:     $r->print(&Apache::loncommon::end_data_table_row().
                   9789:               &Apache::loncommon::start_data_table_row());
1.497     foxr     9790:     for (my $i=0;$i<$max;$i++) {
                   9791: 	$r->print("\n".
                   9792: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   9793: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   9794:     }
1.503     raeburn  9795:     my $nobub_checked = ' ';
                   9796:     if ($error eq 'missingbubble') {
                   9797:         $nobub_checked = ' checked = "checked" ';
                   9798:     }
                   9799:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   9800: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   9801:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   9802:               $line.'" value="'.$questionnum.'" /></td>');
                   9803:     $r->print(&Apache::loncommon::end_data_table_row().
                   9804:               &Apache::loncommon::end_data_table());
1.157     albertel 9805: }
                   9806: 
1.423     albertel 9807: =pod
                   9808: 
                   9809: =item num_matches
                   9810: 
1.424     albertel 9811:    Counts the number of characters that are the same between the two arguments.
                   9812: 
                   9813:  Arguments:
                   9814:    $orig - CODE from the scanline
                   9815:    $code - CODE to match against
                   9816: 
                   9817:  Returns:
                   9818:    $count - integer count of the number of same characters between the
                   9819:             two arguments
                   9820: 
1.423     albertel 9821: =cut
                   9822: 
1.194     albertel 9823: sub num_matches {
                   9824:     my ($orig,$code) = @_;
                   9825:     my @code=split(//,$code);
                   9826:     my @orig=split(//,$orig);
                   9827:     my $same=0;
                   9828:     for (my $i=0;$i<scalar(@code);$i++) {
                   9829: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   9830:     }
                   9831:     return $same;
                   9832: }
                   9833: 
1.423     albertel 9834: =pod
                   9835: 
                   9836: =item scantron_get_closely_matching_CODEs
                   9837: 
1.424     albertel 9838:    Cycles through all CODEs and finds the set that has the greatest
                   9839:    number of same characters as the provided CODE
                   9840: 
                   9841:  Arguments:
                   9842:    $allcodes - hash ref returned by &get_codes()
                   9843:    $CODE     - CODE from the current scanline
                   9844: 
                   9845:  Returns:
                   9846:    2 element list
                   9847:     - first elements is number of how closely matching the best fit is 
                   9848:       (5 means best set has 5 matching characters)
                   9849:     - second element is an arrary ref containing the set of valid CODEs
                   9850:       that best fit the passed in CODE
                   9851: 
1.423     albertel 9852: =cut
                   9853: 
1.194     albertel 9854: sub scantron_get_closely_matching_CODEs {
                   9855:     my ($allcodes,$CODE)=@_;
                   9856:     my @CODEs;
                   9857:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   9858: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   9859:     }
                   9860: 
                   9861:     return ($#CODEs,$CODEs[-1]);
                   9862: }
                   9863: 
1.423     albertel 9864: =pod
                   9865: 
                   9866: =item get_codes
                   9867: 
1.424     albertel 9868:    Builds a hash which has keys of all of the valid CODEs from the selected
                   9869:    set of remembered CODEs.
                   9870: 
                   9871:  Arguments:
                   9872:   $old_name - name of the set of remembered CODEs
                   9873:   $cdom     - domain of the course
                   9874:   $cnum     - internal course name
                   9875: 
                   9876:  Returns:
                   9877:   %allcodes - keys are the valid CODEs, values are all 1
                   9878: 
1.423     albertel 9879: =cut
                   9880: 
1.194     albertel 9881: sub get_codes {
1.280     foxr     9882:     my ($old_name, $cdom, $cnum) = @_;
                   9883:     if (!$old_name) {
                   9884: 	$old_name=$env{'form.scantron_CODElist'};
                   9885:     }
                   9886:     if (!$cdom) {
                   9887: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9888:     }
                   9889:     if (!$cnum) {
                   9890: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   9891:     }
1.278     albertel 9892:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   9893: 				    $cdom,$cnum);
                   9894:     my %allcodes;
                   9895:     if ($result{"type\0$old_name"} eq 'number') {
                   9896: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   9897:     } else {
                   9898: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   9899:     }
1.194     albertel 9900:     return %allcodes;
                   9901: }
                   9902: 
1.423     albertel 9903: =pod
                   9904: 
                   9905: =item scantron_validate_CODE
                   9906: 
1.424     albertel 9907:    Validates all scanlines in the selected file to not have any
                   9908:    invalid or underspecified CODEs and that none of the codes are
                   9909:    duplicated if this was requested.
                   9910: 
1.423     albertel 9911: =cut
                   9912: 
1.157     albertel 9913: sub scantron_validate_CODE {
                   9914:     my ($r,$currentphase) = @_;
1.754     raeburn  9915:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 9916:     if ($scantron_config{'CODElocation'} &&
                   9917: 	$scantron_config{'CODEstart'} &&
                   9918: 	$scantron_config{'CODElength'}) {
1.257     albertel 9919: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 9920: 	    &FIXME_blow_up()
                   9921: 	}
                   9922:     } else {
                   9923: 	return (0,$currentphase+1);
                   9924:     }
                   9925:     
                   9926:     my %usedCODEs;
                   9927: 
1.194     albertel 9928:     my %allcodes=&get_codes();
1.186     albertel 9929: 
1.582     raeburn  9930:     my $nav_error;
1.649     raeburn  9931:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  9932:     if ($nav_error) {
                   9933:         $r->print(&navmap_errormsg());
                   9934:         return(1,$currentphase);
                   9935:     }
1.447     foxr     9936: 
1.186     albertel 9937:     my ($scanlines,$scan_data)=&scantron_getfile();
                   9938:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9939: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 9940: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9941: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9942: 						 $scan_data);
                   9943: 	my $CODE=$$scan_record{'scantron.CODE'};
                   9944: 	my $error=0;
1.224     albertel 9945: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   9946: 	    &scantron_get_correction($r,$i,$scan_record,
                   9947: 				     \%scantron_config,
                   9948: 				     $line,'incorrectCODE',\%allcodes);
                   9949: 	    return(1,$currentphase);
                   9950: 	}
1.221     albertel 9951: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   9952: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 9953: 	    &scantron_get_correction($r,$i,$scan_record,
                   9954: 				     \%scantron_config,
1.194     albertel 9955: 				     $line,'incorrectCODE',\%allcodes);
                   9956: 	    return(1,$currentphase);
1.186     albertel 9957: 	}
1.214     albertel 9958: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 9959: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 9960: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 9961: 	    &scantron_get_correction($r,$i,$scan_record,
                   9962: 				     \%scantron_config,
1.194     albertel 9963: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   9964: 	    return(1,$currentphase);
1.186     albertel 9965: 	}
1.524     raeburn  9966: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 9967:     }
1.157     albertel 9968:     return (0,$currentphase+1);
                   9969: }
                   9970: 
1.423     albertel 9971: =pod
                   9972: 
                   9973: =item scantron_validate_doublebubble
                   9974: 
1.424     albertel 9975:    Validates all scanlines in the selected file to not have any
                   9976:    bubble lines with multiple bubbles marked.
                   9977: 
1.423     albertel 9978: =cut
                   9979: 
1.157     albertel 9980: sub scantron_validate_doublebubble {
                   9981:     my ($r,$currentphase) = @_;
                   9982:     #get student info
                   9983:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9984:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  9985:     my (undef,undef,$sequence)=
                   9986:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 9987: 
                   9988:     #get scantron line setup
1.754     raeburn  9989:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9990:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  9991: 
                   9992:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9993:     unless (ref($navmap)) {
                   9994:         $r->print(&navmap_errormsg());
                   9995:         return(1,$currentphase);
                   9996:     }
                   9997:     my $map=$navmap->getResourceByUrl($sequence);
                   9998:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9999:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10000:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   10001:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10002: 
1.583     raeburn  10003:     my $nav_error;
1.691     raeburn  10004:     if (ref($map)) {
                   10005:         $randomorder = $map->randomorder();
                   10006:         $randompick = $map->randompick();
1.788     raeburn  10007:         unless ($randomorder || $randompick) {
                   10008:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10009:                 if ($res->randomorder()) {
                   10010:                     $randomorder = 1;
                   10011:                 }
                   10012:                 if ($res->randompick()) {
                   10013:                     $randompick = 1;
                   10014:                 }
                   10015:                 last if ($randomorder || $randompick);
                   10016:             }
                   10017:         }
1.691     raeburn  10018:         if ($randomorder || $randompick) {
                   10019:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10020:             if ($nav_error) {
                   10021:                 $r->print(&navmap_errormsg());
                   10022:                 return(1,$currentphase);
                   10023:             }
                   10024:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10025:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   10026:         }
                   10027:     } else {
                   10028:         $r->print(&navmap_errormsg());
                   10029:         return(1,$currentphase);
                   10030:     }
                   10031: 
1.649     raeburn  10032:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  10033:     if ($nav_error) {
                   10034:         $r->print(&navmap_errormsg());
                   10035:         return(1,$currentphase);
                   10036:     }
1.447     foxr     10037: 
1.157     albertel 10038:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 10039: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10040: 	if ($line=~/^[\s\cz]*$/) { next; }
                   10041: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  10042: 						 $scan_data,undef,\%idmap,$randomorder,
                   10043:                                                  $randompick,$sequence,\@master_seq,
                   10044:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   10045:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 10046: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   10047: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   10048: 				 'doublebubble',
1.691     raeburn  10049: 				 $$scan_record{'scantron.doubleerror'},
                   10050:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 10051:     	return (1,$currentphase);
                   10052:     }
                   10053:     return (0,$currentphase+1);
                   10054: }
                   10055: 
1.423     albertel 10056: 
1.503     raeburn  10057: sub scantron_get_maxbubble {
1.649     raeburn  10058:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 10059:     if (defined($env{'form.scantron_maxbubble'}) &&
                   10060: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     10061: 	&restore_bubble_lines();
1.257     albertel 10062: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 10063:     }
1.330     albertel 10064: 
1.447     foxr     10065:     my (undef, undef, $sequence) =
1.257     albertel 10066: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 10067: 
1.447     foxr     10068:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10069:     unless (ref($navmap)) {
                   10070:         if (ref($nav_error)) {
                   10071:             $$nav_error = 1;
                   10072:         }
1.591     raeburn  10073:         return;
1.582     raeburn  10074:     }
1.191     albertel 10075:     my $map=$navmap->getResourceByUrl($sequence);
                   10076:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  10077:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 10078: 
                   10079:     &Apache::lonxml::clear_problem_counter();
                   10080: 
1.557     raeburn  10081:     my $uname       = $env{'user.name'};
                   10082:     my $udom        = $env{'user.domain'};
1.435     foxr     10083:     my $cid         = $env{'request.course.id'};
                   10084:     my $total_lines = 0;
                   10085:     %bubble_lines_per_response = ();
1.447     foxr     10086:     %first_bubble_line         = ();
1.503     raeburn  10087:     %subdivided_bubble_lines   = ();
                   10088:     %responsetype_per_response = ();
1.691     raeburn  10089:     %masterseq_id_responsenum  = ();
1.554     raeburn  10090: 
1.447     foxr     10091:     my $response_number = 0;
                   10092:     my $bubble_line     = 0;
1.191     albertel 10093:     foreach my $resource (@resources) {
1.691     raeburn  10094:         my $resid = $resource->id(); 
1.672     raeburn  10095:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   10096:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  10097:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   10098: 	    foreach my $part_id (@{$parts}) {
                   10099:                 my $lines;
                   10100: 
                   10101: 	        # TODO - make this a persistent hash not an array.
                   10102: 
                   10103:                 # optionresponse, matchresponse and rankresponse type items 
                   10104:                 # render as separate sub-questions in exam mode.
                   10105:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   10106:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   10107:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   10108:                     my ($numbub,$numshown);
                   10109:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   10110:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   10111:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   10112:                         }
                   10113:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   10114:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   10115:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   10116:                         }
                   10117:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   10118:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   10119:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   10120:                         }
                   10121:                     }
                   10122:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   10123:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   10124:                     }
1.649     raeburn  10125:                     my $bubbles_per_row =
                   10126:                         &bubblesheet_bubbles_per_row($scantron_config);
                   10127:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   10128:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  10129:                         $inner_bubble_lines++;
                   10130:                     }
                   10131:                     for (my $i=0; $i<$numshown; $i++) {
                   10132:                         $subdivided_bubble_lines{$response_number} .= 
                   10133:                             $inner_bubble_lines.',';
                   10134:                     }
                   10135:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   10136:                     $lines = $numshown * $inner_bubble_lines;
                   10137:                 } else {
                   10138:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  10139:                 }
1.542     raeburn  10140: 
                   10141:                 $first_bubble_line{$response_number} = $bubble_line;
                   10142: 	        $bubble_lines_per_response{$response_number} = $lines;
                   10143:                 $responsetype_per_response{$response_number} = 
                   10144:                     $analysis->{$part_id.'.type'};
1.691     raeburn  10145:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  10146: 	        $response_number++;
                   10147: 
                   10148: 	        $bubble_line +=  $lines;
                   10149: 	        $total_lines +=  $lines;
                   10150: 	    }
                   10151:         }
                   10152:     }
1.552     raeburn  10153:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  10154: 
                   10155:     &save_bubble_lines();
                   10156:     $env{'form.scantron_maxbubble'} =
                   10157: 	$total_lines;
                   10158:     return $env{'form.scantron_maxbubble'};
                   10159: }
1.523     raeburn  10160: 
1.649     raeburn  10161: sub bubblesheet_bubbles_per_row {
                   10162:     my ($scantron_config) = @_;
                   10163:     my $bubbles_per_row;
                   10164:     if (ref($scantron_config) eq 'HASH') {
                   10165:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   10166:     }
                   10167:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   10168:         $bubbles_per_row = 10;
                   10169:     }
                   10170:     return $bubbles_per_row;
                   10171: }
                   10172: 
1.157     albertel 10173: sub scantron_validate_missingbubbles {
                   10174:     my ($r,$currentphase) = @_;
                   10175:     #get student info
                   10176:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10177:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  10178:     my (undef,undef,$sequence)=
                   10179:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 10180: 
                   10181:     #get scantron line setup
1.754     raeburn  10182:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 10183:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  10184: 
                   10185:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10186:     unless (ref($navmap)) {
                   10187:         $r->print(&navmap_errormsg());
                   10188:         return(1,$currentphase);
                   10189:     }
                   10190: 
                   10191:     my $map=$navmap->getResourceByUrl($sequence);
                   10192:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10193:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10194:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   10195:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10196: 
1.582     raeburn  10197:     my $nav_error;
1.691     raeburn  10198:     if (ref($map)) {
                   10199:         $randomorder = $map->randomorder();
                   10200:         $randompick = $map->randompick();
1.788     raeburn  10201:         unless ($randomorder || $randompick) {
                   10202:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10203:                 if ($res->randomorder()) {
                   10204:                     $randomorder = 1;
                   10205:                 }
                   10206:                 if ($res->randompick()) {
                   10207:                     $randompick = 1;
                   10208:                 }
                   10209:                 last if ($randomorder || $randompick);
                   10210:             }
                   10211:         }
1.691     raeburn  10212:         if ($randomorder || $randompick) {
                   10213:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10214:             if ($nav_error) {
                   10215:                 $r->print(&navmap_errormsg());
                   10216:                 return(1,$currentphase);
                   10217:             }
                   10218:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10219:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   10220:         }
                   10221:     } else {
                   10222:         $r->print(&navmap_errormsg());
                   10223:         return(1,$currentphase);
                   10224:     }
                   10225: 
                   10226: 
1.649     raeburn  10227:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  10228:     if ($nav_error) {
1.691     raeburn  10229:         $r->print(&navmap_errormsg());
1.693     raeburn  10230:         return(1,$currentphase);
1.582     raeburn  10231:     }
1.691     raeburn  10232: 
1.157     albertel 10233:     if (!$max_bubble) { $max_bubble=2**31; }
                   10234:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 10235: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10236: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  10237: 	my $scan_record =
                   10238:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   10239: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   10240:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   10241:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 10242: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   10243: 	my @to_correct;
1.470     foxr     10244: 	
                   10245: 	# Probably here's where the error is...
                   10246: 
1.157     albertel 10247: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  10248:             my $lastbubble;
                   10249:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   10250:                my $question = $1;
                   10251:                my $subquestion = $2;
1.691     raeburn  10252:                my ($first,$responsenum);
                   10253:                if ($randomorder || $randompick) {
                   10254:                    $responsenum = $respnumlookup{$question-1};
                   10255:                    $first = $startline{$question-1};
                   10256:                } else {
                   10257:                    $responsenum = $question-1; 
                   10258:                    $first = $first_bubble_line{$responsenum};
                   10259:                }
                   10260:                if (!defined($first)) { next; }
                   10261:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  10262:                my $subcount = 1;
                   10263:                while ($subcount<$subquestion) {
                   10264:                    $first += $subans[$subcount-1];
                   10265:                    $subcount ++;
                   10266:                }
                   10267:                my $count = $subans[$subquestion-1];
                   10268:                $lastbubble = $first + $count;
                   10269:             } else {
1.691     raeburn  10270:                my ($first,$responsenum);
                   10271:                if ($randomorder || $randompick) {
                   10272:                    $responsenum = $respnumlookup{$missing-1};
                   10273:                    $first = $startline{$missing-1};
                   10274:                } else {
                   10275:                    $responsenum = $missing-1;
                   10276:                    $first = $first_bubble_line{$responsenum};
                   10277:                }
                   10278:                if (!defined($first)) { next; }
                   10279:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  10280:             }
                   10281:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 10282: 	    push(@to_correct,$missing);
                   10283: 	}
                   10284: 	if (@to_correct) {
                   10285: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  10286: 				     $line,'missingbubble',\@to_correct,
                   10287:                                      $randomorder,$randompick,\%respnumlookup,
                   10288:                                      \%startline);
1.157     albertel 10289: 	    return (1,$currentphase);
                   10290: 	}
                   10291: 
                   10292:     }
                   10293:     return (0,$currentphase+1);
                   10294: }
                   10295: 
1.663     raeburn  10296: sub hand_bubble_option {
                   10297:     my (undef, undef, $sequence) =
                   10298:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10299:     return if ($sequence eq '');
                   10300:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10301:     unless (ref($navmap)) {
                   10302:         return;
                   10303:     }
                   10304:     my $needs_hand_bubbles;
                   10305:     my $map=$navmap->getResourceByUrl($sequence);
                   10306:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10307:     foreach my $res (@resources) {
                   10308:         if (ref($res)) {
                   10309:             if ($res->is_problem()) {
                   10310:                 my $partlist = $res->parts();
                   10311:                 foreach my $part (@{ $partlist }) {
                   10312:                     my @types = $res->responseType($part);
                   10313:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   10314:                         $needs_hand_bubbles = 1;
                   10315:                         last;
                   10316:                     }
                   10317:                 }
                   10318:             }
                   10319:         }
                   10320:     }
                   10321:     if ($needs_hand_bubbles) {
1.754     raeburn  10322:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  10323:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10324:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   10325:                &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 />').
                   10326:                '<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;'.
1.722     raeburn  10327:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  10328:     }
                   10329:     return;
                   10330: }
1.423     albertel 10331: 
1.82      albertel 10332: sub scantron_process_students {
1.608     www      10333:     my ($r,$symb) = @_;
1.513     foxr     10334: 
1.257     albertel 10335:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     10336:     if (!$symb) {
                   10337: 	return '';
                   10338:     }
1.324     albertel 10339:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 10340: 
1.754     raeburn  10341:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  10342:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 10343:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 10344:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10345:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 10346:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10347:     unless (ref($navmap)) {
                   10348:         $r->print(&navmap_errormsg());
                   10349:         return '';
1.691     raeburn  10350:     }
1.83      albertel 10351:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10352:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.788     raeburn  10353:         %grader_randomlists_by_symb,%symb_for_examcode);
1.677     raeburn  10354:     if (ref($map)) {
                   10355:         $randomorder = $map->randomorder();
1.689     raeburn  10356:         $randompick = $map->randompick();
1.788     raeburn  10357:         unless ($randomorder || $randompick) {
                   10358:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10359:                 if ($res->randomorder()) {
                   10360:                     $randomorder = 1;
                   10361:                 }
                   10362:                 if ($res->randompick()) {
                   10363:                     $randompick = 1;
                   10364:                 }
                   10365:                 last if ($randomorder || $randompick);
                   10366:             }
                   10367:         }
1.691     raeburn  10368:     } else {
                   10369:         $r->print(&navmap_errormsg());
                   10370:         return '';
1.677     raeburn  10371:     }
1.691     raeburn  10372:     my $nav_error;
1.83      albertel 10373:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10374:     if ($randomorder || $randompick) {
1.788     raeburn  10375:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
1.691     raeburn  10376:         if ($nav_error) {
                   10377:             $r->print(&navmap_errormsg());
                   10378:             return '';
                   10379:         }
                   10380:     }
1.557     raeburn  10381:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  10382:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  10383: 
1.554     raeburn  10384:     my ($uname,$udom);
1.82      albertel 10385:     my $result= <<SCANTRONFORM;
1.81      albertel 10386: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   10387:   <input type="hidden" name="command" value="scantron_configphase" />
                   10388:   $default_form_data
                   10389: SCANTRONFORM
1.82      albertel 10390:     $r->print($result);
                   10391: 
1.770     raeburn  10392:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 10393:     my @delayqueue;
1.542     raeburn  10394:     my (%completedstudents,%scandata);
1.770     raeburn  10395: 
1.520     www      10396:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 10397:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10398:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   10399:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  10400:     $r->print('<br />');
1.140     albertel 10401:     my $start=&Time::HiRes::time();
1.158     albertel 10402:     my $i=-1;
1.542     raeburn  10403:     my $started;
1.447     foxr     10404: 
1.649     raeburn  10405:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10406:     if ($nav_error) {
                   10407:         $r->print(&navmap_errormsg());
                   10408:         return '';
                   10409:     }
                   10410: 
1.513     foxr     10411:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   10412:     # the user and return.
                   10413: 
                   10414:     if ($ssi_error) {
                   10415: 	$r->print("</form>");
                   10416: 	&ssi_print_error($r);
1.520     www      10417:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     10418: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   10419:     }
1.447     foxr     10420: 
1.755     raeburn  10421:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  10422:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  10423:     my %orderedforcode;
1.542     raeburn  10424: 
1.157     albertel 10425:     while ($i<$scanlines->{'count'}) {
                   10426:  	($uname,$udom)=('','');
                   10427:  	$i++;
1.200     albertel 10428:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10429:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 10430: 	if ($started) {
1.667     www      10431: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 10432: 	}
                   10433: 	$started=1;
1.691     raeburn  10434:         my %respnumlookup = ();
                   10435:         my %startline = ();
                   10436:         my $total;
1.157     albertel 10437:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  10438:                                                  $scan_data,undef,\%idmap,$randomorder,
                   10439:                                                  $randompick,$sequence,\@master_seq,
                   10440:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   10441:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   10442:                                                  \$total);
1.157     albertel 10443:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10444:  					      \%idmap,$i)) {
                   10445:   	    &scantron_add_delay(\@delayqueue,$line,
                   10446:  				'Unable to find a student that matches',1);
                   10447:  	    next;
                   10448:   	}
                   10449:  	if (exists $completedstudents{$uname}) {
                   10450:  	    &scantron_add_delay(\@delayqueue,$line,
                   10451:  				'Student '.$uname.' has multiple sheets',2);
                   10452:  	    next;
                   10453:  	}
1.677     raeburn  10454:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  10455:         if (($checksec ne '') && ($checksec ne $usec)) {
                   10456:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   10457:                 &scantron_add_delay(\@delayqueue,$line,
                   10458:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   10459:                 next;
                   10460:             }
                   10461:         }
1.677     raeburn  10462:         my $user = $uname.':'.$usec;
1.157     albertel 10463:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 10464: 
1.677     raeburn  10465:         my $scancode;
                   10466:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10467:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10468:             $scancode = $scan_record->{'scantron.CODE'};
                   10469:         } else {
                   10470:             $scancode = '';
                   10471:         }
                   10472: 
                   10473:         my @mapresources = @resources;
1.689     raeburn  10474:         if ($randomorder || $randompick) {
1.678     raeburn  10475:             @mapresources = 
1.691     raeburn  10476:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10477:                              \%orderedforcode);
1.677     raeburn  10478:         }
1.586     raeburn  10479:         my (%partids_by_symb,$res_error);
1.677     raeburn  10480:         foreach my $resource (@mapresources) {
1.586     raeburn  10481:             my $ressymb;
                   10482:             if (ref($resource)) {
                   10483:                 $ressymb = $resource->symb();
                   10484:             } else {
                   10485:                 $res_error = 1;
                   10486:                 last;
                   10487:             }
1.557     raeburn  10488:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10489:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10490:                 my $currcode;
                   10491:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10492:                     $currcode = $scancode;
                   10493:                 }
1.557     raeburn  10494:                 my ($analysis,$parts) =
1.672     raeburn  10495:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  10496:                                               $uname,$udom,undef,$bubbles_per_row,
                   10497:                                               $currcode);
1.557     raeburn  10498:                 $partids_by_symb{$ressymb} = $parts;
                   10499:             } else {
                   10500:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   10501:             }
1.554     raeburn  10502:         }
                   10503: 
1.586     raeburn  10504:         if ($res_error) {
                   10505:             &scantron_add_delay(\@delayqueue,$line,
                   10506:                                 'An error occurred while grading student '.$uname,2);
                   10507:             next;
                   10508:         }
                   10509: 
1.330     albertel 10510: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  10511:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 10512: 
                   10513: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   10514: 	    &scantron_putfile($scanlines,$scan_data);
                   10515: 	}
1.161     albertel 10516: 	
1.542     raeburn  10517:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10518:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  10519:                                    $bubbles_per_row,$randomorder,$randompick,
                   10520:                                    \%respnumlookup,\%startline) 
                   10521:             eq 'ssi_error') {
1.542     raeburn  10522:             $ssi_error = 0; # So end of handler error message does not trigger.
                   10523:             $r->print("</form>");
                   10524:             &ssi_print_error($r);
                   10525:             &Apache::lonnet::remove_lock($lock);
                   10526:             return '';      # Why return ''?  Beats me.
                   10527:         }
1.513     foxr     10528: 
1.692     raeburn  10529:         if (($scancode) && ($randomorder || $randompick)) {
1.788     raeburn  10530:             foreach my $key (keys(%symb_for_examcode)) {
                   10531:                 my $symb_in_map = $symb_for_examcode{$key};
                   10532:                 if ($symb_in_map ne '') {
                   10533:                     my $parmresult =
                   10534:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   10535:                                                                '0_examcode',2,$scancode,
                   10536:                                                                'string_examcode',$uname,
                   10537:                                                                $udom);
                   10538:                 }
                   10539:             }
1.692     raeburn  10540:         }
1.140     albertel 10541: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  10542:         if ($env{'form.verifyrecord'}) {
                   10543:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  10544:             if ($randompick) {
                   10545:                 if ($total) {
                   10546:                     $lastpos = $total*$scantron_config{'Qlength'};
                   10547:                 }
                   10548:             }
                   10549: 
1.542     raeburn  10550:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10551:             chomp($studentdata);
                   10552:             $studentdata =~ s/\r$//;
                   10553:             my $studentrecord = '';
                   10554:             my $counter = -1;
1.677     raeburn  10555:             foreach my $resource (@mapresources) {
1.554     raeburn  10556:                 my $ressymb = $resource->symb();
1.542     raeburn  10557:                 ($counter,my $recording) =
                   10558:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10559:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10560:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   10561:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  10562:                 $studentrecord .= $recording;
                   10563:             }
                   10564:             if ($studentrecord ne $studentdata) {
1.554     raeburn  10565:                 &Apache::lonxml::clear_problem_counter();
                   10566:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10567:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  10568:                                            $bubbles_per_row,$randomorder,$randompick,
                   10569:                                            \%respnumlookup,\%startline) 
                   10570:                     eq 'ssi_error') {
1.554     raeburn  10571:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   10572:                     $r->print("</form>");
                   10573:                     &ssi_print_error($r);
                   10574:                     &Apache::lonnet::remove_lock($lock);
                   10575:                     delete($completedstudents{$uname});
                   10576:                     return '';
                   10577:                 }
1.542     raeburn  10578:                 $counter = -1;
                   10579:                 $studentrecord = '';
1.677     raeburn  10580:                 foreach my $resource (@mapresources) {
1.554     raeburn  10581:                     my $ressymb = $resource->symb();
1.542     raeburn  10582:                     ($counter,my $recording) =
                   10583:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10584:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10585:                                                  \%scantron_config,\%lettdig,$numletts,
                   10586:                                                  $randomorder,$randompick,\%respnumlookup,
                   10587:                                                  \%startline);
1.542     raeburn  10588:                     $studentrecord .= $recording;
                   10589:                 }
                   10590:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   10591:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  10592:                     if ($scancode eq '') {
1.658     bisitz   10593:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  10594:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   10595:                     } else {
1.658     bisitz   10596:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  10597:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   10598:                     }
                   10599:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   10600:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   10601:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   10602:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   10603:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10604:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   10605:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  10606:                               &Apache::loncommon::end_data_table_row().
                   10607:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10608:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   10609:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  10610:                               &Apache::loncommon::end_data_table_row().
                   10611:                               &Apache::loncommon::end_data_table().'</p>');
                   10612:                 } else {
                   10613:                     $r->print('<br /><span class="LC_warning">'.
                   10614:                              &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 />'.
                   10615:                              &mt("As a consequence, this user's submission history records two tries.").
                   10616:                                  '</span><br />');
                   10617:                 }
                   10618:             }
                   10619:         }
1.543     raeburn  10620:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 10621:     } continue {
1.330     albertel 10622: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  10623: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 10624:     }
1.140     albertel 10625:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      10626:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 10627: #    my $lasttime = &Time::HiRes::time()-$start;
                   10628: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 10629: 
1.200     albertel 10630:     $r->print("</form>");
1.157     albertel 10631:     return '';
1.75      albertel 10632: }
1.157     albertel 10633: 
1.557     raeburn  10634: sub graders_resources_pass {
1.649     raeburn  10635:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   10636:         $bubbles_per_row) = @_;
1.557     raeburn  10637:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   10638:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   10639:         foreach my $resource (@{$resources}) {
                   10640:             my $ressymb = $resource->symb();
                   10641:             my ($analysis,$parts) =
                   10642:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  10643:                                           $env{'user.name'},$env{'user.domain'},
                   10644:                                           1,$bubbles_per_row);
1.557     raeburn  10645:             $grader_partids_by_symb->{$ressymb} = $parts;
                   10646:             if (ref($analysis) eq 'HASH') {
                   10647:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   10648:                     $grader_randomlists_by_symb->{$ressymb} =
                   10649:                         $analysis->{'parts_withrandomlist'};
                   10650:                 }
                   10651:             }
                   10652:         }
                   10653:     }
                   10654:     return;
                   10655: }
                   10656: 
1.678     raeburn  10657: =pod
                   10658: 
                   10659: =item users_order
                   10660: 
                   10661:   Returns array of resources in current map, ordered based on either CODE,
                   10662:   if this is a CODEd exam, or based on student's identity if this is a 
                   10663:   "NAMEd" exam.
                   10664: 
1.691     raeburn  10665:   Should be used when randomorder and/or randompick applied when the 
                   10666:   corresponding exam was printed, prior to students completing bubblesheets 
                   10667:   for the version of the exam the student received.
1.678     raeburn  10668: 
                   10669: =cut
                   10670: 
                   10671: sub users_order  {
1.691     raeburn  10672:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  10673:     my @mapresources;
1.691     raeburn  10674:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  10675:         return @mapresources;
1.691     raeburn  10676:     }
                   10677:     if ($scancode) {
                   10678:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   10679:             @mapresources = @{$orderedforcode->{$scancode}};
                   10680:         } else {
                   10681:             $env{'form.CODE'} = $scancode;
                   10682:             my $actual_seq =
                   10683:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10684:                                                                $master_seq,
                   10685:                                                                $user,$scancode,1);
                   10686:             if (ref($actual_seq) eq 'ARRAY') {
                   10687:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10688:                 if (ref($orderedforcode) eq 'HASH') {
                   10689:                     if (@mapresources > 0) { 
                   10690:                         $orderedforcode->{$scancode} = \@mapresources;
                   10691:                     }
                   10692:                 }
                   10693:             }
                   10694:             delete($env{'form.CODE'});
1.678     raeburn  10695:         }
                   10696:     } else {
                   10697:         my $actual_seq =
                   10698:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10699:                                                            $master_seq,
1.688     raeburn  10700:                                                            $user,undef,1);
1.678     raeburn  10701:         if (ref($actual_seq) eq 'ARRAY') {
                   10702:             @mapresources = 
                   10703:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10704:         }
1.691     raeburn  10705:     }
                   10706:     return @mapresources;
1.678     raeburn  10707: }
                   10708: 
1.542     raeburn  10709: sub grade_student_bubbles {
1.691     raeburn  10710:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   10711:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   10712:     my $uselookup = 0;
                   10713:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   10714:         (ref($startline) eq 'HASH')) {
                   10715:         $uselookup = 1;
                   10716:     }
                   10717: 
1.554     raeburn  10718:     if (ref($resources) eq 'ARRAY') {
                   10719:         my $count = 0;
                   10720:         foreach my $resource (@{$resources}) {
                   10721:             my $ressymb = $resource->symb();
                   10722:             my %form = ('submitted'      => 'scantron',
                   10723:                         'grade_target'   => 'grade',
                   10724:                         'grade_username' => $uname,
                   10725:                         'grade_domain'   => $udom,
                   10726:                         'grade_courseid' => $env{'request.course.id'},
                   10727:                         'grade_symb'     => $ressymb,
                   10728:                         'CODE'           => $scancode
                   10729:                        );
1.649     raeburn  10730:             if ($bubbles_per_row ne '') {
                   10731:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   10732:             }
1.663     raeburn  10733:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   10734:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   10735:             }
1.554     raeburn  10736:             if (ref($parts) eq 'HASH') {
                   10737:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   10738:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  10739:                         if ($uselookup) {
                   10740:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   10741:                         } else {
                   10742:                             $form{'scantron_questnum_start.'.$part} =
                   10743:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   10744:                         }
1.554     raeburn  10745:                         $count++;
                   10746:                     }
                   10747:                 }
                   10748:             }
                   10749:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   10750:             return 'ssi_error' if ($ssi_error);
                   10751:             last if (&Apache::loncommon::connection_aborted($r));
                   10752:         }
1.542     raeburn  10753:     }
                   10754:     return;
                   10755: }
                   10756: 
1.157     albertel 10757: sub scantron_upload_scantron_data {
1.767     raeburn  10758:     my ($r,$symb) = @_;
1.565     raeburn  10759:     my $dom = $env{'request.role.domain'};
1.754     raeburn  10760:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  10761:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   10762:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 10763:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 10764: 							  'domainid',
1.565     raeburn  10765: 							  'coursename',$dom);
                   10766:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   10767:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      10768:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  10769:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  10770:     &js_escape(\$nofile_alert);
1.579     raeburn  10771:     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.736     damieng  10772:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 10773:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 10774:     function checkUpload(formname) {
                   10775: 	if (formname.upfile.value == "") {
1.579     raeburn  10776: 	    alert("'.$nofile_alert.'");
1.157     albertel 10777: 	    return false;
                   10778: 	}
1.565     raeburn  10779:         if (formname.courseid.value == "") {
1.579     raeburn  10780:             alert("'.$nocourseid_alert.'");
1.565     raeburn  10781:             return false;
                   10782:         }
1.157     albertel 10783: 	formname.submit();
                   10784:     }
1.565     raeburn  10785: 
                   10786:     function ToSyllabus() {
                   10787:         var cdom = '."'$dom'".';
                   10788:         var cnum = document.rules.courseid.value;
                   10789:         if (cdom == "" || cdom == null) {
                   10790:             return;
                   10791:         }
                   10792:         if (cnum == "" || cnum == null) {
                   10793:            return;
                   10794:         }
                   10795:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   10796:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   10797:         return;
                   10798:     }
                   10799: 
1.754     raeburn  10800:     '.$formatjs.'
1.597     wenzelju 10801: '));
                   10802:     $r->print('
1.648     bisitz   10803: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  10804: 
1.492     albertel 10805: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  10806: '.$default_form_data.
                   10807:   &Apache::lonhtmlcommon::start_pick_box().
                   10808:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   10809:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   10810:   &Apache::lonhtmlcommon::row_closure().
                   10811:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   10812:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   10813:   &Apache::lonhtmlcommon::row_closure().
                   10814:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   10815:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  10816:   &Apache::lonhtmlcommon::row_closure());
                   10817:     if ($formatoptions) {
                   10818:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   10819:                   &Apache::lonhtmlcommon::row_closure());
                   10820:     }
                   10821:     $r->print(
1.565     raeburn  10822:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   10823:   '<input type="file" name="upfile" size="50" />'.
                   10824:   &Apache::lonhtmlcommon::row_closure(1).
                   10825:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   10826: 
1.492     albertel 10827: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   10828: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 10829: </form>
1.492     albertel 10830: ');
1.157     albertel 10831:     return '';
                   10832: }
                   10833: 
1.754     raeburn  10834: sub scantron_upload_dataformat {
                   10835:     my ($dom) = @_;
                   10836:     my ($formatoptions,$formattitle,$formatjs);
                   10837:     $formatjs = <<'END';
                   10838: function toggleScantab(form) {
                   10839:    return;
                   10840: }
                   10841: END
                   10842:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   10843:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10844:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10845:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   10846:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   10847:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  10848:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   10849:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   10850:                             my ($onclick,$formatextra,$singleline);
                   10851:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   10852:                             my $count = 0;
                   10853:                             foreach my $line (@lines) {
1.790     raeburn  10854:                                 next if (($line =~ /^\#/) || ($line eq ''));
1.756     raeburn  10855:                                 $singleline = $line;
                   10856:                                 $count ++;
                   10857:                             }
                   10858:                             if ($count > 1) {
                   10859:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  10860:                                                '<span class="LC_nobreak">'.
1.776     raeburn  10861:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  10862:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  10863:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   10864:                                 $formatjs = <<"END";
1.754     raeburn  10865: function toggleScantab(form) {
                   10866:     var divid = 'bubbletype';
                   10867:     if (document.getElementById(divid)) {
                   10868:         var radioname = 'fileformat';
                   10869:         var num = form.elements[radioname].length;
                   10870:         if (num) {
                   10871:             for (var i=0; i<num; i++) {
                   10872:                 if (form.elements[radioname][i].checked) {
                   10873:                     var chosen = form.elements[radioname][i].value;
                   10874:                     if (chosen == 'dat') {
                   10875:                         document.getElementById(divid).style.display = 'none';
                   10876:                     } else if (chosen == 'csv') {
1.757     raeburn  10877:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  10878:                     }
                   10879:                 }
                   10880:             }
                   10881:         }
                   10882:     }
                   10883:     return;
                   10884: }
                   10885: 
                   10886: END
1.756     raeburn  10887:                             } elsif ($count == 1) {
                   10888:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   10889:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   10890:                             }
                   10891:                             $formattitle = &mt('File format');
                   10892:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   10893:                                              &mt('Plain Text (no delimiters)').
                   10894:                                              '</label>'.('&nbsp;'x2).
                   10895:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   10896:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  10897:                         }
                   10898:                     }
                   10899:                 }
                   10900:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  10901:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10902:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  10903:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  10904:                         $formatoptions = &scantron_scantab();
                   10905:                     }
1.754     raeburn  10906:                 }
                   10907:             }
                   10908:         }
                   10909:     }
                   10910:     return ($formatoptions,$formattitle,$formatjs);
                   10911: }
1.423     albertel 10912: 
1.157     albertel 10913: sub scantron_upload_scantron_data_save {
1.767     raeburn  10914:     my ($r,$symb) = @_;
1.182     albertel 10915:     my $doanotherupload=
                   10916: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   10917: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 10918: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 10919: 	'</form>'."\n";
1.257     albertel 10920:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 10921: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  10922: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   10923:         !&Apache::lonnet::allowed('usc',
                   10924:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      10925: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      10926: 	unless ($symb) {
1.182     albertel 10927: 	    $r->print($doanotherupload);
                   10928: 	}
1.162     albertel 10929: 	return '';
                   10930:     }
1.257     albertel 10931:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  10932:     my $uploadedfile;
1.710     bisitz   10933:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 10934:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10935:         $r->print(
                   10936:             &Apache::lonhtmlcommon::confirm_success(
                   10937:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10938:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 10939:     } else {
1.754     raeburn  10940:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   10941:         my $parser;
                   10942:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10943:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10944:                 my $is_csv;
                   10945:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   10946:                 if (@possibles > 1) {
                   10947:                     if ($env{'form.fileformat'} eq 'csv') {
                   10948:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10949:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10950:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10951:                                     $is_csv = 1;
                   10952:                                 }
1.754     raeburn  10953:                             }
                   10954:                         }
                   10955:                     }
                   10956:                 } elsif (@possibles == 1) {
                   10957:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10958:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10959:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10960:                                 $is_csv = 1;
                   10961:                             }
1.754     raeburn  10962:                         }
                   10963:                     }
                   10964:                 }
                   10965:                 if ($is_csv) {
                   10966:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   10967:                 }
                   10968:             }
                   10969:         }
                   10970:         my $result =
                   10971:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  10972:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   10973:         if ($result =~ m{^/uploaded/}) {
                   10974:             $r->print(
                   10975:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   10976:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   10977:                         (length($env{'form.upfile'})-1),
                   10978:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  10979:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  10980:             if ($uploadedfile =~ /^scantron_orig_/) {
                   10981:                 my $logname = $uploadedfile;
                   10982:                 $logname =~ s/^scantron_orig_//;
                   10983:                 if ($logname ne '') {
                   10984:                     my $now = time;
                   10985:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   10986:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   10987:                 }
                   10988:             }
1.567     raeburn  10989:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  10990:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   10991:         } else {
                   10992:             $r->print(
                   10993:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   10994:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   10995:                           $result,
1.568     raeburn  10996: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 10997: 	}
                   10998:     }
1.174     albertel 10999:     if ($symb) {
1.612     www      11000: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 11001:     } else {
1.182     albertel 11002: 	$r->print($doanotherupload);
1.174     albertel 11003:     }
1.157     albertel 11004:     return '';
                   11005: }
                   11006: 
1.567     raeburn  11007: sub validate_uploaded_scantron_file {
1.770     raeburn  11008:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   11009: 
1.567     raeburn  11010:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   11011:     my @lines;
                   11012:     if ($scanlines ne '-1') {
                   11013:         @lines=split("\n",$scanlines,-1);
                   11014:     }
1.770     raeburn  11015:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   11016:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   11017:     if ($context eq 'download') {
                   11018:         $priv = 'mgr';
                   11019:     } else {
                   11020:         $priv = 'usc';
                   11021:     }
                   11022:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   11023:             (($env{'request.course.id'}) &&
                   11024:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   11025:         if ($env{'request.course.sec'} ne '') {
                   11026:             unless (&Apache::lonnet::allowed($priv,
                   11027:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   11028:                 unless ($context eq 'download') {
                   11029:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   11030:                 }
                   11031:                 return $output;
                   11032:             }
                   11033:             ($checksec,@possibles)=&gradable_sections();
                   11034:         }
                   11035:     }
1.567     raeburn  11036:     if (@lines) {
                   11037:         my (%counts,$max_match_format);
1.710     bisitz   11038:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  11039:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   11040:         my %idmap = &username_to_idmap($classlist);
                   11041:         foreach my $key (keys(%idmap)) {
                   11042:             my $lckey = lc($key);
                   11043:             $idmap{$lckey} = $idmap{$key};
                   11044:         }
                   11045:         my %unique_formats;
1.754     raeburn  11046:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  11047:         foreach my $line (@formatlines) {
1.790     raeburn  11048:             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  11049:             my @config = split(/:/,$line);
                   11050:             my $idstart = $config[5];
                   11051:             my $idlength = $config[6];
                   11052:             if (($idstart ne '') && ($idlength > 0)) {
                   11053:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   11054:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   11055:                 } else {
                   11056:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   11057:                 }
                   11058:             }
                   11059:         }
                   11060:         foreach my $key (keys(%unique_formats)) {
                   11061:             my ($idstart,$idlength) = split(':',$key);
                   11062:             %{$counts{$key}} = (
                   11063:                                'found'   => 0,
                   11064:                                'total'   => 0,
1.770     raeburn  11065:                                'totalanysec' => 0,
                   11066:                                'othersec' => 0,
1.567     raeburn  11067:                               );
                   11068:             foreach my $line (@lines) {
                   11069:                 next if ($line =~ /^#/);
                   11070:                 next if ($line =~ /^[\s\cz]*$/);
                   11071:                 my $id = substr($line,$idstart-1,$idlength);
                   11072:                 $id = lc($id);
                   11073:                 if (exists($idmap{$id})) {
1.770     raeburn  11074:                     if ($checksec ne '') {
                   11075:                         $counts{$key}{'totalanysec'} ++;
                   11076:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   11077:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   11078:                             if ($stusec ne $checksec) {
                   11079:                                 if (@possibles) {
                   11080:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   11081:                                         $counts{$key}{'othersec'} ++;
                   11082:                                         next;
                   11083:                                     }
                   11084:                                 } else {
                   11085:                                     $counts{$key}{'othersec'} ++;
                   11086:                                     next;
                   11087:                                 }
                   11088:                             }
                   11089:                         }
                   11090:                     }
1.567     raeburn  11091:                     $counts{$key}{'found'} ++;
                   11092:                 }
                   11093:                 $counts{$key}{'total'} ++;
                   11094:             }
                   11095:             if ($counts{$key}{'total'}) {
                   11096:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   11097:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   11098:                     $max_match_pct = $percent_match;
                   11099:                     $max_match_format = $key;
1.710     bisitz   11100:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  11101:                     $max_match_count = $counts{$key}{'total'};
                   11102:                 }
                   11103:             }
                   11104:         }
1.770     raeburn  11105:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  11106:             my $format_descs;
                   11107:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   11108:             for (my $i=0; $i<$numwithformat; $i++) {
                   11109:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   11110:                 if ($i<$numwithformat-2) {
                   11111:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   11112:                 } elsif ($i==$numwithformat-2) {
                   11113:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   11114:                 } elsif ($i==$numwithformat-1) {
                   11115:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   11116:                 }
                   11117:             }
                   11118:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   11119:             $output .= '<br />';
                   11120:             if ($found_match_count == $max_match_count) {
                   11121:                 # 100% matching entries
                   11122:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   11123:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   11124:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   11125:                 &mt('Comparison of student IDs in the uploaded file with'.
                   11126:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   11127:                     ' in the file (for the format defined for [_3]).',
                   11128:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   11129:             } else {
                   11130:                 # Not all entries matching? -> Show warning and additional info
                   11131:                 $output .=
                   11132:                     &Apache::lonhtmlcommon::confirm_success(
                   11133:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   11134:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   11135:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   11136:                     &mt('Comparison of student IDs in the uploaded file with'.
                   11137:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   11138:                         ' in the file (for the format defined for [_3]).',
                   11139:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   11140:                     '<p class="LC_info">'.
                   11141:                     &mt('A low percentage of matches results from one of the following:').
                   11142:                     '</p><ul>'.
                   11143:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   11144:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   11145:                                '<i>'.$cdom.'</i>').'</li>'.
                   11146:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   11147:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   11148:                     '</ul>';
                   11149:             }
1.770     raeburn  11150:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11151:                 if ($counts{$max_match_format}{'othersec'}) {
                   11152:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   11153:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   11154:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   11155:                     &js_escape(\$confirmdel);
                   11156:                     $output .= '<p class="LC_warning">'.
                   11157:                                &mt('Comparison of student IDs in the uploaded file with the course roster found [_1][quant,_2,match,matches][_3] for students in section(s) for which none of your role(s) have privileges to modify grades',
                   11158:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   11159:                                '<br />'.
                   11160:                                &mt('Unless you are assigned role(s) which allow modification of grades in additional sections, [_1] of the records in this file will be automatically excluded when you perform bubblesheet grading.','<b>'.$showpct.'</b>').
                   11161:                                '</p><p>'.
                   11162:                                &mt('If you prefer to delete the file now, use: [_1]').
                   11163:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   11164:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   11165:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   11166:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   11167:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   11168:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   11169:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   11170:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   11171:                                '</form></p>';
                   11172:                 }
                   11173:             }
1.567     raeburn  11174:         }
1.770     raeburn  11175:         if (($context eq 'download') && ($checksec ne '')) {
                   11176:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11177:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   11178:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   11179:             }
                   11180:         } 
                   11181:     } elsif ($context ne 'download') {
1.710     bisitz   11182:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  11183:     }
                   11184:     return $output;
                   11185: }
                   11186: 
1.770     raeburn  11187: sub gradable_sections {
                   11188:     my $checksec = $env{'request.course.sec'};
                   11189:     my @oksecs;
                   11190:     if ($checksec) {
                   11191:         my %availablesecs = &sections_grade_privs();
                   11192:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   11193:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   11194:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   11195:                     push(@oksecs,$sec);
                   11196:                 }
                   11197:             }
                   11198:             if (grep(/^all$/,@oksecs)) {
                   11199:                 undef($checksec);
                   11200:             }
                   11201:         }
                   11202:     }
                   11203:     return($checksec,@oksecs);
                   11204: }
                   11205: 
                   11206: sub sections_grade_privs {
                   11207:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11208:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11209:     my %availablesecs = (
                   11210:                           mgr => [],
                   11211:                           vgr => [],
                   11212:                           usc => [],
                   11213:                         );
                   11214:     my $ccrole = 'cc';
                   11215:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   11216:         $ccrole = 'co';
                   11217:     }
                   11218:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   11219:                                                      'userroles',['active'],
                   11220:                                                      [$ccrole,'in','cr'],$cdom,1);
                   11221:     my $crsid = $cnum.':'.$cdom;
                   11222:     foreach my $item (keys(%crsroleshash)) {
                   11223:         next unless ($item =~ /^$crsid\:/);
                   11224:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   11225:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   11226:         if ($sec ne '') {
                   11227:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   11228:         }
                   11229:         if (($role eq $ccrole) || ($role eq 'in')) {
                   11230:             foreach my $priv ('mgr','vgr','usc') { 
                   11231:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11232:                     if ($sec eq '') {
                   11233:                         $availablesecs{$priv} = ['all'];
                   11234:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   11235:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11236:                             push(@{$availablesecs{$priv}},$sec);
                   11237:                         }
                   11238:                     }
                   11239:                 }
                   11240:             }
                   11241:         } elsif ($role =~ m{^cr/}) {
                   11242:             foreach my $priv ('mgr','vgr','usc') {
                   11243:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11244:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   11245:                         if ($sec eq '') {
                   11246:                             $availablesecs{$priv} = ['all'];
                   11247:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   11248:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11249:                                 push(@{$availablesecs{$priv}},$sec);
                   11250:                             }
                   11251:                         }
                   11252:                     }
                   11253:                 }
                   11254:             }
                   11255:         }
                   11256:     }
                   11257:     return %availablesecs;
                   11258: }
                   11259: 
                   11260: sub scantron_upload_delete {
                   11261:     my ($r,$symb) = @_;
                   11262:     my $filename = $env{'form.uploadedfile'};
                   11263:     if ($filename =~ /^scantron_orig_/) {
                   11264:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   11265:             &Apache::lonnet::allowed('usc',
                   11266:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   11267:             &Apache::lonnet::allowed('usc',
                   11268:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   11269:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   11270:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   11271:             if ($retrieval eq '-1') {
                   11272:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11273:                           &mt('File requested for deletion not found.'));
                   11274:             } else {
                   11275:                 $filename =~ s/^scantron_orig_//;
                   11276:                 if ($filename ne '') {
                   11277:                     my ($is_valid,$numleft);
                   11278:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11279:                     if (keys(%info)) {
                   11280:                         if (ref($info{$filename}) eq 'HASH') {
                   11281:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   11282:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11283:                                     $is_valid = 1;
                   11284:                                     delete($info{$filename}{$timestamp}); 
                   11285:                                 }
                   11286:                             }
                   11287:                             $numleft = scalar(keys(%{$info{$filename}}));
                   11288:                         }
                   11289:                     }
                   11290:                     if ($is_valid) {
                   11291:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   11292:                         if ($result eq 'ok') {
                   11293:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   11294:                             if ($numleft) {
                   11295:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   11296:                             } else {
                   11297:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11298:                             }
                   11299:                         } else {
                   11300:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11301:                                       &mt('Result was [_1]',$result));
                   11302:                         }
                   11303:                     } else {
                   11304:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11305:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   11306:                     }
                   11307:                 } else {
                   11308:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11309:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11310:                 }
                   11311:             }
                   11312:         } else {
                   11313:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   11314:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   11315:         }
                   11316:     } else {
                   11317:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11318:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11319:     }
                   11320:     return;
                   11321: }
                   11322: 
1.202     albertel 11323: sub valid_file {
                   11324:     my ($requested_file)=@_;
                   11325:     foreach my $filename (sort(&scantron_filenames())) {
                   11326: 	if ($requested_file eq $filename) { return 1; }
                   11327:     }
                   11328:     return 0;
                   11329: }
                   11330: 
                   11331: sub scantron_download_scantron_data {
1.767     raeburn  11332:     my ($r,$symb) = @_;
1.608     www      11333:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 11334:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   11335:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   11336:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 11337:     if (! &valid_file($file)) {
1.492     albertel 11338: 	$r->print('
1.202     albertel 11339: 	<p>
1.686     bisitz   11340: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 11341:         </p>
1.492     albertel 11342: ');
1.202     albertel 11343: 	return;
                   11344:     }
1.770     raeburn  11345:     my (%uploader,$is_owner,%counts,$percent);
                   11346:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   11347:     if (ref($uploader{$file}) eq 'HASH') {
                   11348:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   11349:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11350:                 $is_owner = 1;
                   11351:                 last;
                   11352:             }
                   11353:         }
                   11354:     }
                   11355:     unless ($is_owner) {
                   11356:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   11357:         if ($counts{'totalanysec'}) {
                   11358:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   11359:             if ($percent_othersec >= 10) {
                   11360:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   11361:                 $r->print('<p class="LC_warning">'.
                   11362:                           &mt('The original uploaded file includes [_1] or more of records for students for which none of your roles have rights to modify grades, so files are unavailable for download.',$showpct).
                   11363:                           '</p>');
                   11364:                 return;
                   11365:             }
                   11366:         }
                   11367:     }
1.202     albertel 11368:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   11369:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   11370:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   11371:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   11372:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   11373:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 11374:     $r->print('
1.202     albertel 11375:     <p>
1.723     raeburn  11376: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 11377: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 11378:     </p>
                   11379:     <p>
1.492     albertel 11380: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   11381: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 11382:     </p>
                   11383:     <p>
1.492     albertel 11384: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   11385: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 11386:     </p>
1.492     albertel 11387: ');
1.202     albertel 11388:     return '';
                   11389: }
1.157     albertel 11390: 
1.523     raeburn  11391: sub checkscantron_results {
1.608     www      11392:     my ($r,$symb) = @_;
1.523     raeburn  11393:     if (!$symb) {return '';}
                   11394:     my $cid = $env{'request.course.id'};
1.755     raeburn  11395:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  11396:     my $numletts = scalar(keys(%lettdig));
                   11397:     my $cnum = $env{'course.'.$cid.'.num'};
                   11398:     my $cdom = $env{'course.'.$cid.'.domain'};
                   11399:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   11400:     my %record;
                   11401:     my %scantron_config =
1.754     raeburn  11402:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  11403:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  11404:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  11405:     my $classlist=&Apache::loncoursedata::get_classlist();
                   11406:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   11407:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  11408:     unless (ref($navmap)) {
                   11409:         $r->print(&navmap_errormsg());
                   11410:         return '';
                   11411:     }
1.523     raeburn  11412:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  11413:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   11414:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  11415:     if (ref($map)) { 
                   11416:         $randomorder=$map->randomorder();
1.689     raeburn  11417:         $randompick=$map->randompick();
1.788     raeburn  11418:         unless ($randomorder || $randompick) {
                   11419:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   11420:                 if ($res->randomorder()) {
                   11421:                     $randomorder = 1;
                   11422:                 }
                   11423:                 if ($res->randompick()) {
                   11424:                     $randompick = 1;
                   11425:                 }
                   11426:                 last if ($randomorder || $randompick);
                   11427:             }
                   11428:         }
1.677     raeburn  11429:     }
1.557     raeburn  11430:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  11431:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   11432:     if ($nav_error) {
                   11433:         $r->print(&navmap_errormsg());
                   11434:         return '';
1.678     raeburn  11435:     }
1.673     raeburn  11436:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   11437:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  11438:     my ($uname,$udom);
1.523     raeburn  11439:     my (%scandata,%lastname,%bylast);
                   11440:     $r->print('
                   11441: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   11442: 
                   11443:     my @delayqueue;
                   11444:     my %completedstudents;
                   11445: 
1.691     raeburn  11446:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      11447:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  11448:     my ($username,$domain,$started);
1.649     raeburn  11449:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  11450:     if ($nav_error) {
                   11451:         $r->print(&navmap_errormsg());
                   11452:         return '';
                   11453:     }
1.523     raeburn  11454: 
1.667     www      11455:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  11456:     my $start=&Time::HiRes::time();
                   11457:     my $i=-1;
                   11458: 
                   11459:     while ($i<$scanlines->{'count'}) {
                   11460:         ($username,$domain,$uname)=('','','');
                   11461:         $i++;
                   11462:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   11463:         if ($line=~/^[\s\cz]*$/) { next; }
                   11464:         if ($started) {
1.667     www      11465:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  11466:         }
                   11467:         $started=1;
                   11468:         my $scan_record=
                   11469:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   11470:                                                      $scan_data);
1.693     raeburn  11471:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   11472:                                               \%idmap,$i)) {
1.523     raeburn  11473:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11474:                                 'Unable to find a student that matches',1);
                   11475:             next;
                   11476:         }
                   11477:         if (exists $completedstudents{$uname}) {
                   11478:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11479:                                 'Student '.$uname.' has multiple sheets',2);
                   11480:             next;
                   11481:         }
                   11482:         my $pid = $scan_record->{'scantron.ID'};
                   11483:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   11484:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  11485:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   11486:         my $user = $uname.':'.$usec;
1.523     raeburn  11487:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  11488: 
1.678     raeburn  11489:         my $scancode;
1.677     raeburn  11490:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   11491:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   11492:             $scancode = $scan_record->{'scantron.CODE'};
                   11493:         } else {
                   11494:             $scancode = '';
                   11495:         }
                   11496: 
                   11497:         my @mapresources = @resources;
1.691     raeburn  11498:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   11499:         my %respnumlookup=();
                   11500:         my %startline=();
1.689     raeburn  11501:         if ($randomorder || $randompick) {
1.678     raeburn  11502:             @mapresources =
1.691     raeburn  11503:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   11504:                              \%orderedforcode);
                   11505:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   11506:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   11507:                                              \%grader_partids_by_symb,\%orderedforcode,
                   11508:                                              \%respnumlookup,\%startline);
                   11509:             if ($randompick && $total) {
                   11510:                 $lastpos = $total*$scantron_config{'Qlength'};
                   11511:             }
1.677     raeburn  11512:         }
1.691     raeburn  11513:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   11514:         chomp($scandata{$pid});
                   11515:         $scandata{$pid} =~ s/\r$//;
                   11516: 
1.523     raeburn  11517:         my $counter = -1;
1.677     raeburn  11518:         foreach my $resource (@mapresources) {
1.557     raeburn  11519:             my $parts;
1.554     raeburn  11520:             my $ressymb = $resource->symb();
1.557     raeburn  11521:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   11522:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  11523:                 my $currcode;
                   11524:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   11525:                     $currcode = $scancode;
                   11526:                 }
1.557     raeburn  11527:                 (my $analysis,$parts) =
1.672     raeburn  11528:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   11529:                                               $username,$domain,undef,
1.741     raeburn  11530:                                               $bubbles_per_row,$currcode);
1.557     raeburn  11531:             } else {
                   11532:                 $parts = $grader_partids_by_symb{$ressymb};
                   11533:             }
1.542     raeburn  11534:             ($counter,my $recording) =
                   11535:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  11536:                                          $scandata{$pid},$parts,
1.691     raeburn  11537:                                          \%scantron_config,\%lettdig,$numletts,
                   11538:                                          $randomorder,$randompick,
                   11539:                                          \%respnumlookup,\%startline);
1.542     raeburn  11540:             $record{$pid} .= $recording;
1.523     raeburn  11541:         }
                   11542:     }
                   11543:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   11544:     $r->print('<br />');
                   11545:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   11546:     $passed = 0;
                   11547:     $failed = 0;
                   11548:     $numstudents = 0;
                   11549:     foreach my $last (sort(keys(%bylast))) {
                   11550:         if (ref($bylast{$last}) eq 'ARRAY') {
                   11551:             foreach my $pid (sort(@{$bylast{$last}})) {
                   11552:                 my $showscandata = $scandata{$pid};
                   11553:                 my $showrecord = $record{$pid};
                   11554:                 $showscandata =~ s/\s/&nbsp;/g;
                   11555:                 $showrecord =~ s/\s/&nbsp;/g;
                   11556:                 if ($scandata{$pid} eq $record{$pid}) {
                   11557:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   11558:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      11559: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  11560: '</tr>'."\n".
                   11561: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11562: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  11563:                     $passed ++;
                   11564:                 } else {
                   11565:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      11566:                     $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  11567: '</tr>'."\n".
                   11568: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11569: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  11570: '</tr>'."\n";
                   11571:                     $failed ++;
                   11572:                 }
                   11573:                 $numstudents ++;
                   11574:             }
                   11575:         }
                   11576:     }
1.648     bisitz   11577:     $r->print(
                   11578:         '<p>'
                   11579:        .&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).',
                   11580:             '<b>',
                   11581:             $numstudents,
                   11582:             '</b>',
                   11583:             $env{'form.scantron_maxbubble'})
                   11584:        .'</p>'
                   11585:     );
1.682     raeburn  11586:     $r->print('<p>'
1.683     raeburn  11587:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  11588:              .'<br />'
                   11589:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   11590:              .'</p>'
                   11591:     );
1.523     raeburn  11592:     if ($passed) {
1.572     www      11593:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11594:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11595:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11596:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11597:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11598:                  $okstudents."\n".
                   11599:                  &Apache::loncommon::end_data_table().'<br />');
                   11600:     }
                   11601:     if ($failed) {
1.572     www      11602:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11603:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11604:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11605:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11606:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11607:                  $badstudents."\n".
                   11608:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      11609:                  &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  11610:     }
1.614     www      11611:     $r->print('</form><br />');
1.523     raeburn  11612:     return;
                   11613: }
                   11614: 
1.542     raeburn  11615: sub verify_scantron_grading {
1.554     raeburn  11616:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  11617:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   11618:         $respnumlookup,$startline) = @_;
1.542     raeburn  11619:     my ($record,%expected,%startpos);
                   11620:     return ($counter,$record) if (!ref($resource));
                   11621:     return ($counter,$record) if (!$resource->is_problem());
                   11622:     my $symb = $resource->symb();
1.554     raeburn  11623:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   11624:     foreach my $part_id (@{$partids}) {
1.542     raeburn  11625:         $counter ++;
                   11626:         $expected{$part_id} = 0;
1.691     raeburn  11627:         my $respnum = $counter;
                   11628:         if ($randomorder || $randompick) {
                   11629:             $respnum = $respnumlookup->{$counter};
                   11630:             $startpos{$part_id} = $startline->{$counter} + 1;
                   11631:         } else {
                   11632:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   11633:         }
                   11634:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   11635:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  11636:             foreach my $item (@sub_lines) {
                   11637:                 $expected{$part_id} += $item;
                   11638:             }
                   11639:         } else {
1.691     raeburn  11640:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  11641:         }
                   11642:     }
                   11643:     if ($symb) {
                   11644:         my %recorded;
                   11645:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   11646:         if ($returnhash{'version'}) {
                   11647:             my %lasthash=();
                   11648:             my $version;
                   11649:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   11650:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   11651:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   11652:                 }
                   11653:             }
                   11654:             foreach my $key (keys(%lasthash)) {
                   11655:                 if ($key =~ /\.scantron$/) {
                   11656:                     my $value = &unescape($lasthash{$key});
                   11657:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   11658:                     if ($value eq '') {
                   11659:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11660:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   11661:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11662:                             }
                   11663:                         }
                   11664:                     } else {
                   11665:                         my @tocheck;
                   11666:                         my @items = split(//,$value);
                   11667:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   11668:                             ($scantron_config->{'Qon'} eq 'number')) {
                   11669:                             if (@items < $expected{$part_id}) {
                   11670:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   11671:                                 my @singles = split(//,$fragment);
                   11672:                                 foreach my $pos (@singles) {
                   11673:                                     if ($pos eq ' ') {
                   11674:                                         push(@tocheck,$pos);
                   11675:                                     } else {
                   11676:                                         my $next = shift(@items);
                   11677:                                         push(@tocheck,$next);
                   11678:                                     }
                   11679:                                 }
                   11680:                             } else {
                   11681:                                 @tocheck = @items;
                   11682:                             }
                   11683:                             foreach my $letter (@tocheck) {
                   11684:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   11685:                                     if ($letter !~ /^[A-J]$/) {
                   11686:                                         $letter = $scantron_config->{'Qoff'};
                   11687:                                     }
                   11688:                                     $recorded{$part_id} .= $letter;
                   11689:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   11690:                                     my $digit;
                   11691:                                     if ($letter !~ /^[A-J]$/) {
                   11692:                                         $digit = $scantron_config->{'Qoff'};
                   11693:                                     } else {
                   11694:                                         $digit = $lettdig->{$letter};
                   11695:                                     }
                   11696:                                     $recorded{$part_id} .= $digit;
                   11697:                                 }
                   11698:                             }
                   11699:                         } else {
                   11700:                             @tocheck = @items;
                   11701:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11702:                                 my $curr_sub = shift(@tocheck);
                   11703:                                 my $digit;
                   11704:                                 if ($curr_sub =~ /^[A-J]$/) {
                   11705:                                     $digit = $lettdig->{$curr_sub}-1;
                   11706:                                 }
                   11707:                                 if ($curr_sub eq 'J') {
                   11708:                                     $digit += scalar($numletts);
                   11709:                                 }
                   11710:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11711:                                     if ($j == $digit) {
                   11712:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   11713:                                     } else {
                   11714:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11715:                                     }
                   11716:                                 }
                   11717:                             }
                   11718:                         }
                   11719:                     }
                   11720:                 }
                   11721:             }
                   11722:         }
1.554     raeburn  11723:         foreach my $part_id (@{$partids}) {
1.542     raeburn  11724:             if ($recorded{$part_id} eq '') {
                   11725:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11726:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11727:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11728:                     }
                   11729:                 }
                   11730:             }
                   11731:             $record .= $recorded{$part_id};
                   11732:         }
                   11733:     }
                   11734:     return ($counter,$record);
                   11735: }
                   11736: 
1.75      albertel 11737: #-------- end of section for handling grading scantron forms -------
                   11738: #
                   11739: #-------------------------------------------------------------------
                   11740: 
1.72      ng       11741: #-------------------------- Menu interface -------------------------
                   11742: #
1.614     www      11743: #--- Href with symb and command ---
                   11744: 
                   11745: sub href_symb_cmd {
                   11746:     my ($symb,$cmd)=@_;
1.796     raeburn  11747:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.
                   11748:            &HTML::Entities::encode($cmd,'<>&"');
1.72      ng       11749: }
                   11750: 
1.443     banghart 11751: sub grading_menu {
1.608     www      11752:     my ($request,$symb) = @_;
1.443     banghart 11753:     if (!$symb) {return '';}
                   11754: 
                   11755:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      11756:                   'command'=>'individual');
1.538     schulted 11757:     
1.598     www      11758:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11759: 
                   11760:     $fields{'command'}='ungraded';
                   11761:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11762: 
                   11763:     $fields{'command'}='table';
                   11764:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11765: 
                   11766:     $fields{'command'}='all_for_one';
                   11767:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11768: 
1.621     www      11769:     $fields{'command'}='downloadfilesselect';
                   11770:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11771: 
1.443     banghart 11772:     $fields{'command'} = 'csvform';
1.538     schulted 11773:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11774:     
1.443     banghart 11775:     $fields{'command'} = 'processclicker';
1.538     schulted 11776:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11777:     
1.443     banghart 11778:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 11779:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      11780: 
                   11781:     $fields{'command'} = 'initialverifyreceipt';
                   11782:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  11783: 
                   11784:     my %permissions;
                   11785:     if ($perm{'mgr'}) {
                   11786:         $permissions{'either'} = 'F';
                   11787:         $permissions{'mgr'} = 'F';
                   11788:     }
                   11789:     if ($perm{'vgr'}) {
                   11790:         $permissions{'either'} = 'F';
                   11791:         $permissions{'vgr'} = 'F';
                   11792:     }
                   11793: 
1.598     www      11794:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 11795:             items =>[
1.598     www      11796:                         {	linktext => 'Select individual students to grade',
                   11797:                     		url => $url1a,
1.781     raeburn  11798:                     		permission => $permissions{'either'},
1.636     wenzelju 11799:                     		icon => 'grade_students.png',
1.598     www      11800:                     		linktitle => 'Grade current resource for a selection of students.'
                   11801:                         }, 
1.764     raeburn  11802:                         {       linktext => 'Grade ungraded submissions',
1.598     www      11803:                                 url => $url1b,
1.781     raeburn  11804:                                 permission => $permissions{'either'},
1.636     wenzelju 11805:                                 icon => 'ungrade_sub.png',
1.598     www      11806:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 11807:                         },
1.598     www      11808: 
                   11809:                         {       linktext => 'Grading table',
                   11810:                                 url => $url1c,
1.781     raeburn  11811:                                 permission => $permissions{'either'},
1.636     wenzelju 11812:                                 icon => 'grading_table.png',
1.598     www      11813:                                 linktitle => 'Grade current resource for all students.'
                   11814:                         },
1.615     www      11815:                         {       linktext => 'Grade page/folder for one student',
1.598     www      11816:                                 url => $url1d,
1.781     raeburn  11817:                                 permission => $permissions{'either'},
1.636     wenzelju 11818:                                 icon => 'grade_PageFolder.png',
1.598     www      11819:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      11820:                         },
                   11821:                         {       linktext => 'Download submissions',
                   11822:                                 url => $url1e,
1.781     raeburn  11823:                                 permission => $permissions{'either'},
1.636     wenzelju 11824:                                 icon => 'download_sub.png',
1.621     www      11825:                                 linktitle => 'Download all students submissions.'
1.598     www      11826:                         }]},
                   11827:                          { categorytitle=>'Automated Grading',
                   11828:                items =>[
                   11829: 
1.538     schulted 11830:                 	    {	linktext => 'Upload Scores',
                   11831:                     		url => $url2,
1.780     raeburn  11832:                     		permission => $permissions{'mgr'},
1.538     schulted 11833:                     		icon => 'uploadscores.png',
                   11834:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   11835:                 	    },
                   11836:                 	    {	linktext => 'Process Clicker',
                   11837:                     		url => $url3,
1.780     raeburn  11838:                     		permission => $permissions{'mgr'},
1.538     schulted 11839:                     		icon => 'addClickerInfoFile.png',
                   11840:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   11841:                 	    },
1.587     raeburn  11842:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 11843:                     		url => $url4,
1.780     raeburn  11844:                     		permission => $permissions{'mgr'},
1.636     wenzelju 11845:                     		icon => 'bubblesheet.png',
1.648     bisitz   11846:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      11847:                 	    },
1.616     www      11848:                             {   linktext => 'Verify Receipt Number',
1.602     www      11849:                                 url => $url5,
1.780     raeburn  11850:                                 permission => $permissions{'either'},
1.636     wenzelju 11851:                                 icon => 'receipt_number.png',
1.602     www      11852:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   11853:                             }
                   11854: 
1.538     schulted 11855:                     ]
                   11856:             });
1.796     raeburn  11857:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   11858:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   11859:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   11860:     if (keys(%passback)) {
                   11861:         $fields{'command'} = 'initialpassback';
                   11862:         my $url6 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11863:         push (@{$menu[1]{items}},
                   11864:                   { linktext => 'Passback of Scores',
                   11865:                     url => $url6,
                   11866:                     permission => $permissions{'either'},
                   11867:                     icon => 'passback.png',
                   11868:                     linktitle => 'Passback scores to launcher CMS for resources accessed via LTI-mediated deep-linking',
                   11869:                   });
                   11870:     }
1.443     banghart 11871:     # Create the menu
                   11872:     my $Str;
1.445     banghart 11873:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   11874:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      11875:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 11876: 
1.602     www      11877:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 11878:     return $Str;    
                   11879: }
                   11880: 
1.598     www      11881: sub ungraded {
                   11882:     my ($request)=@_;
                   11883:     &submit_options($request);
                   11884: }
                   11885: 
1.599     www      11886: sub submit_options_sequence {
1.608     www      11887:     my ($request,$symb) = @_;
1.599     www      11888:     if (!$symb) {return '';}
1.600     www      11889:     &commonJSfunctions($request);
                   11890:     my $result;
1.599     www      11891: 
1.600     www      11892:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11893:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      11894:     $result.=&selectfield(0).
1.601     www      11895:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      11896:             <div>
                   11897:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11898:             </div>
                   11899:         </div>
                   11900:   </form>';
                   11901:     return $result;
                   11902: }
                   11903: 
                   11904: sub submit_options_table {
1.608     www      11905:     my ($request,$symb) = @_;
1.600     www      11906:     if (!$symb) {return '';}
1.599     www      11907:     &commonJSfunctions($request);
1.746     raeburn  11908:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      11909:     my $result;
                   11910: 
                   11911:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11912:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      11913: 
1.745     raeburn  11914:     $result.=&selectfield(1,$is_tool).
1.601     www      11915:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      11916:             <div>
                   11917:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11918:             </div>
                   11919:         </div>
                   11920:   </form>';
                   11921:     return $result;
                   11922: }
1.443     banghart 11923: 
1.621     www      11924: sub submit_options_download {
                   11925:     my ($request,$symb) = @_;
                   11926:     if (!$symb) {return '';}
                   11927: 
1.773     raeburn  11928:     my $res_error;
                   11929:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   11930:         &response_type($symb,\$res_error);
                   11931:     if ($res_error) {
                   11932:         $request->print(&mt('An error occurred retrieving response types'));
                   11933:         return;
                   11934:     }
                   11935:     unless ($numessay) {
                   11936:         $request->print(&mt('No essayresponse items found'));
                   11937:         return;
                   11938:     }
                   11939:     my $table;
                   11940:     if (ref($partlist) eq 'ARRAY') {
                   11941:         if (scalar(@$partlist) > 1 ) {
                   11942:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   11943:         }
                   11944:     }
                   11945: 
1.746     raeburn  11946:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      11947:     &commonJSfunctions($request);
                   11948: 
                   11949:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  11950:                $table."\n".
                   11951:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      11952:     $result.='
                   11953: <h2>
1.750     raeburn  11954:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  11955: </h2>'.&selectfield(1,$is_tool).'
1.621     www      11956:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   11957:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11958:             </div>
                   11959:           </div>
1.600     www      11960: 
                   11961: 
1.621     www      11962:   </form>';
                   11963:     return $result;
                   11964: }
                   11965: 
1.443     banghart 11966: #--- Displays the submissions first page -------
                   11967: sub submit_options {
1.608     www      11968:     my ($request,$symb) = @_;
1.72      ng       11969:     if (!$symb) {return '';}
                   11970: 
1.746     raeburn  11971:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       11972:     &commonJSfunctions($request);
1.473     albertel 11973:     my $result;
1.533     bisitz   11974: 
1.72      ng       11975:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11976: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  11977:     $result.=&selectfield(1,$is_tool).'
1.601     www      11978:                 <input type="hidden" name="command" value="submission" /> 
                   11979: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11980:             </div>
                   11981:           </div>
                   11982:   </form>';
                   11983:     return $result;
                   11984: }
1.533     bisitz   11985: 
1.601     www      11986: sub selectfield {
1.745     raeburn  11987:    my ($full,$is_tool)=@_;
                   11988:    my %options;
                   11989:    if ($is_tool) {
                   11990:        %options =
                   11991:            (&transtatus_options,
                   11992:             'select_form_order' => ['yes','incorrect','all']);
                   11993:    } else {
                   11994:        %options = 
                   11995:            (&substatus_options,
                   11996:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   11997:    }
1.782     raeburn  11998: 
                   11999:   #
                   12000:   # PrepareClasslist() needs to be called to avoid getting a sections list
                   12001:   # for a different course from the @Sections global in lonstatistics.pm, 
                   12002:   # populated by an earlier request.
                   12003:   #
                   12004:    &Apache::lonstatistics::PrepareClasslist();
                   12005: 
1.601     www      12006:    my $result='<div class="LC_columnSection">
1.537     harmsja  12007:   
1.533     bisitz   12008:     <fieldset>
                   12009:       <legend>
                   12010:        '.&mt('Sections').'
                   12011:       </legend>
1.601     www      12012:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   12013:     </fieldset>
1.537     harmsja  12014:   
1.533     bisitz   12015:     <fieldset>
                   12016:       <legend>
                   12017:         '.&mt('Groups').'
                   12018:       </legend>
                   12019:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   12020:     </fieldset>
1.537     harmsja  12021:   
1.533     bisitz   12022:     <fieldset>
                   12023:       <legend>
                   12024:         '.&mt('Access Status').'
                   12025:       </legend>
1.601     www      12026:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   12027:     </fieldset>';
                   12028:     if ($full) {
1.745     raeburn  12029:         my $heading = &mt('Submission Status');
                   12030:         if ($is_tool) {
                   12031:             $heading = &mt('Transaction Status');
                   12032:         }
                   12033:         $result.='
1.533     bisitz   12034:     <fieldset>
                   12035:       <legend>
1.745     raeburn  12036:         '.$heading.'
1.601     www      12037:       </legend>'.
1.635     raeburn  12038:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      12039:    '</fieldset>';
                   12040:     }
                   12041:     $result.='</div><br />';
1.44      ng       12042:     return $result;
1.2       albertel 12043: }
                   12044: 
1.738     raeburn  12045: sub substatus_options {
                   12046:     return &Apache::lonlocal::texthash(
                   12047:                                       'yes'       => 'with submissions',
                   12048:                                       'queued'    => 'in grading queue',
                   12049:                                       'graded'    => 'with ungraded submissions',
                   12050:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  12051:                                       'all'       => 'with any status',
                   12052:                                       );
1.738     raeburn  12053: }
                   12054: 
1.745     raeburn  12055: sub transtatus_options {
                   12056:     return &Apache::lonlocal::texthash(
                   12057:                                        'yes'       => 'with score transactions',
                   12058:                                        'incorrect' => 'with less than full credit',
                   12059:                                        'all'       => 'with any status',
                   12060:                                       );
                   12061: }
                   12062: 
1.285     albertel 12063: sub reset_perm {
                   12064:     undef(%perm);
                   12065: }
                   12066: 
                   12067: sub init_perm {
                   12068:     &reset_perm();
1.770     raeburn  12069:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 12070: 
                   12071: 	my $scope = $env{'request.course.id'};
                   12072: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   12073: 
                   12074: 	    $scope .= '/'.$env{'request.course.sec'};
                   12075: 	    if ( $perm{$test_perm}=
                   12076: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   12077: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   12078: 	    } else {
                   12079: 		delete($perm{$test_perm});
                   12080: 	    }
1.285     albertel 12081: 	}
                   12082:     }
                   12083: }
                   12084: 
1.674     raeburn  12085: sub init_old_essays {
                   12086:     my ($symb,$apath,$adom,$aname) = @_;
                   12087:     if ($symb ne '') {
                   12088:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   12089:         if (keys(%essays) > 0) {
                   12090:             $old_essays{$symb} = \%essays;
                   12091:         }
                   12092:     }
                   12093:     return;
                   12094: }
                   12095: 
                   12096: sub reset_old_essays {
                   12097:     undef(%old_essays);
                   12098: }
                   12099: 
1.400     www      12100: sub gather_clicker_ids {
1.408     albertel 12101:     my %clicker_ids;
1.400     www      12102: 
                   12103:     my $classlist = &Apache::loncoursedata::get_classlist();
                   12104: 
                   12105:     # Set up a couple variables.
1.407     albertel 12106:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   12107:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      12108:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      12109: 
1.407     albertel 12110:     foreach my $student (keys(%$classlist)) {
1.438     www      12111:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 12112:         my $username = $classlist->{$student}->[$username_idx];
                   12113:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      12114:         my $clickers =
1.408     albertel 12115: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      12116:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      12117:             $id=~s/^[\#0]+//;
1.421     www      12118:             $id=~s/[\-\:]//g;
1.407     albertel 12119:             if (exists($clicker_ids{$id})) {
1.408     albertel 12120: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      12121:             } else {
1.408     albertel 12122: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      12123:             }
                   12124:         }
                   12125:     }
1.407     albertel 12126:     return %clicker_ids;
1.400     www      12127: }
                   12128: 
1.402     www      12129: sub gather_adv_clicker_ids {
1.408     albertel 12130:     my %clicker_ids;
1.402     www      12131:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   12132:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   12133:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 12134:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      12135:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   12136:             my ($puname,$pudom)=split(/\:/,$person);
                   12137:             my $clickers =
1.408     albertel 12138: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      12139:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      12140: 		$id=~s/^[\#0]+//;
1.421     www      12141:                 $id=~s/[\-\:]//g;
1.408     albertel 12142: 		if (exists($clicker_ids{$id})) {
                   12143: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   12144: 		} else {
                   12145: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   12146: 		}
1.405     www      12147:             }
1.402     www      12148:         }
                   12149:     }
1.407     albertel 12150:     return %clicker_ids;
1.402     www      12151: }
                   12152: 
1.413     www      12153: sub clicker_grading_parameters {
                   12154:     return ('gradingmechanism' => 'scalar',
                   12155:             'upfiletype' => 'scalar',
                   12156:             'specificid' => 'scalar',
                   12157:             'pcorrect' => 'scalar',
                   12158:             'pincorrect' => 'scalar');
                   12159: }
                   12160: 
1.400     www      12161: sub process_clicker {
1.608     www      12162:     my ($r,$symb)=@_;
1.400     www      12163:     if (!$symb) {return '';}
                   12164:     my $result=&checkforfile_js();
1.632     www      12165:     $result.=&Apache::loncommon::start_data_table().
                   12166:              &Apache::loncommon::start_data_table_header_row().
                   12167:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   12168:              &Apache::loncommon::end_data_table_header_row().
                   12169:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      12170: # Attempt to restore parameters from last session, set defaults if not present
                   12171:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12172:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   12173:                                                  \%Saveable_Parameters);
                   12174:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   12175:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   12176:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   12177:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   12178: 
                   12179:     my %checked;
1.521     www      12180:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      12181:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   12182:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      12183:        }
                   12184:     }
                   12185: 
1.632     www      12186:     my $upload=&mt("Evaluate File");
1.400     www      12187:     my $type=&mt("Type");
1.402     www      12188:     my $attendance=&mt("Award points just for participation");
                   12189:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      12190:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      12191:     my $given=&mt("Correctness determined from given list of answers").' '.
                   12192:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      12193:     my $pcorrect=&mt("Percentage points for correct solution");
                   12194:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      12195:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  12196: 						   {'iclicker' => 'i>clicker',
1.666     www      12197:                                                     'interwrite' => 'interwrite PRS',
                   12198:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 12199:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 12200:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      12201: function sanitycheck() {
                   12202: // Accept only integer percentages
                   12203:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   12204:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   12205: // Find out grading choice
                   12206:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12207:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   12208:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   12209:       }
                   12210:    }
                   12211: // By default, new choice equals user selection
                   12212:    newgradingchoice=gradingchoice;
                   12213: // Not good to give more points for false answers than correct ones
                   12214:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   12215:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   12216:    }
                   12217: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   12218:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   12219:       document.forms.gradesupload.pcorrect.value=100;
                   12220:       document.forms.gradesupload.pincorrect.value=100;
                   12221:    }
                   12222: // If the values are different, cannot be attendance only
                   12223:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   12224:        (gradingchoice=='attendance')) {
                   12225:        newgradingchoice='personnel';
                   12226:    }
                   12227: // Change grading choice to new one
                   12228:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12229:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   12230:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   12231:       } else {
                   12232:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   12233:       }
                   12234:    }
                   12235: // Remember the old state
                   12236:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   12237: }
1.597     wenzelju 12238: ENDUPFORM
                   12239:     $result.= <<ENDUPFORM;
1.400     www      12240: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   12241: <input type="hidden" name="symb" value="$symb" />
                   12242: <input type="hidden" name="command" value="processclickerfile" />
                   12243: <input type="file" name="upfile" size="50" />
                   12244: <br /><label>$type: $selectform</label>
1.632     www      12245: ENDUPFORM
                   12246:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   12247:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   12248:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   12249: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   12250: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      12251: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   12252: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      12253: <br />&nbsp;&nbsp;&nbsp;
                   12254: <input type="text" name="givenanswer" size="50" />
1.413     www      12255: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      12256: ENDGRADINGFORM
1.766     raeburn  12257:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      12258:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   12259:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   12260: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   12261: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  12262: </form>
1.632     www      12263: ENDPERCFORM
                   12264:     $result.='</td>'.
                   12265:              &Apache::loncommon::end_data_table_row().
                   12266:              &Apache::loncommon::end_data_table();
1.400     www      12267:     return $result;
                   12268: }
                   12269: 
                   12270: sub process_clicker_file {
1.766     raeburn  12271:     my ($r,$symb) = @_;
1.400     www      12272:     if (!$symb) {return '';}
1.413     www      12273: 
                   12274:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12275:     &Apache::loncommon::store_course_settings('grades_clicker',
                   12276:                                               \%Saveable_Parameters);
1.598     www      12277:     my $result='';
1.404     www      12278:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 12279: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      12280: 	return $result;
1.404     www      12281:     }
1.522     www      12282:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      12283:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      12284:         return $result;
1.521     www      12285:     }
1.522     www      12286:     my $foundgiven=0;
1.521     www      12287:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12288:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   12289:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      12290:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      12291:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      12292:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   12293:         $foundgiven=$#answers+1;
1.521     www      12294:     }
1.407     albertel 12295:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 12296:     my %correct_ids;
1.404     www      12297:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 12298: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      12299:     }
                   12300:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      12301: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   12302: 	   $correct_id=~tr/a-z/A-Z/;
                   12303: 	   $correct_id=~s/\s//gs;
                   12304: 	   $correct_id=~s/^[\#0]+//;
1.421     www      12305:            $correct_id=~s/[\-\:]//g;
1.414     www      12306:            if ($correct_id) {
                   12307: 	      $correct_ids{$correct_id}='specified';
                   12308:            }
                   12309:         }
1.400     www      12310:     }
1.404     www      12311:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 12312: 	$result.=&mt('Score based on attendance only');
1.521     www      12313:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      12314:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      12315:     } else {
1.408     albertel 12316: 	my $number=0;
1.411     www      12317: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 12318: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      12319: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 12320: 	    if ($correct_ids{$id} eq 'specified') {
                   12321: 		$result.=&mt('specified');
                   12322: 	    } else {
                   12323: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   12324: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   12325: 	    }
                   12326: 	    $number++;
                   12327: 	}
1.411     www      12328:         $result.="</p>\n";
1.710     bisitz   12329:         if ($number==0) {
                   12330:             $result .=
                   12331:                  &Apache::lonhtmlcommon::confirm_success(
                   12332:                      &mt('No IDs found to determine correct answer'),1);
                   12333:             return $result;
                   12334:         }
1.404     www      12335:     }
1.405     www      12336:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   12337:         $result .=
                   12338:             &Apache::lonhtmlcommon::confirm_success(
                   12339:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   12340:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      12341:         return $result;
1.405     www      12342:     }
1.760     raeburn  12343:     my $mimetype;
                   12344:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   12345:         my $mm = new File::MMagic;
                   12346:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   12347:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   12348:             $result.= '<p>'.
                   12349:                 &Apache::lonhtmlcommon::confirm_success(
                   12350:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   12351:             return $result;
                   12352:         }
                   12353:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   12354:         $result .= '<p>'.
                   12355:             &Apache::lonhtmlcommon::confirm_success(
                   12356:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   12357:         return $result;
                   12358:     }
1.410     www      12359: 
                   12360: # Were able to get all the info needed, now analyze the file
                   12361: 
1.411     www      12362:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 12363:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      12364:     $result.=&Apache::loncommon::start_data_table().
                   12365:              &Apache::loncommon::start_data_table_header_row().
                   12366:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   12367:              &Apache::loncommon::end_data_table_header_row().
                   12368:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   12369: <td>
1.410     www      12370: <form method="post" action="/adm/grades" name="clickeranalysis">
                   12371: <input type="hidden" name="symb" value="$symb" />
                   12372: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      12373: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   12374: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   12375: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      12376: ENDHEADER
1.522     www      12377:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12378:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   12379:     } 
1.408     albertel 12380:     my %responses;
                   12381:     my @questiontitles;
1.405     www      12382:     my $errormsg='';
                   12383:     my $number=0;
                   12384:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  12385:         if ($mimetype eq 'text/plain') {
                   12386:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   12387:         } elsif ($mimetype eq 'text/html') {
                   12388:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   12389:         }
                   12390:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      12391:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  12392:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      12393:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   12394:     }
1.411     www      12395:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   12396:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   12397:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   12398:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   12399:              '<br />';
1.522     www      12400:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   12401:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      12402:        return $result;
1.522     www      12403:     } 
1.414     www      12404: # Remember Question Titles
                   12405: # FIXME: Possibly need delimiter other than ":"
                   12406:     for (my $i=0;$i<$number;$i++) {
                   12407:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   12408:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   12409:     }
1.411     www      12410:     my $correct_count=0;
                   12411:     my $student_count=0;
                   12412:     my $unknown_count=0;
1.414     www      12413: # Match answers with usernames
                   12414: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 12415:     foreach my $id (keys(%responses)) {
1.410     www      12416:        if ($correct_ids{$id}) {
1.414     www      12417:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      12418:           $correct_count++;
1.410     www      12419:        } elsif ($clicker_ids{$id}) {
1.437     www      12420:           if ($clicker_ids{$id}=~/\,/) {
                   12421: # More than one user with the same clicker!
1.632     www      12422:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12423:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12424:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      12425:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12426:                            "<select name='multi".$id."'>";
                   12427:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   12428:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   12429:              }
                   12430:              $result.='</select>';
                   12431:              $unknown_count++;
                   12432:           } else {
                   12433: # Good: found one and only one user with the right clicker
                   12434:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   12435:              $student_count++;
                   12436:           }
1.410     www      12437:        } else {
1.632     www      12438:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12439:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12440:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      12441:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12442:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   12443:                    "\n".&mt("Domain").": ".
                   12444:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  12445:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      12446:           $unknown_count++;
1.410     www      12447:        }
1.405     www      12448:     }
1.412     www      12449:     $result.='<hr />'.
                   12450:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      12451:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      12452:        if ($correct_count==0) {
1.696     bisitz   12453:           $errormsg.="Found no correct answers for grading!";
1.412     www      12454:        } elsif ($correct_count>1) {
1.414     www      12455:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      12456:        }
                   12457:     }
1.428     www      12458:     if ($number<1) {
                   12459:        $errormsg.="Found no questions.";
                   12460:     }
1.412     www      12461:     if ($errormsg) {
                   12462:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   12463:     } else {
                   12464:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   12465:     }
1.632     www      12466:     $result.='</form></td>'.
                   12467:              &Apache::loncommon::end_data_table_row().
                   12468:              &Apache::loncommon::end_data_table();
1.614     www      12469:     return $result;
1.400     www      12470: }
                   12471: 
1.405     www      12472: sub iclicker_eval {
1.406     www      12473:     my ($questiontitles,$responses)=@_;
1.405     www      12474:     my $number=0;
                   12475:     my $errormsg='';
                   12476:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      12477:         my %components=&Apache::loncommon::record_sep($line);
                   12478:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 12479: 	if ($entries[0] eq 'Question') {
                   12480: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   12481: 		$$questiontitles[$number]=$entries[$i];
                   12482: 		$number++;
                   12483: 	    }
                   12484: 	}
                   12485: 	if ($entries[0]=~/^\#/) {
                   12486: 	    my $id=$entries[0];
                   12487: 	    my @idresponses;
                   12488: 	    $id=~s/^[\#0]+//;
                   12489: 	    for (my $i=0;$i<$number;$i++) {
                   12490: 		my $idx=3+$i*6;
1.644     www      12491:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 12492: 		push(@idresponses,$entries[$idx]);
                   12493: 	    }
                   12494: 	    $$responses{$id}=join(',',@idresponses);
                   12495: 	}
1.405     www      12496:     }
                   12497:     return ($errormsg,$number);
                   12498: }
                   12499: 
1.760     raeburn  12500: sub iclickerxml_eval {
                   12501:     my ($questiontitles,$responses)=@_;
                   12502:     my $number=0;
                   12503:     my $errormsg='';
                   12504:     my @state;
                   12505:     my %respbyid;
                   12506:     my $p = HTML::Parser->new
                   12507:     (
                   12508:         xml_mode => 1,
                   12509:         start_h =>
                   12510:             [sub {
                   12511:                  my ($tagname,$attr) = @_;
                   12512:                  push(@state,$tagname);
                   12513:                  if ("@state" eq "ssn p") {
                   12514:                      my $title = $attr->{qn};
                   12515:                      $title =~ s/(^\s+|\s+$)//g;
                   12516:                      $questiontitles->[$number]=$title;
                   12517:                  } elsif ("@state" eq "ssn p v") {
                   12518:                      my $id = $attr->{id};
                   12519:                      my $entry = $attr->{ans};
                   12520:                      $id=~s/^[\#0]+//;
                   12521:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   12522:                      $respbyid{$id}[$number] = $entry;
                   12523:                  }
                   12524:             }, "tagname, attr"],
                   12525:          end_h =>
                   12526:                [sub {
                   12527:                    my ($tagname) = @_;
                   12528:                    if ("@state" eq "ssn p") {
                   12529:                        $number++;
                   12530:                    }
                   12531:                    pop(@state);
                   12532:                 }, "tagname"],
                   12533:     );
                   12534: 
                   12535:     $p->parse($env{'form.upfile'});
                   12536:     $p->eof;
                   12537:     foreach my $id (keys(%respbyid)) {
                   12538:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   12539:     }
                   12540:     return ($errormsg,$number);
                   12541: }
                   12542: 
1.419     www      12543: sub interwrite_eval {
                   12544:     my ($questiontitles,$responses)=@_;
                   12545:     my $number=0;
                   12546:     my $errormsg='';
1.420     www      12547:     my $skipline=1;
                   12548:     my $questionnumber=0;
                   12549:     my %idresponses=();
1.419     www      12550:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12551:         my %components=&Apache::loncommon::record_sep($line);
                   12552:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      12553:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   12554:         if ($entries[1] eq 'Response') { $skipline=1; }
                   12555:         next if $skipline;
                   12556:         if ($entries[0]!=$questionnumber) {
                   12557:            $questionnumber=$entries[0];
                   12558:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   12559:            $number++;
1.419     www      12560:         }
1.420     www      12561:         my $id=$entries[4];
                   12562:         $id=~s/^[\#0]+//;
1.421     www      12563:         $id=~s/^v\d*\://i;
                   12564:         $id=~s/[\-\:]//g;
1.420     www      12565:         $idresponses{$id}[$number]=$entries[6];
                   12566:     }
1.524     raeburn  12567:     foreach my $id (keys(%idresponses)) {
1.420     www      12568:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   12569:        $$responses{$id}=~s/^\s*\,//;
1.419     www      12570:     }
                   12571:     return ($errormsg,$number);
                   12572: }
                   12573: 
1.666     www      12574: sub turning_eval {
                   12575:     my ($questiontitles,$responses)=@_;
                   12576:     my $number=0;
                   12577:     my $errormsg='';
                   12578:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12579:         my %components=&Apache::loncommon::record_sep($line);
                   12580:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   12581:         if ($#entries>$number) { $number=$#entries; }
                   12582:         my $id=$entries[0];
                   12583:         my @idresponses;
                   12584:         $id=~s/^[\#0]+//;
                   12585:         unless ($id) { next; }
                   12586:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   12587:             $entries[$idx]=~s/\,/\;/g;
                   12588:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   12589:             push(@idresponses,$entries[$idx]);
                   12590:         }
                   12591:         $$responses{$id}=join(',',@idresponses);
                   12592:     }
                   12593:     for (my $i=1; $i<=$number; $i++) {
                   12594:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   12595:     }
                   12596:     return ($errormsg,$number);
                   12597: }
                   12598: 
                   12599: 
1.414     www      12600: sub assign_clicker_grades {
1.766     raeburn  12601:     my ($r,$symb) = @_;
1.414     www      12602:     if (!$symb) {return '';}
1.416     www      12603: # See which part we are saving to
1.582     raeburn  12604:     my $res_error;
                   12605:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   12606:     if ($res_error) {
                   12607:         return &navmap_errormsg();
                   12608:     }
1.804     raeburn  12609:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12610:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12611:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   12612:     my (%skip_passback,%pbsave); 
1.416     www      12613: # FIXME: This should probably look for the first handgradeable part
                   12614:     my $part=$$partlist[0];
                   12615: # Start screen output
1.766     raeburn  12616:     my $result = &Apache::loncommon::start_data_table().
                   12617:                  &Apache::loncommon::start_data_table_header_row().
                   12618:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   12619:                  &Apache::loncommon::end_data_table_header_row().
                   12620:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      12621: # Get correct result
                   12622: # FIXME: Possibly need delimiter other than ":"
                   12623:     my @correct=();
1.415     www      12624:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   12625:     my $number=$env{'form.number'};
                   12626:     if ($gradingmechanism ne 'attendance') {
1.414     www      12627:        foreach my $key (keys(%env)) {
                   12628:           if ($key=~/^form\.correct\:/) {
                   12629:              my @input=split(/\,/,$env{$key});
                   12630:              for (my $i=0;$i<=$#input;$i++) {
                   12631:                  if (($correct[$i]) && ($input[$i]) &&
                   12632:                      ($correct[$i] ne $input[$i])) {
                   12633:                     $result.='<br /><span class="LC_warning">'.
                   12634:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   12635:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      12636:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      12637:                     $correct[$i]=$input[$i];
                   12638:                  }
                   12639:              }
                   12640:           }
                   12641:        }
1.415     www      12642:        for (my $i=0;$i<$number;$i++) {
1.644     www      12643:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      12644:              $result.='<br /><span class="LC_error">'.
                   12645:                       &mt('No correct result given for question "[_1]"!',
                   12646:                           $env{'form.question:'.$i}).'</span>';
                   12647:           }
                   12648:        }
1.644     www      12649:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      12650:     }
                   12651: # Start grading
1.415     www      12652:     my $pcorrect=$env{'form.pcorrect'};
                   12653:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      12654:     my $storecount=0;
1.632     www      12655:     my %users=();
1.415     www      12656:     foreach my $key (keys(%env)) {
1.420     www      12657:        my $user='';
1.415     www      12658:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      12659:           $user=$1;
                   12660:        }
                   12661:        if ($key=~/^form\.unknown\:(.*)$/) {
                   12662:           my $id=$1;
                   12663:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   12664:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      12665:           } elsif ($env{'form.multi'.$id}) {
                   12666:              $user=$env{'form.multi'.$id};
1.420     www      12667:           }
                   12668:        }
1.632     www      12669:        if ($user) {
                   12670:           if ($users{$user}) {
                   12671:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   12672:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      12673:                       '</span><br />';
                   12674:           }
                   12675:           $users{$user}=1; 
1.415     www      12676:           my @answer=split(/\,/,$env{$key});
                   12677:           my $sum=0;
1.522     www      12678:           my $realnumber=$number;
1.415     www      12679:           for (my $i=0;$i<$number;$i++) {
1.576     www      12680:              if  ($correct[$i] eq '-') {
                   12681:                 $realnumber--;
1.766     raeburn  12682:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      12683:                 if ($gradingmechanism eq 'attendance') {
                   12684:                    $sum+=$pcorrect;
1.576     www      12685:                 } elsif ($correct[$i] eq '*') {
1.522     www      12686:                    $sum+=$pcorrect;
1.415     www      12687:                 } else {
1.644     www      12688: # We actually grade if correct or not
                   12689:                    my $increment=$pincorrect;
                   12690: # Special case: numerical answer "0"
                   12691:                    if ($correct[$i] eq '0') {
                   12692:                       if ($answer[$i]=~/^[0\.]+$/) {
                   12693:                          $increment=$pcorrect;
                   12694:                       }
                   12695: # General numerical answer, both evaluate to something non-zero
                   12696:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   12697:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   12698:                          $increment=$pcorrect;
                   12699:                       }
                   12700: # Must be just alphanumeric
                   12701:                    } elsif ($answer[$i] eq $correct[$i]) {
                   12702:                       $increment=$pcorrect;
1.415     www      12703:                    }
1.644     www      12704:                    $sum+=$increment;
1.415     www      12705:                 }
                   12706:              }
                   12707:           }
1.522     www      12708:           my $ave=$sum/(100*$realnumber);
1.416     www      12709: # Store
                   12710:           my ($username,$domain)=split(/\:/,$user);
                   12711:           my %grades=();
                   12712:           $grades{"resource.$part.solved"}='correct_by_override';
                   12713:           $grades{"resource.$part.awarded"}=$ave;
                   12714:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   12715:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   12716:                                                  $env{'request.course.id'},
                   12717:                                                  $domain,$username);
                   12718:           if ($returncode ne 'ok') {
                   12719:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   12720:           } else {
                   12721:              $storecount++;
1.804     raeburn  12722:              if (keys(%needpb)) {
                   12723:                  my (%weights,%awardeds,%excuseds);
                   12724:                  my $usec = &Apache::lonnet::getsection($domain,$username,$env{'request.course.id'});
                   12725:                  $weights{$symb}{$part} = &Apache::lonnet::EXT("resource.$part.weight",$symb,$domain,$username,$usec);
                   12726:                  $awardeds{$symb}{$part} = $ave;
                   12727:                  $excuseds{$symb}{$part} = '';
                   12728:                  &process_passbacks('clickergrade',[$symb],$cdom,$cnum,$domain,$username,$usec,\%weights,
                   12729:                                     \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   12730:              }
1.416     www      12731:           }
1.415     www      12732:        }
                   12733:     }
                   12734: # We are done
1.549     hauer    12735:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      12736:              '</td>'.
                   12737:              &Apache::loncommon::end_data_table_row().
                   12738:              &Apache::loncommon::end_data_table();
1.614     www      12739:     return $result;
1.414     www      12740: }
                   12741: 
1.582     raeburn  12742: sub navmap_errormsg {
                   12743:     return '<div class="LC_error">'.
                   12744:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  12745:            &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  12746:            '</div>';
                   12747: }
1.607     droeschl 12748: 
1.609     www      12749: sub startpage {
1.777     raeburn  12750:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  12751:     my %args;
                   12752:     if ($onload) {
                   12753:          my %loaditems = (
                   12754:                         'onload' => $onload,
                   12755:                       );
                   12756:          $args{'add_entries'} = \%loaditems;
                   12757:     }
1.671     raeburn  12758:     if ($nomenu) {
1.754     raeburn  12759:         $args{'only_body'} = 1; 
1.777     raeburn  12760:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  12761:     } else {
1.785     raeburn  12762:         if ($env{'request.course.id'}) { 
                   12763:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   12764:         }
1.754     raeburn  12765:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  12766:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  12767:         if ($env{'request.course.id'}) {
                   12768:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   12769:         }
1.671     raeburn  12770:     }
1.613     www      12771:     unless ($nodisplayflag) {
1.773     raeburn  12772:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      12773:     }
1.607     droeschl 12774: }
1.582     raeburn  12775: 
1.622     www      12776: sub select_problem {
                   12777:     my ($r)=@_;
1.632     www      12778:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  12779:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      12780:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   12781:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   12782: }
                   12783: 
1.793     raeburn  12784: #----- display problem, answer, and submissions for a single student (no grading)
                   12785: 
                   12786: sub view_as_user {
                   12787:     my ($symb,$vuname,$vudom,$hasperm) = @_;
                   12788:     my $plainname = &Apache::loncommon::plainname($vuname,$vudom,'lastname');
                   12789:     my $displayname = &nameUserString('',$plainname,$vuname,$vudom);
                   12790:     my $output = &Apache::loncommon::get_student_view($symb,$vuname,$vudom,
                   12791:                                                       $env{'request.course.id'},
                   12792:                                                       undef,{'disable_submit' => 1}).
                   12793:                  "\n\n".
                   12794:                  '<div class="LC_grade_show_user">'.
                   12795:                  '<h2>'.$displayname.'</h2>'.
                   12796:                  "\n".
                   12797:                  &Apache::loncommon::track_student_link('View recent activity',
                   12798:                                                         $vuname,$vudom,'check').' '.
                   12799:                  "\n";
                   12800:     if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) ||
                   12801:         (($env{'request.course.sec'} ne '') &&
                   12802:          &Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
                   12803:         $output .= &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   12804:                                                $vuname,$vudom,$symb,'check');
                   12805:     }
                   12806:     $output .= "\n";
                   12807:     my $companswer = &Apache::loncommon::get_student_answers($symb,$vuname,$vudom,
                   12808:                                                              $env{'request.course.id'});
                   12809:     $companswer=~s|<form(.*?)>||g;
                   12810:     $companswer=~s|</form>||g;
                   12811:     $companswer=~s|name="submit"|name="would_have_been_submit"|g;
                   12812:     $output .= '<div class="LC_Box">'.
                   12813:                '<h3 class="LC_hcell">'.&mt('Correct answer for[_1]',$displayname).'</h3>'.
                   12814:                $companswer.
                   12815:                '</div>'."\n";
                   12816:     my $is_tool = ($symb =~ /ext\.tool$/);
                   12817:     my ($essayurl,%coursedesc_by_cid);
                   12818:     (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   12819:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$vudom,$vuname);
                   12820:     my $res_error;
                   12821:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   12822:         &response_type($symb,\$res_error);
                   12823:     my $fullname;
                   12824:     my $collabinfo;
                   12825:     if ($numessay) {
                   12826:         unless ($hasperm) {
                   12827:             &init_perm();
                   12828:         }
                   12829:         ($collabinfo,$fullname)=
                   12830:             &check_collaborators($symb,$vuname,$vudom,\%record,$handgrade,0);
                   12831:         unless ($hasperm) {
                   12832:             &reset_perm();
                   12833:         }
                   12834:     }
                   12835:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   12836:                     '" src="'.$Apache::lonnet::perlvar{'lonIconsURL'}.
                   12837:                     '/check.gif" height="16" border="0" />';
                   12838:     my ($lastsubonly,$partinfo) =
                   12839:         &show_last_submission($vuname,$vudom,$symb,$essayurl,$responseType,'datesub',
                   12840:                               '',$fullname,\%record,\%coursedesc_by_cid);
                   12841:     $output .= '<div class="LC_Box">'.
                   12842:                '<h3 class="LC_hcell">'.&mt('Submissions').'</h3>'."\n".$collabinfo."\n";
                   12843:     if (($numresp > $numessay) & !$is_tool) {
                   12844:         $output .='<p class="LC_info">'.
                   12845:                   &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon).
                   12846:                   "</p>\n";
                   12847:     }
                   12848:     $output .= $partinfo;
                   12849:     $output .= $lastsubonly;
                   12850:     $output .= &displaySubByDates($symb,\%record,$partlist,$responseType,$checkIcon,$vuname,$vudom);
                   12851:     $output .= '</div></div>'."\n";
                   12852:     return $output;
                   12853: }
                   12854: 
1.1       albertel 12855: sub handler {
1.41      ng       12856:     my $request=$_[0];
1.434     albertel 12857:     &reset_caches();
1.646     raeburn  12858:     if ($request->header_only) {
                   12859:         &Apache::loncommon::content_type($request,'text/html');
                   12860:         $request->send_http_header;
                   12861:         return OK;
                   12862:     }
                   12863:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   12864: 
1.664     raeburn  12865: # see what command we need to execute
                   12866: 
                   12867:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   12868:     my $command=$commands[0];
                   12869: 
1.646     raeburn  12870:     &init_perm();
                   12871:     if (!$env{'request.course.id'}) {
1.664     raeburn  12872:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   12873:                 ($command =~ /^scantronupload/)) {
                   12874:             # Not in a course.
                   12875:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   12876:             return HTTP_NOT_ACCEPTABLE;
                   12877:         }
1.646     raeburn  12878:     } elsif (!%perm) {
                   12879:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  12880:         return OK;
1.41      ng       12881:     }
1.646     raeburn  12882:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       12883:     $request->send_http_header;
1.646     raeburn  12884: 
1.160     albertel 12885:     if ($#commands > 0) {
                   12886: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   12887:     }
1.608     www      12888: 
1.801     raeburn  12889: # -------------------------------------- Flag and buffer for registered cleanup
                   12890:     $registered_cleanup=0;
                   12891:     undef(@Apache::grades::ltipassback);
                   12892: 
1.608     www      12893: # see what the symb is
                   12894: 
                   12895:     my $symb=$env{'form.symb'};
                   12896:     unless ($symb) {
                   12897:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   12898:        $symb=&Apache::lonnet::symbread($url);
                   12899:     }
1.646     raeburn  12900:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      12901: 
1.513     foxr     12902:     $ssi_error = 0;
1.637     www      12903:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      12904: #
1.637     www      12905: # Not called from a resource, but inside a course
1.601     www      12906: #    
1.622     www      12907:         &startpage($request,undef,[],1,1);
                   12908:         &select_problem($request);
1.41      ng       12909:     } else {
1.104     albertel 12910: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  12911:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  12912:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   12913:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12914:                     &choose_task_version_form($symb,$env{'form.student'},
                   12915:                                               $env{'form.userdom'});
                   12916:             }
1.773     raeburn  12917:             my $divforres;
                   12918:             if ($env{'form.student'} eq '') {
                   12919:                 $js .= &part_selector_js();
                   12920:                 $onload = "toggleParts('gradesub');";
                   12921:             } else {
                   12922:                 $divforres = 1;
                   12923:             }
1.778     raeburn  12924:             my $head_extra = $js;
                   12925:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12926:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12927:                 if ($csslinks) {
                   12928:                     $head_extra .= "\n$csslinks";
                   12929:                 }
                   12930:             }
1.777     raeburn  12931:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   12932:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  12933:             if ($versionform) {
1.775     raeburn  12934:                 if ($divforres) {
                   12935:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   12936:                 }
1.671     raeburn  12937:                 $request->print($versionform);
                   12938:             }
1.773     raeburn  12939: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  12940:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   12941:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12942:                 &choose_task_version_form($symb,$env{'form.student'},
                   12943:                                           $env{'form.userdom'},
                   12944:                                           $env{'form.inhibitmenu'});
1.778     raeburn  12945:             my $head_extra = $js;
                   12946:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12947:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12948:                 if ($csslinks) {
                   12949:                     $head_extra .= "\n$csslinks";
                   12950:                 }
                   12951:             }
1.777     raeburn  12952:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   12953:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  12954:             if ($versionform) {
                   12955:                 $request->print($versionform);
                   12956:             }
                   12957:             $request->print('<br clear="all" />');
                   12958:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 12959: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      12960:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12961:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      12962: 	    &pickStudentPage($request,$symb);
1.103     albertel 12963: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  12964:             my $csslinks;
                   12965:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12966:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  12967:             }
1.615     www      12968:             &startpage($request,$symb,
                   12969:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12970:                                        {href=>'',text=>'Select student'},
1.777     raeburn  12971:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      12972: 	    &displayPage($request,$symb);
1.104     albertel 12973: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      12974:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12975:                                        {href=>'',text=>'Select student'},
                   12976:                                        {href=>'',text=>'Grade student'},
                   12977:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      12978: 	    &updateGradeByPage($request,$symb);
1.104     albertel 12979: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  12980:             my $csslinks;
                   12981:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12982:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12983:             }
1.619     www      12984:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  12985:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      12986: 	    &processGroup($request,$symb);
1.104     albertel 12987: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      12988:             &startpage($request,$symb);
                   12989: 	    $request->print(&grading_menu($request,$symb));
1.598     www      12990: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      12991:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      12992: 	    $request->print(&submit_options($request,$symb));
1.598     www      12993:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  12994:             my $js = &part_selector_js();
                   12995:             my $onload = "toggleParts('gradesub');";
                   12996:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   12997:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      12998:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      12999:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      13000:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      13001:             $request->print(&submit_options_table($request,$symb));
1.598     www      13002:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      13003:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      13004:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 13005: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      13006:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      13007: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 13008: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      13009:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   13010:                                        {href=>'',text=>'Store grades'}]);
1.608     www      13011: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 13012: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      13013:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   13014:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   13015:                                                                              text=>"Modify grades"},
                   13016:                                        {href=>'', text=>"Store grades"}]);
1.608     www      13017: 	    $request->print(&editgrades($request,$symb));
1.602     www      13018:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      13019:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      13020:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 13021: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      13022:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   13023:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      13024: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      13025:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      13026:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      13027:             $request->print(&process_clicker($request,$symb));
1.400     www      13028:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      13029:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   13030:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      13031:             $request->print(&process_clicker_file($request,$symb));
1.414     www      13032:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      13033:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   13034:                                        {href=>'', text=>'Process clicker file'},
                   13035:                                        {href=>'', text=>'Store grades'}]);
1.608     www      13036:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 13037: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      13038:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13039: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 13040: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      13041:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13042: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 13043: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      13044:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13045: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 13046: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 13047: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      13048:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13049: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       13050: 	    } else {
1.257     albertel 13051: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   13052: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       13053: 		} else {
1.257     albertel 13054: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       13055: 		}
1.627     www      13056:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13057: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       13058: 	    }
1.246     albertel 13059: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      13060:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13061: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 13062: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  13063:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   13064:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      13065: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 13066:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      13067:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13068:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 13069: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      13070:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13071: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 13072: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      13073:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13074: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 13075:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  13076:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  13077:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   13078:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      13079:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 13080:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  13081:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      13082:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13083:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  13084:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      13085:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13086:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  13087:         } elsif ($command eq 'scantronupload_delete' &&
                   13088:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   13089:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   13090:             &scantron_upload_delete($request,$symb);
1.523     raeburn  13091:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      13092:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      13093:             $request->print(&checkscantron_results($request,$symb));
                   13094:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  13095:             my $js = &part_selector_js();
                   13096:             my $onload = "toggleParts('gradingMenu');";
                   13097:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   13098:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      13099:             $request->print(&submit_options_download($request,$symb));
                   13100:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   13101:             &startpage($request,$symb,
                   13102:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  13103:     {href=>'', text=>'Download submitted files'}],
                   13104:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  13105:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      13106:             &submit_download_link($request,$symb);
1.796     raeburn  13107:         } elsif ($command eq 'initialpassback') {
                   13108:             &startpage($request,$symb,[{href=>'', text=>'Choose Launcher'}],undef,1);
                   13109:             $request->print(&initialpassback($request,$symb));
                   13110:         } elsif ($command eq 'passback') {
                   13111:             &startpage($request,$symb,
                   13112:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13113:                         {href=>'', text=>'Types of User'}],undef,1);
                   13114:             $request->print(&passback_filters($request,$symb));
                   13115:         } elsif ($command eq 'passbacknames') {
                   13116:             my $chosen;
                   13117:             if ($env{'form.passback'} ne '') {
                   13118:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13119:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13120:                 }
                   13121:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13122:             }
                   13123:             &startpage($request,$symb,
                   13124:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13125:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13126:                         {href=>'', text=>'Select Users'}],undef,1);
                   13127:             $request->print(&names_for_passback($request,$symb));
                   13128:         } elsif ($command eq 'passbackscores') {
                   13129:             my ($chosen,$stu_status);
                   13130:             if ($env{'form.passback'} ne '') {
                   13131:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13132:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13133:                 }
                   13134:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13135:             }
                   13136:             if ($env{'form.Status'}) {
                   13137:                 $stu_status = &HTML::Entities::encode($env{'form.Status'});
                   13138:             }
                   13139:             &startpage($request,$symb,
                   13140:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13141:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13142:                         {href=>&href_symb_cmd($symb,'passbacknames').'&amp;Status='.$stu_status.'&amp;passback='.$chosen, text=>'Select Users'},
                   13143:                         {href=>'', text=>'Execute Passback'}],undef,1);
                   13144:             $request->print(&do_passback($request,$symb));
1.106     albertel 13145: 	} elsif ($command) {
1.620     www      13146:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   13147: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 13148: 	}
1.2       albertel 13149:     }
1.513     foxr     13150:     if ($ssi_error) {
                   13151: 	&ssi_print_error($request);
                   13152:     }
1.671     raeburn  13153:     if ($env{'form.inhibitmenu'}) {
                   13154:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  13155:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  13156:         &Apache::lonquickgrades::endGradeScreen($request);
                   13157:     }
1.434     albertel 13158:     &reset_caches();
1.646     raeburn  13159:     return OK;
1.44      ng       13160: }
                   13161: 
1.1       albertel 13162: 1;
                   13163: 
1.13      albertel 13164: __END__;
1.531     jms      13165: 
                   13166: 
                   13167: =head1 NAME
                   13168: 
                   13169: Apache::grades
                   13170: 
                   13171: =head1 SYNOPSIS
                   13172: 
                   13173: Handles the viewing of grades.
                   13174: 
                   13175: This is part of the LearningOnline Network with CAPA project
                   13176: described at http://www.lon-capa.org.
                   13177: 
                   13178: =head1 OVERVIEW
                   13179: 
                   13180: Do an ssi with retries:
1.715     bisitz   13181: While I'd love to factor out this with the version in lonprintout,
1.531     jms      13182: 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
                   13183: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   13184: 
                   13185: At least the logic that drives this has been pulled out into loncommon.
                   13186: 
                   13187: 
                   13188: 
                   13189: ssi_with_retries - Does the server side include of a resource.
                   13190:                      if the ssi call returns an error we'll retry it up to
                   13191:                      the number of times requested by the caller.
1.715     bisitz   13192:                      If we still have a problem, no text is appended to the
1.531     jms      13193:                      output and we set some global variables.
                   13194:                      to indicate to the caller an SSI error occurred.  
                   13195:                      All of this is supposed to deal with the issues described
1.715     bisitz   13196:                      in LON-CAPA BZ 5631 see:
1.531     jms      13197:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   13198:                      by informing the user that this happened.
                   13199: 
                   13200: Parameters:
                   13201:   resource   - The resource to include.  This is passed directly, without
                   13202:                interpretation to lonnet::ssi.
                   13203:   form       - The form hash parameters that guide the interpretation of the resource
                   13204:                
                   13205:   retries    - Number of retries allowed before giving up completely.
                   13206: Returns:
                   13207:   On success, returns the rendered resource identified by the resource parameter.
                   13208: Side Effects:
                   13209:   The following global variables can be set:
                   13210:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   13211:                               It is up to the caller to initialize this to false
                   13212:                               if desired.
                   13213:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   13214:                               of the resource that could not be rendered by the ssi
                   13215:                               call.
                   13216:    ssi_error_message   - The error string fetched from the ssi response
                   13217:                               in the event of an error.
                   13218: 
                   13219: 
                   13220: =head1 HANDLER SUBROUTINE
                   13221: 
                   13222: ssi_with_retries()
                   13223: 
                   13224: =head1 SUBROUTINES
                   13225: 
                   13226: =over
                   13227: 
1.671     raeburn  13228: =head1 Routines to display previous version of a Task for a specific student
                   13229: 
                   13230: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   13231: can receive another opportunity. Access to tasks is slot-based. If a slot
                   13232: requires a proctor to check-in the student, a new version of the Task will
                   13233: be created when the student is checked in to the new opportunity.
                   13234: 
                   13235: If a particular student has tried two or more versions of a particular task,
                   13236: the submission screen provides a user with vgr privileges (e.g., a Course
                   13237: Coordinator) the ability to display a previous version worked on by the
                   13238: student.  By default, the current version is displayed. If a previous version
                   13239: has been selected for display, submission data are only shown that pertain
                   13240: to that particular version, and the interface to submit grades is not shown.
                   13241: 
                   13242: =over 4
                   13243: 
                   13244: =item show_previous_task_version()
                   13245: 
                   13246: Displays a specified version of a student's Task, as the student sees it.
                   13247: 
                   13248: Inputs: 2
                   13249:         request - request object
                   13250:         symb    - unique symb for current instance of resource
                   13251: 
                   13252: Output: None.
                   13253: 
                   13254: Side Effects: calls &show_problem() to print version of Task, with
                   13255:               version contained in form item: $env{'form.previousversion'}
                   13256: 
                   13257: =item choose_task_version_form()
                   13258: 
                   13259: Displays a web form used to select which version of a student's view of a
                   13260: Task should be displayed.  Either launches a pop-up window, or replaces
                   13261: content in existing pop-up, or replaces page in main window.
                   13262: 
                   13263: Inputs: 4
                   13264:         symb    - unique symb for current instance of resource
                   13265:         uname   - username of student
                   13266:         udom    - domain of student
                   13267:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13268:                   breadcrumbs etc., are displayed
                   13269: 
                   13270: Output: 4
                   13271:         current   - student's current version
                   13272:         displayed - student's version being displayed
                   13273:         result    - scalar containing HTML for web form used to switch to
                   13274:                     a different version (or a link to close window, if pop-up).
                   13275:         js        - javascript for processing selection in versions web form
                   13276: 
                   13277: Side Effects: None.
                   13278: 
                   13279: =item previous_display_javascript()
                   13280: 
                   13281: Inputs: 2
                   13282:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13283:                   breadcrumbs etc., are displayed.
                   13284:         current - student's current version number.
                   13285: 
                   13286: Output: 1
                   13287:         js      - javascript for processing selection in versions web form.
                   13288: 
                   13289: Side Effects: None.
                   13290: 
                   13291: =back
                   13292: 
                   13293: =head1 Routines to process bubblesheet data.
                   13294: 
                   13295: =over 4
                   13296: 
1.531     jms      13297: =item scantron_get_correction() : 
                   13298: 
                   13299:    Builds the interface screen to interact with the operator to fix a
                   13300:    specific error condition in a specific scanline
                   13301: 
                   13302:  Arguments:
                   13303:     $r           - Apache request object
                   13304:     $i           - number of the current scanline
                   13305:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  13306:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      13307:     $line        - full contents of the current scanline
                   13308:     $error       - error condition, valid values are
                   13309:                    'incorrectCODE', 'duplicateCODE',
                   13310:                    'doublebubble', 'missingbubble',
                   13311:                    'duplicateID', 'incorrectID'
                   13312:     $arg         - extra information needed
                   13313:        For errors:
                   13314:          - duplicateID   - paper number that this studentID was seen before on
                   13315:          - duplicateCODE - array ref of the paper numbers this CODE was
                   13316:                            seen on before
                   13317:          - incorrectCODE - current incorrect CODE 
                   13318:          - doublebubble  - array ref of the bubble lines that have double
                   13319:                            bubble errors
                   13320:          - missingbubble - array ref of the bubble lines that have missing
                   13321:                            bubble errors
                   13322: 
1.788     raeburn  13323:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   13324:    $randompick  - True if exam folder (or a sub-folder) has randompick set
1.691     raeburn  13325:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   13326:                      for current line to question number used for same question
                   13327:                      in "Master Seqence" (as seen by Course Coordinator).
                   13328:    $startline   - Reference to hash where key is question number (0 is first)
                   13329:                   and value is number of first bubble line for current student
                   13330:                   or code-based randompick and/or randomorder.
                   13331: 
                   13332: 
                   13333: 
1.531     jms      13334: =item  scantron_get_maxbubble() : 
                   13335: 
1.582     raeburn  13336:    Arguments:
                   13337:        $nav_error  - Reference to scalar which is a flag to indicate a
                   13338:                       failure to retrieve a navmap object.
                   13339:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   13340:        calling routine should trap the error condition and display the warning
                   13341:        found in &navmap_errormsg().
                   13342: 
1.649     raeburn  13343:        $scantron_config - Reference to bubblesheet format configuration hash.
                   13344: 
1.531     jms      13345:    Returns the maximum number of bubble lines that are expected to
                   13346:    occur. Does this by walking the selected sequence rendering the
                   13347:    resource and then checking &Apache::lonxml::get_problem_counter()
                   13348:    for what the current value of the problem counter is.
                   13349: 
                   13350:    Caches the results to $env{'form.scantron_maxbubble'},
                   13351:    $env{'form.scantron.bubble_lines.n'}, 
                   13352:    $env{'form.scantron.first_bubble_line.n'} and
                   13353:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  13354:    which are the total number of bubble lines, the number of bubble
1.531     jms      13355:    lines for response n and number of the first bubble line for response n,
                   13356:    and a comma separated list of numbers of bubble lines for sub-questions
                   13357:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   13358: 
                   13359: 
                   13360: =item  scantron_validate_missingbubbles() : 
                   13361: 
                   13362:    Validates all scanlines in the selected file to not have any
                   13363:     answers that don't have bubbles that have not been verified
                   13364:     to be bubble free.
                   13365: 
                   13366: =item  scantron_process_students() : 
                   13367: 
1.659     raeburn  13368:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      13369: 
                   13370:    The parsed scanline hash is added to %env 
                   13371: 
                   13372:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   13373:    foreach resource , with the form data of
                   13374: 
                   13375: 	'submitted'     =>'scantron' 
                   13376: 	'grade_target'  =>'grade',
                   13377: 	'grade_username'=> username of student
                   13378: 	'grade_domain'  => domain of student
                   13379: 	'grade_courseid'=> of course
                   13380: 	'grade_symb'    => symb of resource to grade
                   13381: 
                   13382:     This triggers a grading pass. The problem grading code takes care
                   13383:     of converting the bubbled letter information (now in %env) into a
                   13384:     valid submission.
                   13385: 
                   13386: =item  scantron_upload_scantron_data() :
                   13387: 
1.659     raeburn  13388:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      13389: 
                   13390: =item  scantron_upload_scantron_data_save() : 
                   13391: 
                   13392:    Adds a provided bubble information data file to the course if user
1.770     raeburn  13393:    has the correct privileges to do so.
                   13394: 
                   13395: = item scantron_upload_delete() :
                   13396: 
                   13397:    Deletes a previously uploaded bubble information data file, if user
                   13398:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      13399: 
                   13400: =item  valid_file() :
                   13401: 
                   13402:    Validates that the requested bubble data file exists in the course.
                   13403: 
                   13404: =item  scantron_download_scantron_data() : 
                   13405: 
                   13406:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  13407:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      13408:    course.
                   13409: 
                   13410: =item  scantron_validate_ID() : 
                   13411: 
                   13412:    Validates all scanlines in the selected file to not have any
1.556     weissno  13413:    invalid or underspecified student/employee IDs
1.531     jms      13414: 
1.582     raeburn  13415: =item navmap_errormsg() :
                   13416: 
                   13417:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  13418:    Should be called whenever the request to instantiate a navmap object fails.
                   13419: 
                   13420: =back
1.582     raeburn  13421: 
1.531     jms      13422: =back
                   13423: 
                   13424: =cut

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