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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.801   ! raeburn     4: # $Id: grades.pm,v 1.800 2024/12/09 22:01:01 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.315     bowersj2  884: # Given the score (as a number [0-1] and the weight) what is the final
                    885: # point value? This function will round to the nearest tenth, third,
                    886: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  887: sub compute_points {
1.315     bowersj2  888:     my ($score, $weight) = @_;
                    889:     
                    890:     my $tolerance = .00001;
                    891:     my $points = $score * $weight;
                    892: 
                    893:     # Check for nearness to 1/x.
                    894:     my $check_for_nearness = sub {
                    895:         my ($factor) = @_;
                    896:         my $num = ($points * $factor) + $tolerance;
                    897:         my $floored_num = floor($num);
1.316     albertel  898:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  899:             return $floored_num / $factor;
                    900:         }
                    901:         return $points;
                    902:     };
                    903: 
                    904:     $points = $check_for_nearness->(10);
                    905:     $points = $check_for_nearness->(3);
                    906:     $points = $check_for_nearness->(4);
                    907:     
                    908:     return $points;
                    909: }
                    910: 
1.44      ng        911: #------------------ End of general use routines --------------------
1.87      www       912: 
                    913: #
                    914: # Find most similar essay
                    915: #
                    916: 
                    917: sub most_similar {
1.674     raeburn   918:     my ($uname,$udom,$symb,$uessay)=@_;
                    919: 
                    920:     unless ($symb) { return ''; }
                    921: 
                    922:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       923: 
                    924: # ignore spaces and punctuation
                    925: 
                    926:     $uessay=~s/\W+/ /gs;
                    927: 
1.282     www       928: # ignore empty submissions (occuring when only files are sent)
                    929: 
1.598     www       930:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       931: 
1.87      www       932: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       933:     my $limit=0.6;
1.87      www       934:     my $sname='';
                    935:     my $sdom='';
                    936:     my $scrsid='';
                    937:     my $sessay='';
                    938: # go through all essays ...
1.674     raeburn   939:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  940: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       941: # ... except the same student
1.426     albertel  942:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   943: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  944: 	$tessay=~s/\W+/ /gs;
1.87      www       945: # String similarity gives up if not even limit
1.426     albertel  946: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       947: # Found one
1.426     albertel  948: 	if ($tsimilar>$limit) {
                    949: 	    $limit=$tsimilar;
                    950: 	    $sname=$tname;
                    951: 	    $sdom=$tdom;
                    952: 	    $scrsid=$tcrsid;
1.674     raeburn   953: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  954: 	}
1.87      www       955:     }
1.88      www       956:     if ($limit>0.6) {
1.87      www       957:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    958:     } else {
                    959:        return ('','','','',0);
                    960:     }
                    961: }
                    962: 
1.44      ng        963: #-------------------------------------------------------------------
                    964: 
                    965: #------------------------------------ Receipt Verification Routines
1.45      ng        966: #
1.602     www       967: 
                    968: sub initialverifyreceipt {
1.608     www       969:    my ($request,$symb) = @_;
1.602     www       970:    &commonJSfunctions($request);
1.694     bisitz    971:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       972:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    973:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       974:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    975:         '<input type="hidden" name="command" value="verify" />'.
                    976:         "</form>\n";
1.602     www       977: }
                    978: 
1.44      ng        979: #--- Check whether a receipt number is valid.---
                    980: sub verifyreceipt {
1.766     raeburn   981:     my ($request,$symb) = @_;
1.44      ng        982: 
1.257     albertel  983:     my $courseid = $env{'request.course.id'};
1.184     www       984:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  985: 	$env{'form.receipt'};
1.44      ng        986:     $receipt     =~ s/[^\-\d]//g;
                    987: 
1.766     raeburn   988:     my $title =
1.487     albertel  989: 	'<h3><span class="LC_info">'.
1.605     www       990: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    991: 	'</span></h3>'."\n";
1.44      ng        992: 
                    993:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   994:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  995:     
                    996:     my $receiptparts=0;
1.390     albertel  997:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    998: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  999:     my $parts=['0'];
1.582     raeburn  1000:     if ($receiptparts) {
                   1001:         my $res_error; 
                   1002:         ($parts)=&response_type($symb,\$res_error);
                   1003:         if ($res_error) {
                   1004:             return &navmap_errormsg();
                   1005:         } 
                   1006:     }
1.486     albertel 1007:     
                   1008:     my $header = 
                   1009: 	&Apache::loncommon::start_data_table().
                   1010: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel 1011: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                   1012: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                   1013: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel 1014:     if ($receiptparts) {
1.487     albertel 1015: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel 1016:     }
                   1017:     $header.=
                   1018: 	&Apache::loncommon::end_data_table_header_row();
                   1019: 
1.294     albertel 1020:     foreach (sort 
                   1021: 	     {
                   1022: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1023: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1024: 		 }
                   1025: 		 return $a cmp $b;
                   1026: 	     } (keys(%$fullname))) {
1.44      ng       1027: 	my ($uname,$udom)=split(/\:/);
1.177     albertel 1028: 	foreach my $part (@$parts) {
                   1029: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel 1030: 		$contents.=
                   1031: 		    &Apache::loncommon::start_data_table_row().
                   1032: 		    '<td>&nbsp;'."\n".
1.177     albertel 1033: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 1034: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel 1035: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                   1036: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                   1037: 		if ($receiptparts) {
                   1038: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                   1039: 		}
1.486     albertel 1040: 		$contents.= 
                   1041: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel 1042: 		
                   1043: 		$matches++;
                   1044: 	    }
1.44      ng       1045: 	}
                   1046:     }
                   1047:     if ($matches == 0) {
1.584     bisitz   1048:         $string = $title
                   1049:                  .'<p class="LC_warning">'
                   1050:                  .&mt('No match found for the above receipt number.')
                   1051:                  .'</p>';
1.44      ng       1052:     } else {
1.324     albertel 1053: 	$string = &jscriptNform($symb).$title.
1.487     albertel 1054: 	    '<p>'.
1.584     bisitz   1055: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel 1056: 	    '</p>'.
1.486     albertel 1057: 	    $header.
                   1058: 	    $contents.
                   1059: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng       1060:     }
1.614     www      1061:     return $string;
1.44      ng       1062: }
                   1063: 
1.798     raeburn  1064: #-------------------------------------------------------------------
                   1065: 
                   1066: #------------------------------------------- Grade Passback Routines
                   1067: #
                   1068: 
1.796     raeburn  1069: sub initialpassback {
                   1070:     my ($request,$symb) = @_;
                   1071:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1072:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1073:     my $crstype = &Apache::loncommon::course_type();
                   1074:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   1075:     my $readonly;
                   1076:     unless ($perm{'mgr'}) {
                   1077:         $readonly = 1;
                   1078:     }
                   1079:     my $formname = 'initialpassback';
                   1080:     my $navmap = Apache::lonnavmaps::navmap->new();
                   1081:     my $output;
                   1082:     if (!defined($navmap)) {
                   1083:         if ($crstype eq 'Community') {
                   1084:             $output = &mt('Unable to retrieve information about community contents');
                   1085:         } else {
                   1086:             $output = &mt('Unable to retrieve information about course contents');
                   1087:         }
                   1088:         return '<p>'.$output.'</p>';
                   1089:     }
                   1090:     return &Apache::loncourserespicker::create_picker($navmap,'passback',$formname,$crstype,undef,
                   1091:                                                       undef,undef,undef,undef,undef,undef,
                   1092:                                                       \%passback,$readonly);
                   1093: }
                   1094: 
                   1095: sub passback_filters {
                   1096:     my ($request,$symb) = @_;
                   1097:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1098:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1099:     my $crstype = &Apache::loncommon::course_type();
                   1100:     my ($launcher,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
                   1101:     if ($env{'form.passback'} ne '') {
                   1102:         $chosen = &unescape($env{'form.passback'});
                   1103:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1104:         ($launcher,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
                   1105:     }
                   1106:     my $result;
                   1107:     if ($launcher ne '') {
                   1108:         $result = &launcher_info_box($launcher,$appname,$setter,$linkuri,$scope).
                   1109:                   '<p><br />'.&mt('Set criteria to use to list students for possible passback of scores, then push Next [_1]',
                   1110:                                   '&rarr;').
                   1111:                   '</p>';
                   1112:     }
                   1113:     $result .= '<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   1114:                '<input type="hidden" name="passback" value="'.&escape($chosen).'" />'."\n".
                   1115:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   1116:     my ($submittext,$newcommand);
                   1117:     if ($launcher ne '') {
                   1118:         $submittext = &mt('Next').' &rarr;';
                   1119:         $newcommand = 'passbacknames';
                   1120:         $result .=  &selectfield(0)."\n";
                   1121:     } else {
                   1122:         $submittext = '&larr; '.&mt('Previous');
                   1123:         $newcommand = 'initialpassback';
                   1124:         if ($env{'form.passback'}) {
                   1125:             $result .= '<span class="LC_warning">'.&mt('Invalid launcher').'</span>'."\n";
                   1126:         } else {
                   1127:             $result .= '<span class="LC_warning">'.&mt('No launcher selected').'</span>'."\n";
                   1128:         }
                   1129:     }
                   1130:     $result .=  '<input type="hidden" name="command" value="'.$newcommand.'" />'."\n".
                   1131:                 '<div>'."\n".
                   1132:                 '<input type="submit" value="'.$submittext.'" />'."\n".
                   1133:                 '</div>'."\n".
                   1134:                 '</form>'."\n";
                   1135:     return $result;
                   1136: }
                   1137: 
                   1138: sub names_for_passback {
                   1139:     my ($request,$symb) = @_;
                   1140:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1141:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1142:     my $crstype = &Apache::loncommon::course_type();
                   1143:     my ($launcher,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
                   1144:     if ($env{'form.passback'} ne '') {
                   1145:         $chosen = &unescape($env{'form.passback'});
                   1146:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1147:         ($launcher,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
                   1148:     }
                   1149:     my ($result,$ctr,$newcommand,$submittext);
                   1150:     if ($launcher ne '') {
                   1151:         $result = &launcher_info_box($launcher,$appname,$setter,$linkuri,$scope);
                   1152:     }
                   1153:     $ctr = 0;
                   1154:     my @statuses = &Apache::loncommon::get_env_multiple('form.Status');
                   1155:     my $stu_status = join(':',@statuses);
                   1156:     $result .= '<form action="/adm/grades" method="post" name="passbackusers">'."\n".
                   1157:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   1158:     if ($launcher ne '') {
                   1159:         $result .= '<input type="hidden" name="passback" value="'.&escape($chosen).'" />'."\n".
                   1160:                    '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
                   1161:         my ($sections,$groups,$group_display,$disabled) = &sections_and_groups();
                   1162:         my $section_display = join(' ',@{$sections});
                   1163:         my $status_display;
                   1164:         if ((grep(/^Any$/,@statuses)) ||
                   1165:             (@statuses == 3)) {
                   1166:             $status_display = &mt('Any');
                   1167:         } else {
                   1168:             $status_display = join(' '.&mt('or').' ',map { &mt($_); } @statuses);
                   1169:         }
                   1170:         $result .= '<p>'.&mt('Student(s) with stored passback credentials for [_1], and also satisfy:',
                   1171:                              '<span class="LC_cusr_emph">'.$linkuri.'</span>').
                   1172:                    '<ul>'.
                   1173:                    '<li>'.&mt('Section(s)').": $section_display</li>\n".
                   1174:                    '<li>'.&mt('Group(s)').": $group_display</li>\n".
                   1175:                    '<li>'.&mt('Status').": $status_display</li>\n".
                   1176:                    '</ul>';
                   1177:         my ($classlist,undef,$fullname) = &getclasslist($sections,'1',$groups,'','','',$chosen);
                   1178:         if (keys(%$fullname)) {
                   1179:             $newcommand = 'passbackscores';
                   1180:             $result .= &build_section_inputs().
                   1181:                        &checkselect_js('passbackusers').
                   1182:                        '<p><br />'.
                   1183:                        &mt("To send scores, check box(es) next to the student's name(s), then push 'Send Scores'.").
                   1184:                        '</p>'.
                   1185:                        &check_script('passbackusers', 'stuinfo')."\n".
                   1186:                        '<input type="button" '."\n".
                   1187:                        'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1188:                        'value="'.&mt('Send Scores').'" /> <br />'."\n".
                   1189:                        &check_buttons()."\n".
                   1190:                        &Apache::loncommon::start_data_table().
                   1191:                        &Apache::loncommon::start_data_table_header_row();
                   1192:             my $loop = 0;
                   1193:             while ($loop < 2) {
                   1194:                 $result .= '<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1195:                            '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
                   1196:                 $loop++;
                   1197:             }
                   1198:             $result .= &Apache::loncommon::end_data_table_header_row()."\n";
                   1199:             foreach my $student (sort
                   1200:                                  {
                   1201:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1202:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1203:                                      }
                   1204:                                      return $a cmp $b;
                   1205:                                  }
                   1206:                                  (keys(%$fullname))) {
                   1207:                 $ctr++;
                   1208:                 my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                   1209:                 my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
                   1210:                 my $udom = $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                   1211:                 my $uname = $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                   1212:                 if ( $perm{'vgr'} eq 'F' ) {
                   1213:                     if ($ctr%2 ==1) {
                   1214:                         $result.= &Apache::loncommon::start_data_table_row();
                   1215:                     }
                   1216:                     $result .= '<td align="right">'.$ctr.'&nbsp;</td>'.
                   1217:                                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
                   1218:                                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1219:                                ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1220:                                &nameUserString(undef,$$fullname{$student},$uname,$udom).
                   1221:                                '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
                   1222: 
                   1223:                     if ($ctr%2 ==0) {
                   1224:                         $result .= &Apache::loncommon::end_data_table_row()."\n";
                   1225:                     }
                   1226:                 }
                   1227:             }
                   1228:             if ($ctr%2 ==1) {
                   1229:                 $result .= &Apache::loncommon::end_data_table_row();
                   1230:             }
                   1231:             $result .= &Apache::loncommon::end_data_table()."\n";
                   1232:             if ($ctr) {
                   1233:                 $result .= '<input type="button" '.
                   1234:                            'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1235:                            'value="'.&mt('Send Scores').'" />'."\n";
                   1236:             }
                   1237:         } else {
                   1238:             $submittext = '&larr; '.&mt('Previous');
                   1239:             $newcommand = 'passback';
                   1240:             $result .= '<span class="LC_warning">'.&mt('No students match the selection criteria').'</p>';
                   1241:         }
                   1242:     } else {
                   1243:         $newcommand = 'initialpassback';
                   1244:         $submittext = &mt('Start over');
                   1245:         if ($env{'form.passback'}) {
                   1246:             $result .= '<span class="LC_warning">'.&mt('Invalid launcher').'</span>'."\n";
                   1247:         } else {
                   1248:             $result .= '<span class="LC_warning">'.&mt('No launcher selected').'</span>'."\n";
                   1249:         }
                   1250:     }
                   1251:     $result .=  '<input type="hidden" name="command" value="'.$newcommand.'" />'."\n";
                   1252:     if (!$ctr) {
                   1253:         $result .= '<div>'."\n".
                   1254:                    '<input type="submit" value="'.$submittext.'" />'."\n".
                   1255:                    '</div>'."\n";
                   1256:     }
                   1257:     $result .= '</form>'."\n";
                   1258:     return $result;
                   1259: }
                   1260: 
                   1261: sub do_passback {
                   1262:     my ($request,$symb) = @_;
                   1263:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1264:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1265:     my $crstype = &Apache::loncommon::course_type();
                   1266:     my ($launcher,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
                   1267:     if ($env{'form.passback'} ne '') {
                   1268:         $chosen = &unescape($env{'form.passback'});
                   1269:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1270:         ($launcher,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
                   1271:     }
                   1272:     if ($launcher ne '') {
                   1273:         $request->print(&launcher_info_box($launcher,$appname,$setter,$linkuri,$scope));
                   1274:     }
                   1275:     my $error;
                   1276:     if ($perm{'mgr'}) {
                   1277:         if ($launcher ne '') {
                   1278:             my @poss_students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   1279:             if (@poss_students) {
                   1280:                 my %possibles;
                   1281:                 foreach my $item (@poss_students) {
                   1282:                     my ($stuname,$studom) = split(/:/,$item,3);
                   1283:                     $possibles{$stuname.':'.$studom} = 1;
                   1284:                 }
                   1285:                 my ($sections,$groups,$group_display,$disabled) = &sections_and_groups();
                   1286:                 my ($classlist,undef,$fullname,$pbinfo) =
                   1287:                     &getclasslist($sections,'1',$groups,'','','',$chosen,\%possibles);
                   1288:                 if ((ref($classlist) eq 'HASH') && (ref($pbinfo) eq 'HASH')) {
                   1289:                     my %passback = %{$pbinfo};
                   1290:                     my (%tosend,%remotenotok,%scorenotok,%zeroposs,%nopbinfo);
                   1291:                     foreach my $possible (keys(%possibles)) {
                   1292:                         if ((exists($classlist->{$possible})) &&
                   1293:                             (exists($passback{$possible})) && (ref($passback{$possible}) eq 'ARRAY')) {
                   1294:                             $tosend{$possible} = 1;
                   1295:                         }
                   1296:                     }
                   1297:                     if (keys(%tosend)) {
                   1298:                         my ($lti_in_use,$crsdef);
                   1299:                         my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
                   1300:                         if ($ltitype eq 'c') {
                   1301:                             my %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1302:                             $lti_in_use = $crslti{$ltinum};
                   1303:                             $crsdef = 1;
                   1304:                         } else {
                   1305:                             my %domlti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1306:                             $lti_in_use = $domlti{$ltinum};
                   1307:                         }
                   1308:                         if (ref($lti_in_use) eq 'HASH') {
                   1309:                             my $msgformat = $lti_in_use->{'passbackformat'};
                   1310:                             my $keynum = $lti_in_use->{'cipher'};
                   1311:                             my $scoretype = 'decimal';
                   1312:                             if ($lti_in_use->{'scoreformat'} =~ /^(decimal|ratio|percentage)$/) {
                   1313:                                 $scoretype = $1;
                   1314:                             }
                   1315:                             my $pbsymb = &Apache::loncommon::symb_from_tinyurl($linkuri,$cnum,$cdom);
                   1316:                             my $pbmap;
                   1317:                             if ($pbsymb =~ /\.(page|sequence)$/) {
                   1318:                                 $pbmap = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pbsymb))[2]);
                   1319:                             } else {
                   1320:                                 $pbmap = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pbsymb))[0]);
                   1321:                             }
                   1322:                             $pbmap = &Apache::lonnet::clutter($pbmap);
                   1323:                             my $pbscope;
                   1324:                             if ($scope eq 'res') {
                   1325:                                 $pbscope = 'resource';
                   1326:                             } elsif ($scope eq 'map') {
                   1327:                                 $pbscope = 'nonrec';
                   1328:                             } elsif ($scope eq 'rec') {
                   1329:                                 $pbscope = 'map';
                   1330:                             }
1.798     raeburn  1331:                             my %pb = &common_passback_info();
1.796     raeburn  1332:                             my $numstudents = scalar(keys(%tosend));
                   1333:                             my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($request,$numstudents);
                   1334:                             my $outcome = &Apache::loncommon::start_data_table().
                   1335:                                          &Apache::loncommon::start_data_table_header_row();
                   1336:                             my $loop = 0;
                   1337:                             while ($loop < 2) {
                   1338:                                 $outcome .= '<th>'.&mt('No.').'</th>'.
                   1339:                                            '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>'.
                   1340:                                            '<th>'.&mt('Score').'</th>';
                   1341:                                  $loop++;
                   1342:                             }
                   1343:                             $outcome .= &Apache::loncommon::end_data_table_header_row()."\n";
                   1344:                             my $ctr=0;
                   1345:                             foreach my $student (sort
                   1346:                                 {
                   1347:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1348:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1349:                                      }
                   1350:                                      return $a cmp $b;
                   1351:                                 } (keys(%$fullname))) {
                   1352:                                 next unless ($tosend{$student});
                   1353:                                 my ($uname,$udom) = split(/:/,$student);
                   1354:                                 &Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last student');
                   1355:                                 my ($uname,$udom) = split(/:/,$student);
                   1356:                                 my $uhome = &Apache::lonnet::homeserver($uname,$udom),
                   1357:                                 my $id = $passback{$student}[0],
                   1358:                                 my $url = $passback{$student}[1],
                   1359:                                 my ($total,$possible,$usec);
                   1360:                                 if (ref($classlist->{$student}) eq 'ARRAY') {
                   1361:                                     $usec = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION];
                   1362:                                 }
                   1363:                                 if ($pbscope eq 'resource') {
                   1364:                                     $total = 0;
                   1365:                                     $possible = 0;
                   1366:                                     my $navmap = Apache::lonnavmaps::navmap->new($uname,$udom);
                   1367:                                     if (ref($navmap)) {
                   1368:                                         my $res = $navmap->getBySymb($pbsymb);
                   1369:                                         if (ref($res)) {
                   1370:                                             my $partlist = $res->parts();
                   1371:                                             if (ref($partlist) eq 'ARRAY') {
                   1372:                                                 my %record = &Apache::lonnet::restore($pbsymb,$env{'request.course.id'},$udom,$uname);
                   1373:                                                 foreach my $part (@{$partlist}) {
                   1374:                                                     next if ($record{"resource.$part.solved"} =~/^excused/);
                   1375:                                                     my $weight = &Apache::lonnet::EXT("resource.$part.weight",$pbsymb,$udom,$uname,$usec);
                   1376:                                                     $possible += $weight;
                   1377:                                                     if (($record{'version'}) && (exists($record{"resource.$part.awarded"}))) {
                   1378:                                                         my $awarded = $record{"resource.$part.awarded"};
                   1379:                                                         if ($awarded) {
                   1380:                                                             $total += $weight * $awarded;
                   1381:                                                         }
                   1382:                                                     }
                   1383:                                                 }
                   1384:                                             }
                   1385:                                         }
                   1386:                                     }
                   1387:                                 } elsif (($pbscope eq 'map') || ($pbscope eq 'nonrec')) {
                   1388:                                     ($total,$possible) =
                   1389:                                         &Apache::lonhomework::get_lti_score($uname,$udom,$pbmap,$pbscope);
                   1390:                                 }
                   1391:                                 if (($id ne '') && ($url ne '') && ($possible)) {
                   1392:                                     my ($sent,$score,$code,$result) =
1.798     raeburn  1393:                                         &LONCAPA::ltiutils::send_grade($cdom,$cnum,$crsdef,$pb{'type'},$ltinum,$keynum,$id,
                   1394:                                                                        $url,$scoretype,$pb{'sigmethod'},$msgformat,$total,$possible);
1.796     raeburn  1395:                                     my $no_passback;
                   1396:                                     if ($sent) {
                   1397:                                         if ($code == 200) {
                   1398:                                             delete($tosend{$student});
                   1399:                                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
                   1400:                                             my $store = {
                   1401:                                                  'score' => $score,
1.798     raeburn  1402:                                                  'ip' => $pb{'ip'},
                   1403:                                                  'host' => $pb{'lonhost'},
1.796     raeburn  1404:                                                  'protector' => $linkprotector,
                   1405:                                                  'deeplink' => $linkuri,
                   1406:                                                  'scope' => $scope,
                   1407:                                                  'url' => $url,
                   1408:                                                  'id' => $id,
1.798     raeburn  1409:                                                  'clientip' => $pb{'clientip'},
1.796     raeburn  1410:                                                  'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
                   1411:                                                 };
                   1412:                                             my $value='';
                   1413:                                             foreach my $key (keys(%{$store})) {
                   1414:                                                 $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
                   1415:                                             }
                   1416:                                             $value=~s/\&$//;
                   1417:                                             &Apache::lonnet::courselog(&escape($linkuri).':'.$uname.':'.$udom.':EXPORT:'.$value);
1.798     raeburn  1418:                                             &Apache::lonnet::cstore({'score' => $score},$chosen,$namespace,$udom,$uname,'',$pb{'ip'},1);
1.796     raeburn  1419:                                             $ctr++;
                   1420:                                             if ($ctr%2 ==1) {
                   1421:                                                 $outcome .= &Apache::loncommon::start_data_table_row();
                   1422:                                             }
                   1423:                                             my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                   1424:                                             my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
                   1425:                                             $outcome .= '<td align="right">'.$ctr.'&nbsp;</td>'.
                   1426:                                                        '<td>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).
                   1427:                                                        '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'.
                   1428:                                                        '<td>'.$score.'</td>'."\n";
                   1429:                                             if ($ctr%2 ==0) {
                   1430:                                                 $outcome .= &Apache::loncommon::end_data_table_row()."\n";
                   1431:                                             }
                   1432:                                         } else {
                   1433:                                             $remotenotok{$student} = 1;
                   1434:                                             $no_passback = "Passback response for ".$linkprotector." was $code ($result)";
                   1435:                                             &Apache::lonnet::logthis($no_passback." for $uname:$udom in ${cdom}_${cnum}");
                   1436:                                         }
                   1437:                                     } else {
                   1438:                                         $scorenotok{$student} = 1;
                   1439:                                         $no_passback = "Passback of grades not sent for ".$linkprotector;
                   1440:                                         &Apache::lonnet::logthis($no_passback." for $uname:$udom in ${cdom}_${cnum}");
                   1441:                                     }
                   1442:                                     if ($no_passback) {
                   1443:                                         &Apache::lonnet::log($udom,$uname,$uhome,$no_passback." score: $score; total: $total; possible: $possible");
                   1444:                                         my $ltigrade = {
                   1445:                                             'ltinum'   => $ltinum,
                   1446:                                             'lti'      => $lti_in_use,
                   1447:                                             'crsdef'   => $crsdef,
                   1448:                                             'cid'      => $cdom.'_'.$cnum,
                   1449:                                             'uname'    => $uname,
                   1450:                                             'udom'     => $udom,
                   1451:                                             'uhome'    => $uhome,
                   1452:                                             'pbid'     => $id,
                   1453:                                             'pburl'    => $url,
1.798     raeburn  1454:                                             'pbtype'   => $pb{'type'},
1.796     raeburn  1455:                                             'pbscope'  => $pbscope,
                   1456:                                             'pbmap'    => $pbmap,
                   1457:                                             'pbsymb'   => $pbsymb,
                   1458:                                             'format'   => $scoretype,
                   1459:                                             'scope'    => $scope,
1.798     raeburn  1460:                                             'clientip' => $pb{'clientip'},
1.799     raeburn  1461:                                             'linkprot' => $linkprotector.':'.$linkuri,
1.796     raeburn  1462:                                             'total'    => $total,
                   1463:                                             'possible' => $possible,
                   1464:                                             'score'    => $score,
                   1465:                                         };
                   1466:                                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1467:                                     }
                   1468:                                 } else {
                   1469:                                     if (($id ne '') && ($url ne '')) {
                   1470:                                         $zeroposs{$student} = 1;
                   1471:                                     } else {
                   1472:                                         $nopbinfo{$student} = 1;
                   1473:                                     }
                   1474:                                 }
                   1475:                             }
                   1476:                             &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
                   1477:                             if ($ctr%2 ==1) {
                   1478:                                 $outcome .= &Apache::loncommon::end_data_table_row();
                   1479:                             }
                   1480:                             $outcome .= &Apache::loncommon::end_data_table();
                   1481:                             if ($ctr) {
                   1482:                                 $request->print('<p><br />'.&mt('Scores sent to launcher CMS').'</p>'.
                   1483:                                                 '<p>'.$outcome.'</p>');
                   1484:                             } else {
                   1485:                                 $request->print('<p>'.&mt('No scores sent to launcher CMS').'</p>');
                   1486:                             }
                   1487:                             if (keys(%tosend)) {
                   1488:                                 $request->print('<p>'.&mt('No scores sent for following'));
                   1489:                                 my ($zeros,$nopbcreds,$noconfirm,$noscore);
                   1490:                                 foreach my $student (sort
                   1491:                                 {
                   1492:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1493:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1494:                                      }
                   1495:                                      return $a cmp $b;
                   1496:                                 } (keys(%$fullname))) {
                   1497:                                     next unless ($tosend{$student});
                   1498:                                     my ($uname,$udom) = split(/:/,$student);
                   1499:                                     my $line = '<li>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).'</li>'."\n";
                   1500:                                     if ($zeroposs{$student}) {
                   1501:                                         $zeros .= $line;
                   1502:                                     } elsif ($nopbinfo{$student}) {
                   1503:                                         $nopbcreds .= $line;
                   1504:                                     } elsif ($remotenotok{$student}) {
                   1505:                                         $noconfirm .= $line;
                   1506:                                     } elsif ($scorenotok{$student}) {
                   1507:                                         $noscore .= $line;
                   1508:                                     }
                   1509:                                 }
                   1510:                                 if ($zeros) {
                   1511:                                     $request->print('<br />'.&mt('Total points possible was 0').':'.
                   1512:                                                     '<ul>'.$zeros.'</ul><br />');
                   1513:                                 }
                   1514:                                 if ($nopbcreds) {
                   1515:                                     $request->print('<br />'.&mt('Missing unique identifier and/or passback location').':'.
                   1516:                                                     '<ul>'.$nopbcreds.'</ul><br />');
                   1517:                                 }
                   1518:                                 if ($noconfirm) {
                   1519:                                     $request->print('<br />'.&mt('Score receipt not confirmed by receiving CMS').':'.
                   1520:                                                     '<ul>'.$noconfirm.'</ul><br />');
                   1521:                                 }
                   1522:                                 if ($noscore) {
                   1523:                                     $request->print('<br />'.&mt('Score computation or transmission failed').':'.
                   1524:                                                     '<ul>'.$noscore.'</ul><br />');
                   1525:                                 }
                   1526:                                 $request->print('</p>');
                   1527:                             }
                   1528:                         } else {
                   1529:                             $error = &mt('Settings for deep-link launch target unavailable, so no scores were sent');
                   1530:                         }
                   1531:                     } else {
                   1532:                         $error = &mt('No available students for whom scores can be sent.');
                   1533:                     }
                   1534:                 } else {
                   1535:                     $error = &mt('Classlist could not be retrieved so no scores were sent.');
                   1536:                 }
                   1537:             } else {
                   1538:                 $error = &mt('No students selected to receive scores so none were sent.');
                   1539:             }
                   1540:         } else {
                   1541:             if ($env{'form.passback'}) {
                   1542:                 $error = &mt('Deep-link launch target was invalid so no scores were sent.');
                   1543:             } else {
                   1544:                 $error = &mt('Deep-link launch target was missing so no scores were sent.');
                   1545:             }
                   1546:         }
                   1547:     } else {
                   1548:         $error = &mt('You do not have permission to manage grades, so no scores were sent');
                   1549:     }
                   1550:     if ($error) {
                   1551:         $request->print('<p class="LC_info">'.$error.'</p>');
                   1552:     }
                   1553:     return;
                   1554: }
                   1555: 
                   1556: sub get_passback_launcher {
                   1557:     my ($cdom,$cnum,$chosen) = @_;
                   1558:     my ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1559:     my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
                   1560:     my ($appname,$setter);
                   1561:     if ($ltitype eq 'c') {
                   1562:         my %lti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1563:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1564:             $appname = $lti{$ltinum}{'name'};
                   1565:             if ($appname) {
                   1566:                 $setter = ' (defined in course)';
                   1567:             }
                   1568:         }
                   1569:     } elsif ($ltitype eq 'd') {
                   1570:         my %lti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1571:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1572:             $appname = $lti{$ltinum}{'name'};
                   1573:             if ($appname) {
                   1574:                 $setter = ' (defined in domain)';
                   1575:             }
                   1576:         }
                   1577:     }
                   1578:     if ($linkuri =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   1579:         my $key = $1;
                   1580:         my $tinyurl;
                   1581:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   1582:         if (defined($cached)) {
                   1583:             $tinyurl = $result;
                   1584:         } else {
                   1585:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   1586:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   1587:             if ($currtiny{$key} ne '') {
                   1588:                 $tinyurl = $currtiny{$key};
                   1589:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   1590:             }
                   1591:         }
                   1592:         if ($tinyurl) {
                   1593:             my ($crsnum,$launchsymb) = split(/\&/,$tinyurl);
                   1594:             if ($crsnum eq $cnum) {
                   1595:                 my %passback = &Apache::lonnet::get('nohist_linkprot_passback',[$launchsymb],$cdom,$cnum);
                   1596:                 if (ref($passback{$launchsymb}) eq 'HASH') {
                   1597:                     if (exists($passback{$launchsymb}{$chosen})) {
1.798     raeburn  1598:                         return ($launchsymb,$appname,$setter);
1.796     raeburn  1599:                     }
                   1600:                 }
                   1601:             }
                   1602:         }
                   1603:     }
                   1604:     return ();
                   1605: }
                   1606: 
                   1607: sub sections_and_groups {
                   1608:     my (@sections,@groups,$group_display);
                   1609:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   1610:     if (grep(/^all$/,@groups)) {
                   1611:          @groups = ('all');
                   1612:          $group_display = 'all';
                   1613:     } elsif (grep(/^none$/,@groups)) {
                   1614:          @groups = ('none');
                   1615:          $group_display = 'none';
                   1616:     } elsif (@groups > 0) {
                   1617:          $group_display = join(', ',@groups);
                   1618:     }
                   1619:     if ($env{'request.course.sec'} ne '') {
                   1620:         @sections = ($env{'request.course.sec'});
                   1621:     } else {
                   1622:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1623:     }
                   1624:     my $disabled = ' disabled="disabled"';
                   1625:     if ($perm{'mgr'}) {
                   1626:         if (grep(/^all$/,@sections)) {
                   1627:             undef($disabled);
                   1628:         } else {
                   1629:             foreach my $sec (@sections) {
                   1630:                 if (&canmodify($sec)) {
                   1631:                     undef($disabled);
                   1632:                     last;
                   1633:                 }
                   1634:             }
                   1635:         }
                   1636:     }
                   1637:     if (grep(/^all$/,@sections)) {
                   1638:         @sections = ('all');
                   1639:     }
                   1640:     return(\@sections,\@groups,$group_display,$disabled);
                   1641: }
                   1642: 
                   1643: sub launcher_info_box {
                   1644:     my ($launcher,$appname,$setter,$linkuri,$scope) = @_;
                   1645:     my $shownscope;
                   1646:     if ($scope eq 'res') {
                   1647:         $shownscope = &mt('Resource');
                   1648:     } elsif ($scope eq 'map') {
                   1649:         $shownscope = &mt('Folder');
                   1650:     }  elsif ($scope eq 'rec') {
                   1651:         $shownscope = &mt('Folder + sub-folders');
                   1652:     }
                   1653:     return '<p>'.
                   1654:            &Apache::lonhtmlcommon::start_pick_box().
                   1655:            &Apache::lonhtmlcommon::row_title(&mt('Launch Item Title')).
1.797     raeburn  1656:            &Apache::lonnet::gettitle($launcher).
1.796     raeburn  1657:            &Apache::lonhtmlcommon::row_closure().
                   1658:            &Apache::lonhtmlcommon::row_title(&mt('Deep-link')).
                   1659:            $linkuri.
                   1660:            &Apache::lonhtmlcommon::row_closure().
                   1661:            &Apache::lonhtmlcommon::row_title(&mt('Launcher')).
                   1662:            $appname.' '.$setter.
                   1663:            &Apache::lonhtmlcommon::row_closure().
                   1664:            &Apache::lonhtmlcommon::row_title(&mt('Score Type')).
                   1665:            $shownscope.      
                   1666:            &Apache::lonhtmlcommon::row_closure(1).
                   1667:            &Apache::lonhtmlcommon::end_pick_box().'</p>'."\n";
                   1668: }
                   1669: 
1.798     raeburn  1670: sub passbacks_for_symb {
                   1671:     my ($cdom,$cnum,$symb) = @_;
                   1672:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   1673:     my %needpb;
                   1674:     if (keys(%passback)) {
                   1675:         my $checkpb = 1;
                   1676:         if (exists($passback{$symb})) {
                   1677:             if (keys(%passback) == 1) {
                   1678:                 undef($checkpb);
                   1679:             }
                   1680:             if (ref($passback{$symb}) eq 'HASH') {
                   1681:                 foreach my $launcher (keys(%{$passback{$symb}})) {
                   1682:                     $needpb{$launcher} = 1;
                   1683:                 }
                   1684:             }
                   1685:         }
                   1686:         if ($checkpb) {
                   1687:             my ($map,$id,$url) = &Apache::lonnet::decode_symb($symb);
                   1688:             my $navmap = Apache::lonnavmaps::navmap->new();
                   1689:             if (ref($navmap)) {
                   1690:                 my $mapres = $navmap->getResourceByUrl($map);
                   1691:                 if (ref($mapres)) {
                   1692:                     my $mapsymb = $mapres->symb();
                   1693:                     if (exists($passback{$mapsymb})) {
                   1694:                         if (keys(%passback) == 1) {
                   1695:                             undef($checkpb);
                   1696:                         }
                   1697:                         if (ref($passback{$mapsymb}) eq 'HASH') {
                   1698:                             foreach my $launcher (keys(%{$passback{$mapsymb}})) {
                   1699:                                 $needpb{$launcher} = 1;
                   1700:                             }
                   1701:                         }
                   1702:                     }
                   1703:                     my %posspb;
                   1704:                     if ($checkpb) {
                   1705:                         my @recurseup = $navmap->recurseup_maps($map,1);
                   1706:                         if (@recurseup) {
                   1707:                             map { $posspb{$_} = 1; } @recurseup;
                   1708:                         }
                   1709:                     }
                   1710:                     foreach my $key (keys(%passback)) {
                   1711:                         if (exists($posspb{$key})) {
                   1712:                             if (ref($passback{$key}) eq 'HASH') {
                   1713:                                 foreach my $launcher (keys(%{$passback{$key}})) {
                   1714:                                     my ($linkuri,$linkprotector,$scope) = split("\0",$launcher);
                   1715:                                     next unless ($scope eq 'rec');
                   1716:                                     $needpb{$launcher} = 1;
                   1717:                                 }
                   1718:                             }
                   1719:                         }
                   1720:                     }
                   1721:                 }
                   1722:             }
                   1723:         }
                   1724:     }
                   1725:     return %needpb;
                   1726: }
                   1727: 
                   1728: sub process_passbacks {
                   1729:     my ($context,$symbs,$cdom,$cnum,$udom,$uname,$weights,$awardeds,$excuseds,$needpb,
                   1730:         $skip_passback,$pbsave,$pbids) = @_;
                   1731:     if ((ref($needpb) eq 'HASH') && (ref($skip_passback) eq 'HASH') && (ref($pbsave) eq 'HASH')) {
                   1732:         my (%weight,%awarded,%excused);
                   1733:         if ((ref($symbs) eq 'ARRAY') && (ref($weights) eq 'HASH') && (ref($awardeds) eq 'HASH') &&
                   1734:             (ref($excuseds) eq 'HASH')) {
                   1735:             %weight = %{$weights};
                   1736:             %awarded = %{$awardeds};
                   1737:             %excused = %{$excuseds};
                   1738:         }
                   1739:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
                   1740:         my @launchers = keys(%{$needpb});
                   1741:         my %pbinfo;
                   1742:         if (ref($pbids) eq 'HASH') {
                   1743:             %pbinfo = %{$pbids};
                   1744:         } else {
                   1745:             %pbinfo = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@launchers,$udom,$uname);
                   1746:         }
                   1747:         my %pbc = &common_passback_info();
                   1748:         foreach my $launcher (@launchers) {
                   1749:             if (ref($pbinfo{$launcher}) eq 'ARRAY') {
                   1750:                 my $pbid = $pbinfo{$launcher}[0];
                   1751:                 my $pburl = $pbinfo{$launcher}[1];
                   1752:                 my (%total_by_symb,%possible_by_symb);
                   1753:                 if (($pbid ne '') && ($pburl ne '')) {
                   1754:                     next if ($skip_passback->{$launcher});
                   1755:                     my %pb = %pbc;
                   1756:                     if ((exists($pbsave->{$launcher})) &&
                   1757:                         (ref($pbsave->{$launcher}) eq 'HASH')) {
                   1758:                         foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
                   1759:                                           'symb','map','pbscope','linkuri','linkprotector','scope') {
                   1760:                             $pb{$item} = $pbsave->{$launcher}{$item};
                   1761:                         }
                   1762:                     } else {
                   1763:                         my $ltitype;
                   1764:                         ($pb{'linkuri'},$pb{'linkprotector'},$pb{'scope'}) = split("\0",$launcher);
                   1765:                         ($pb{'ltinum'},$ltitype) = ($pb{'linkprotector'} =~ /^(\d+)(c|d)$/);
                   1766:                         if ($ltitype eq 'c') {
                   1767:                             my %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1768:                             $pb{'lti_in_use'} = $crslti{$pb{'ltinum'}};
                   1769:                             $pb{'crsdef'} = 1;
                   1770:                         } else {
                   1771:                             my %domlti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1772:                             $pb{'lti_in_use'} = $domlti{$pb{'ltinum'}};
                   1773:                         }
                   1774:                         if (ref($pb{'lti_in_use'}) eq 'HASH') {
                   1775:                             $pb{'msgformat'} = $pb{'lti_in_use'}->{'passbackformat'};
                   1776:                             $pb{'keynum'} = $pb{'lti_in_use'}->{'cipher'};
                   1777:                             $pb{'scoretype'} = 'decimal';
                   1778:                             if ($pb{'lti_in_use'}->{'scoreformat'} =~ /^(decimal|ratio|percentage)$/) {
                   1779:                                 $pb{'scoretype'} = $1;
                   1780:                             }
                   1781:                             $pb{'symb'} = &Apache::loncommon::symb_from_tinyurl($pb{'linkuri'},$cnum,$cdom);
                   1782:                             if ($pb{'symb'} =~ /\.(page|sequence)$/) {
                   1783:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[2]);
                   1784:                             } else {
                   1785:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[0]);
                   1786:                             }
                   1787:                             $pb{'map'} = &Apache::lonnet::clutter($pb{'map'});
                   1788:                             if ($pb{'scope'} eq 'res') {
                   1789:                                 $pb{'pbscope'} = 'resource';
                   1790:                             } elsif ($pb{'scope'} eq 'map') {
                   1791:                                 $pb{'pbscope'} = 'nonrec';
                   1792:                             } elsif ($pb{'scope'} eq 'rec') {
                   1793:                                 $pb{'pbscope'} = 'map';
                   1794:                             }
                   1795:                             foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
                   1796:                                               'symb','map','pbscope','linkuri','linkprotector','scope') {
                   1797:                                 $pbsave->{$launcher}{$item} = $pb{$item};
                   1798:                             }
                   1799:                         } else {
                   1800:                             $skip_passback->{$launcher} = 1;
                   1801:                         }
                   1802:                     }
                   1803:                     if (ref($symbs) eq 'ARRAY') {
                   1804:                         foreach my $symb (@{$symbs}) {
                   1805:                             if ((ref($weight{$symb}) eq 'HASH') && (ref($awarded{$symb}) eq 'HASH') &&
                   1806:                                 (ref($excused{$symb}) eq 'HASH')) {
                   1807:                                 foreach my $part (keys(%{$weight{$symb}})) {
                   1808:                                     if ($excused{$symb}{$part}) {
                   1809:                                         next;
                   1810:                                     }
                   1811:                                     my $partweight = $weight{$symb}{$part} eq '' ? 1 :
                   1812:                                                      $weight{$symb}{$part};
                   1813:                                     if ($awarded{$symb}{$part}) {
                   1814:                                         $total_by_symb{$symb} += $partweight * $awarded{$symb}{$part};
                   1815:                                     }
                   1816:                                     $possible_by_symb{$symb} += $partweight;
                   1817:                                 }
                   1818:                             }
                   1819:                         }
                   1820:                     }
                   1821:                     if ($context eq 'updatebypage') {
                   1822:                         my $ltigrade = {
                   1823:                                         'ltinum'     => $pb{'ltinum'},
                   1824:                                         'lti'        => $pb{'lti_in_use'},
                   1825:                                         'crsdef'     => $pb{'crsdef'},
                   1826:                                         'cid'        => $cdom.'_'.$cnum,
                   1827:                                         'uname'      => $uname,
                   1828:                                         'udom'       => $udom,
                   1829:                                         'uhome'      => $uhome,
                   1830:                                         'pbid'       => $pbid,
                   1831:                                         'pburl'      => $pburl,
                   1832:                                         'pbtype'     => $pb{'type'},
                   1833:                                         'pbscope'    => $pb{'pbscope'},
                   1834:                                         'pbmap'      => $pb{'map'},
                   1835:                                         'pbsymb'     => $pb{'symb'},
                   1836:                                         'format'     => $pb{'scoretype'},
                   1837:                                         'scope'      => $pb{'scope'},
                   1838:                                         'clientip'   => $pb{'clientip'},
1.799     raeburn  1839:                                         'linkprot'   => $pb{'linkprotector'}.':'.$pb{'linkuri'},
1.798     raeburn  1840:                                         'total_s'    => \%total_by_symb,
                   1841:                                         'possible_s' => \%possible_by_symb,
                   1842:                         };
1.801   ! raeburn  1843:                         push(@Apache::grades::ltipassback,$ltigrade);
1.798     raeburn  1844:                         next;
                   1845:                     }
                   1846:                     my ($total,$possible);
                   1847:                     if ($pb{'pbscope'} eq 'resource') {
                   1848:                         $total = $total_by_symb{$pb{'symb'}};
                   1849:                         $possible = $possible_by_symb{$pb{'symb'}};
                   1850:                     } elsif (($pb{'pbscope'} eq 'map') || ($pb{'pbscope'} eq 'nonrec')) {
                   1851:                         ($total,$possible) =
                   1852:                             &Apache::lonhomework::get_lti_score($uname,$udom,$pb{'map'},$pb{'pbscope'},
                   1853:                                                                 \%total_by_symb,\%possible_by_symb);
                   1854:                     }
                   1855:                     if (!$possible) {
                   1856:                         $total = 0;
                   1857:                         $possible = 1;
                   1858:                     }
                   1859:                     my ($sent,$score,$code,$result) =
                   1860:                         &LONCAPA::ltiutils::send_grade($cdom,$cnum,$pb{'crsdef'},$pb{'type'},$pb{'ltinum'},
                   1861:                                                        $pb{'keynum'},$pbid,$pburl,$pb{'scoretype'},$pb{'sigmethod'},
                   1862:                                                        $pb{'msgformat'},$total,$possible);
                   1863:                     my $no_passback;
                   1864:                     if ($sent) {
                   1865:                         if ($code == 200) {
                   1866:                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
                   1867:                             my $store = {
                   1868:                                 'score' => $score,
                   1869:                                 'ip' => $pb{'ip'},
                   1870:                                 'host' => $pb{'lonhost'},
                   1871:                                 'protector' => $pb{'linkprotector'},
                   1872:                                 'deeplink' => $pb{'linkuri'},
                   1873:                                 'scope' => $pb{'scope'},
                   1874:                                 'url' => $pburl,
                   1875:                                 'id' => $pbid,
                   1876:                                 'clientip' => $pb{'clientip'},
                   1877:                                 'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
                   1878:                             };
                   1879:                             my $value='';
                   1880:                             foreach my $key (keys(%{$store})) {
                   1881:                                  $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
                   1882:                             }
                   1883:                             $value=~s/\&$//;
                   1884:                             &Apache::lonnet::courselog(&escape($pb{'linkuri'}).':'.$uname.':'.$udom.':EXPORT:'.$value);
                   1885:                             &Apache::lonnet::cstore({'score' => $score},$launcher,$namespace,$udom,$uname,'',$pb{'ip'},1);
                   1886:                         } else {
                   1887:                             $no_passback = 1;
                   1888:                         }
                   1889:                     } else {
                   1890:                         $no_passback = 1;
                   1891:                     }
                   1892:                     if ($no_passback) {
                   1893:                         &Apache::lonnet::log($udom,$uname,$uhome,$no_passback." score: $score; total: $total; possible: $possible");
                   1894:                         my $ltigrade = {
                   1895:                            'ltinum'   => $pb{'ltinum'},
                   1896:                            'lti'      => $pb{'lti_in_use'},
                   1897:                            'crsdef'   => $pb{'crsdef'},
                   1898:                            'cid'      => $cdom.'_'.$cnum,
                   1899:                            'uname'    => $uname,
                   1900:                            'udom'     => $udom,
                   1901:                            'uhome'    => $uhome,
                   1902:                            'pbid'     => $pbid,
                   1903:                            'pburl'    => $pburl,
                   1904:                            'pbtype'   => $pb{'type'},
                   1905:                            'pbscope'  => $pb{'pbscope'},
                   1906:                            'pbmap'    => $pb{'map'},
                   1907:                            'pbsymb'   => $pb{'symb'},
                   1908:                            'format'   => $pb{'scoretype'},
                   1909:                            'scope'    => $pb{'scope'},
                   1910:                            'clientip' => $pb{'clientip'},
1.799     raeburn  1911:                            'linkprot' => $pb{'linkprotector'}.':'.$pb{'linkuri'},
1.798     raeburn  1912:                            'total'    => $total,
                   1913:                            'possible' => $possible,
                   1914:                            'score'    => $score,
                   1915:                         };
                   1916:                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1917:                     }
                   1918:                 }
                   1919:             }
                   1920:         }
                   1921:     }
                   1922:     return;
                   1923: }
                   1924: 
                   1925: sub common_passback_info {
                   1926:     my %pbc = (
                   1927:                sigmethod => 'HMAC-SHA1',
                   1928:                type      => 'linkprot',
                   1929:                clientip  => &Apache::lonnet::get_requestor_ip(),
                   1930:                lonhost   => $Apache::lonnet::perlvar{'lonHostID'},
                   1931:                ip        => &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}),
                   1932:              );
                   1933:     return %pbc;
                   1934: }
                   1935: 
1.44      ng       1936: #--- This is called by a number of programs.
                   1937: #--- Called from the Grading Menu - View/Grade an individual student
                   1938: #--- Also called directly when one clicks on the subm button 
                   1939: #    on the problem page.
1.30      ng       1940: sub listStudents {
1.773     raeburn  1941:     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1942: 
1.747     raeburn  1943:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1944:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1945:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1946:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1947:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www      1948:     unless ($submitonly) {
1.766     raeburn  1949:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www      1950:     }
1.49      albertel 1951: 
1.632     www      1952:     my $result='';
1.623     www      1953:     my $res_error;
1.773     raeburn  1954:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   1955: 
                   1956:     my $table;
                   1957:     if (ref($partlist) eq 'ARRAY') {
                   1958:         if (scalar(@$partlist) > 1 ) {
                   1959:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1960:         } elsif ($divforres) {
                   1961:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1962:         } else {
                   1963:             $table = '<br clear="all" />';
                   1964:         }
                   1965:     }
1.49      albertel 1966: 
1.796     raeburn  1967:     $request->print(&checkselect_js());
1.597     wenzelju 1968:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1969: 
                   1970:     function reLoadList(formname) {
1.112     ng       1971: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1972: 	formname.command.value = 'submission';
                   1973: 	formname.submit();
                   1974:     }
1.45      ng       1975: LISTJAVASCRIPT
                   1976: 
1.118     ng       1977:     &commonJSfunctions($request);
1.41      ng       1978:     $request->print($result);
1.39      ng       1979: 
1.154     albertel 1980:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.773     raeburn  1981: 	"\n".$table;
                   1982: 
1.561     bisitz   1983:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn  1984:     unless ($is_tool) {
                   1985:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1986:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1987:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1988:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1989:                       .&Apache::lonhtmlcommon::row_closure();
                   1990:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1991:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1992:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1993:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1994:                       .&Apache::lonhtmlcommon::row_closure();
                   1995:     }
1.485     albertel 1996: 
1.442     banghart 1997:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1998:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1999:     $env{'form.Status'} = $saveStatus;
1.745     raeburn  2000:     my %optiontext;
                   2001:     if ($is_tool) {
                   2002:         %optiontext = &Apache::lonlocal::texthash (
                   2003:                           lastonly => 'last transaction',
                   2004:                           last     => 'last transaction with details',
                   2005:                           datesub  => 'all transactions',
                   2006:                           all      => 'all transactions with details',
                   2007:                       );
                   2008:     } else {
                   2009:         %optiontext = &Apache::lonlocal::texthash (
                   2010:                           lastonly => 'last submission',
                   2011:                           last     => 'last submission with details',
                   2012:                           datesub  => 'all submissions',
                   2013:                           all      => 'all submissions with details',
                   2014:                       );
                   2015:     }
1.773     raeburn  2016:     my $submission_options =
1.592     bisitz   2017:         '<span class="LC_nobreak">'.
1.624     www      2018:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  2019:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   2020:         '<span class="LC_nobreak">'.
                   2021:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  2022:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   2023:         '<span class="LC_nobreak">'.
1.628     www      2024:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  2025:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   2026:         '<span class="LC_nobreak">'.
                   2027:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  2028:         $optiontext{'all'}.'</label></span>';
                   2029:     my $viewtitle;
                   2030:     if ($is_tool) {
                   2031:         $viewtitle = &mt('View Transactions');
                   2032:     } else {
                   2033:         $viewtitle = &mt('View Submissions');
                   2034:     }
1.773     raeburn  2035:     my ($compmsg,$nocompmsg);
                   2036:     $nocompmsg = ' checked="checked"';
                   2037:     if ($numessay) {
                   2038:         $compmsg = $nocompmsg;
                   2039:         $nocompmsg = '';
                   2040:     }
1.745     raeburn  2041:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.780     raeburn  2042:                   .$submission_options;
                   2043: # Check if any gradable
                   2044:     my $showmore;
                   2045:     if ($perm{'mgr'}) {
                   2046:         my @sections;
                   2047:         if ($env{'request.course.sec'} ne '') {
                   2048:             @sections = ($env{'request.course.sec'});
1.783     raeburn  2049:         } elsif ($env{'form.section'} eq '') {
                   2050:             @sections = ('all');
1.780     raeburn  2051:         } else {
                   2052:             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   2053:         }
                   2054:         if (grep(/^all$/,@sections)) {
                   2055:             $showmore = 1;
                   2056:         } else {
                   2057:             foreach my $sec (@sections) {
                   2058:                 if (&canmodify($sec)) {
                   2059:                     $showmore = 1;
                   2060:                     last;
                   2061:                 }
                   2062:             }
                   2063:         }
                   2064:     }
                   2065: 
                   2066:     if ($showmore) {
                   2067:         $gradeTable .=
                   2068:                    &Apache::lonhtmlcommon::row_closure()
1.773     raeburn  2069:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   2070:                   .'<span class="LC_nobreak">'
                   2071:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   2072:                   .&mt('No').('&nbsp;'x2).'</label>'
                   2073:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   2074:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   2075:                   .&Apache::lonhtmlcommon::row_closure();
                   2076: 
1.780     raeburn  2077:         $gradeTable .= 
                   2078:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   2079:                   .'<select name="increment">'
                   2080:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   2081:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   2082:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   2083:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773     raeburn  2084:                   .'</select>';
1.780     raeburn  2085:     }
1.485     albertel 2086:     $gradeTable .= 
1.432     banghart 2087:         &build_section_inputs().
1.45      ng       2088: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 2089: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       2090: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      2091:     if (exists($env{'form.Status'})) {
1.784     raeburn  2092: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng       2093:     } else {
1.773     raeburn  2094:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2095:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   2096:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773     raeburn  2097:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       2098:     }
1.773     raeburn  2099:     if ($numessay) {
                   2100:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2101:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   2102:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  2103:     }
1.773     raeburn  2104:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
                   2105:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  2106:     my $regrademsg;
                   2107:     if ($is_tool) {
                   2108:         $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.");
                   2109:     } else {
                   2110:         $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.");
                   2111:     }
1.561     bisitz   2112:     $gradeTable .= '<p>'
1.745     raeburn  2113:                   .$regrademsg."\n"
1.561     bisitz   2114:                   .'<input type="hidden" name="command" value="processGroup" />'
                   2115:                   .'</p>';
1.249     albertel 2116: 
                   2117: # checkall buttons
                   2118:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       2119:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   2120:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   2121:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 2122:     $gradeTable.=&check_buttons();
1.450     banghart 2123:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 2124:     $gradeTable.= &Apache::loncommon::start_data_table().
                   2125: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       2126:     my $loop = 0;
                   2127:     while ($loop < 2) {
1.485     albertel 2128: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   2129: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      2130: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 2131: 	    foreach my $part (sort(@$partlist)) {
                   2132: 		my $display_part=
                   2133: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   2134: 		$gradeTable.=
                   2135: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       2136: 	    }
1.301     albertel 2137: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 2138: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       2139: 	}
                   2140: 	$loop++;
1.126     ng       2141: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       2142:     }
1.474     albertel 2143:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       2144: 
1.45      ng       2145:     my $ctr = 0;
1.294     albertel 2146:     foreach my $student (sort 
                   2147: 			 {
                   2148: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2149: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2150: 			     }
                   2151: 			     return $a cmp $b;
                   2152: 			 }
                   2153: 			 (keys(%$fullname))) {
1.41      ng       2154: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2155: 
1.110     ng       2156: 	my %status = ();
1.301     albertel 2157: 
                   2158: 	if ($submitonly eq 'queued') {
                   2159: 	    my %queue_status = 
                   2160: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2161: 							$udom,$uname);
                   2162: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2163: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   2164: 	}
                   2165: 
1.618     www      2166: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 2167: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2168: 	    my $submitted = 0;
1.164     albertel 2169: 	    my $graded = 0;
1.248     albertel 2170: 	    my $incorrect = 0;
1.110     ng       2171: 	    foreach (keys(%status)) {
1.145     albertel 2172: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2173: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   2174: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   2175: 		
1.110     ng       2176: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2177: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 2178: 		    $submitted = 0;
1.150     albertel 2179: 		    my ($part)=split(/\./,$partid);
1.110     ng       2180: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 2181: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       2182: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   2183: 		}
1.41      ng       2184: 	    }
1.248     albertel 2185: 	    
1.156     albertel 2186: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2187: 				     $submitonly eq 'incorrect' ||
                   2188: 				     $submitonly eq 'graded'));
1.248     albertel 2189: 	    next if (!$graded && ($submitonly eq 'graded'));
                   2190: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2191: 	}
1.34      ng       2192: 
1.45      ng       2193: 	$ctr++;
1.249     albertel 2194: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 2195:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 2196: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 2197: 	    if ($ctr%2 ==1) {
                   2198: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   2199: 	    }
1.126     ng       2200: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   2201:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 2202:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   2203: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   2204: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 2205: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       2206: 
1.618     www      2207: 	    if ($submitonly ne 'all') {
1.524     raeburn  2208: 		foreach (sort(keys(%status))) {
1.485     albertel 2209: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   2210: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       2211: 		}
1.41      ng       2212: 	    }
1.126     ng       2213: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 2214: 	    if ($ctr%2 ==0) {
                   2215: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   2216: 	    }
1.41      ng       2217: 	}
                   2218:     }
1.110     ng       2219:     if ($ctr%2 ==1) {
1.126     ng       2220: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      2221: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       2222: 		foreach (@$partlist) {
                   2223: 		    $gradeTable.='<td>&nbsp;</td>';
                   2224: 		}
1.301     albertel 2225: 	    } elsif ($submitonly eq 'queued') {
                   2226: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       2227: 	    }
1.474     albertel 2228: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       2229:     }
                   2230: 
1.474     albertel 2231:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   2232:         '<input type="button" '.
                   2233:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   2234:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       2235:     if ($ctr == 0) {
1.96      albertel 2236: 	my $num_students=(scalar(keys(%$fullname)));
                   2237: 	if ($num_students eq 0) {
1.485     albertel 2238: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 2239: 	} else {
1.171     albertel 2240: 	    my $submissions='submissions';
                   2241: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   2242: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 2243: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 2244: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   2245: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 2246: 		    $num_students).
                   2247: 		'</span><br />';
1.96      albertel 2248: 	}
1.46      ng       2249:     } elsif ($ctr == 1) {
1.474     albertel 2250: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       2251:     }
                   2252:     $request->print($gradeTable);
1.44      ng       2253:     return '';
1.10      ng       2254: }
                   2255: 
1.796     raeburn  2256: #---- Called from the listStudents and the names_for_passback routines.
                   2257: 
                   2258: sub checkselect_js {
                   2259:     my ($formname) = @_;
                   2260:     if ($formname eq '') {
                   2261:         $formname = 'gradesub';
                   2262:     }
                   2263:     my %js_lt;
                   2264:     if ($formname eq 'passbackusers') {
                   2265:         %js_lt = &Apache::lonlocal::texthash (
                   2266:                      'multiple' => 'Please select a student or group of students before pushing the Save Scores button.',
                   2267:                      'single'   => 'Please select the student before pushing the Save Scores button.',
                   2268:                  );
                   2269:     } else {
                   2270:         %js_lt = &Apache::lonlocal::texthash (
                   2271:                      'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   2272:                      'single'   => 'Please select the student before clicking on the Next button.',
                   2273:                  );
                   2274:     }
                   2275:     &js_escape(\%js_lt);
                   2276:     return &Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT);
                   2277: 
                   2278:     function checkSelect(checkBox) {
                   2279:         var ctr=0;
                   2280:         var sense="";
                   2281:         var len = checkBox.length;
                   2282:         if (len == undefined) len = 1;
                   2283:         if (len > 1) {
                   2284:             for (var i=0; i<len; i++) {
                   2285:                 if (checkBox[i].checked) {
                   2286:                     ctr++;
                   2287:                 }
                   2288:             }
                   2289:             sense = '$js_lt{'multiple'}';
                   2290:         } else {
                   2291:             if (checkBox.checked) {
                   2292:                 ctr = 1;
                   2293:             }
                   2294:             sense = '$js_lt{'single'}';
                   2295:         }
                   2296:         if (ctr == 0) {
                   2297:             alert(sense);
                   2298:             return false;
                   2299:         }
                   2300:         document.$formname.submit();
                   2301:     }
                   2302: LISTJAVASCRIPT
                   2303: 
                   2304: }
1.249     albertel 2305: 
                   2306: sub check_script {
1.766     raeburn  2307:     my ($form,$type) = @_;
                   2308:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 2309:     function checkall() {
                   2310:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2311:             ele = document.forms.'.$form.'.elements[i];
                   2312:             if (ele.name == "'.$type.'") {
                   2313:             document.forms.'.$form.'.elements[i].checked=true;
                   2314:                                        }
                   2315:         }
                   2316:     }
                   2317: 
                   2318:     function checksec() {
                   2319:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2320:             ele = document.forms.'.$form.'.elements[i];
                   2321:            string = document.forms.'.$form.'.chksec.value;
                   2322:            if
                   2323:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   2324:               document.forms.'.$form.'.elements[i].checked=true;
                   2325:             }
                   2326:         }
                   2327:     }
                   2328: 
                   2329: 
                   2330:     function uncheckall() {
                   2331:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2332:             ele = document.forms.'.$form.'.elements[i];
                   2333:             if (ele.name == "'.$type.'") {
                   2334:             document.forms.'.$form.'.elements[i].checked=false;
                   2335:                                        }
                   2336:         }
                   2337:     }
                   2338: 
1.597     wenzelju 2339: '."\n");
1.249     albertel 2340:     return $chkallscript;
                   2341: }
                   2342: 
                   2343: sub check_buttons {
1.485     albertel 2344:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   2345:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   2346:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 2347:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   2348:     return $buttons;
                   2349: }
                   2350: 
1.44      ng       2351: #     Displays the submissions for one student or a group of students
1.34      ng       2352: sub processGroup {
1.766     raeburn  2353:     my ($request,$symb) = @_;
1.41      ng       2354:     my $ctr        = 0;
1.155     albertel 2355:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       2356:     my $total      = scalar(@stuchecked)-1;
1.45      ng       2357: 
1.396     banghart 2358:     foreach my $student (@stuchecked) {
                   2359: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 2360: 	$env{'form.student'}        = $uname;
                   2361: 	$env{'form.userdom'}        = $udom;
                   2362: 	$env{'form.fullname'}       = $fullname;
1.619     www      2363: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2364: 	$ctr++;
                   2365:     }
                   2366:     return '';
1.35      ng       2367: }
1.34      ng       2368: 
1.44      ng       2369: #------------------------------------------------------------------------------------
                   2370: #
                   2371: #-------------------------- Next few routines handles grading by student, essentially
                   2372: #                           handles essay response type problem/part
                   2373: #
                   2374: #--- Javascript to handle the submission page functionality ---
                   2375: sub sub_page_js {
                   2376:     my $request = shift;
1.736     damieng  2377:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   2378:     &js_escape(\$alertmsg);
1.597     wenzelju 2379:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       2380:     function updateRadio(formname,id,weight) {
1.125     ng       2381: 	var gradeBox = formname["GD_BOX"+id];
                   2382: 	var radioButton = formname["RADVAL"+id];
                   2383: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       2384: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       2385: 	gradeBox.value = pts;
                   2386: 	var resetbox = false;
                   2387: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  2388: 	    alert("$alertmsg"+pts);
1.71      ng       2389: 	    for (var i=0; i<radioButton.length; i++) {
                   2390: 		if (radioButton[i].checked) {
                   2391: 		    gradeBox.value = i;
                   2392: 		    resetbox = true;
                   2393: 		}
                   2394: 	    }
                   2395: 	    if (!resetbox) {
                   2396: 		formtextbox.value = "";
                   2397: 	    }
                   2398: 	    return;
1.44      ng       2399: 	}
1.71      ng       2400: 
                   2401: 	if (pts > weight) {
                   2402: 	    var resp = confirm("You entered a value ("+pts+
                   2403: 			       ") greater than the weight for the part. Accept?");
                   2404: 	    if (resp == false) {
1.125     ng       2405: 		gradeBox.value = oldpts;
1.71      ng       2406: 		return;
                   2407: 	    }
1.44      ng       2408: 	}
1.13      albertel 2409: 
1.71      ng       2410: 	for (var i=0; i<radioButton.length; i++) {
                   2411: 	    radioButton[i].checked=false;
                   2412: 	    if (pts == i && pts != "") {
                   2413: 		radioButton[i].checked=true;
                   2414: 	    }
                   2415: 	}
                   2416: 	updateSelect(formname,id);
1.125     ng       2417: 	formname["stores"+id].value = "0";
1.41      ng       2418:     }
1.5       albertel 2419: 
1.72      ng       2420:     function writeBox(formname,id,pts) {
1.125     ng       2421: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2422: 	if (checkSolved(formname,id) == 'update') {
                   2423: 	    gradeBox.value = pts;
                   2424: 	} else {
1.125     ng       2425: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       2426: 	    gradeBox.value = oldpts;
1.125     ng       2427: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       2428: 	    for (var i=0; i<radioButton.length; i++) {
                   2429: 		radioButton[i].checked=false;
1.72      ng       2430: 		if (i == oldpts) {
1.71      ng       2431: 		    radioButton[i].checked=true;
                   2432: 		}
                   2433: 	    }
1.41      ng       2434: 	}
1.125     ng       2435: 	formname["stores"+id].value = "0";
1.71      ng       2436: 	updateSelect(formname,id);
                   2437: 	return;
1.41      ng       2438:     }
1.44      ng       2439: 
1.71      ng       2440:     function clearRadBox(formname,id) {
                   2441: 	if (checkSolved(formname,id) == 'noupdate') {
                   2442: 	    updateSelect(formname,id);
                   2443: 	    return;
                   2444: 	}
1.125     ng       2445: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       2446: 	for (var i=0; i<gradeSelect.length; i++) {
                   2447: 	    if (gradeSelect[i].selected) {
                   2448: 		var selectx=i;
                   2449: 	    }
                   2450: 	}
1.125     ng       2451: 	var stores = formname["stores"+id];
1.71      ng       2452: 	if (selectx == stores.value) { return };
1.125     ng       2453: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2454: 	gradeBox.value = "";
1.125     ng       2455: 	var radioButton = formname["RADVAL"+id];
1.71      ng       2456: 	for (var i=0; i<radioButton.length; i++) {
                   2457: 	    radioButton[i].checked=false;
                   2458: 	}
                   2459: 	stores.value = selectx;
                   2460:     }
1.5       albertel 2461: 
1.71      ng       2462:     function checkSolved(formname,id) {
1.125     ng       2463: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       2464: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   2465: 	    if (!reply) {return "noupdate";}
1.120     ng       2466: 	    formname.overRideScore.value = 'yes';
1.41      ng       2467: 	}
1.71      ng       2468: 	return "update";
1.13      albertel 2469:     }
1.71      ng       2470: 
                   2471:     function updateSelect(formname,id) {
1.125     ng       2472: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       2473: 	return;
1.41      ng       2474:     }
1.33      ng       2475: 
1.121     ng       2476: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       2477:     function checksubmit(formname,val,total,parttot) {
1.121     ng       2478: 	formname.gradeOpt.value = val;
1.71      ng       2479: 	if (val == "Save & Next") {
                   2480: 	    for (i=0;i<=total;i++) {
                   2481: 		for (j=0;j<parttot;j++) {
1.125     ng       2482: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       2483: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2484: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       2485: 			if (points == "") {
1.125     ng       2486: 			    var name = formname["name"+i].value;
1.129     ng       2487: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   2488: 			    var resp = confirm("You did not assign a score for "+studentID+
                   2489: 					       ", part "+partid+". Continue?");
1.71      ng       2490: 			    if (resp == false) {
1.125     ng       2491: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       2492: 				return false;
                   2493: 			    }
                   2494: 			}
                   2495: 		    }
                   2496: 		}
                   2497: 	    }
                   2498: 	}
1.120     ng       2499: 	formname.submit();
                   2500:     }
                   2501: 
1.71      ng       2502: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   2503:     function checkSubmitPage(formname,total) {
                   2504: 	noscore = new Array(100);
                   2505: 	var ptr = 0;
                   2506: 	for (i=1;i<total;i++) {
1.125     ng       2507: 	    var partid = formname["q_"+i].value;
1.127     ng       2508: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2509: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   2510: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       2511: 		if (points == "" && status != "correct_by_student") {
                   2512: 		    noscore[ptr] = i;
                   2513: 		    ptr++;
                   2514: 		}
                   2515: 	    }
                   2516: 	}
                   2517: 	if (ptr != 0) {
                   2518: 	    var sense = ptr == 1 ? ": " : "s: ";
                   2519: 	    var prolist = "";
                   2520: 	    if (ptr == 1) {
                   2521: 		prolist = noscore[0];
                   2522: 	    } else {
                   2523: 		var i = 0;
                   2524: 		while (i < ptr-1) {
                   2525: 		    prolist += noscore[i]+", ";
                   2526: 		    i++;
                   2527: 		}
                   2528: 		prolist += "and "+noscore[i];
                   2529: 	    }
                   2530: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   2531: 	    if (resp == false) {
                   2532: 		return false;
                   2533: 	    }
                   2534: 	}
1.45      ng       2535: 
1.71      ng       2536: 	formname.submit();
                   2537:     }
                   2538: SUBJAVASCRIPT
                   2539: }
1.45      ng       2540: 
1.773     raeburn  2541: #--- javascript for grading message center
                   2542: sub sub_grademessage_js {
1.71      ng       2543:     my $request = shift;
1.80      ng       2544:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       2545:     &commonJSfunctions($request);
1.350     albertel 2546: 
1.629     www      2547:     my $inner_js_msg_central= (<<INNERJS);
                   2548: <script type="text/javascript">
1.350     albertel 2549:     function checkInput() {
                   2550:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   2551:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   2552:       var usrctr = document.msgcenter.usrctr.value;
                   2553:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   2554:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   2555: 
                   2556:       var msgchk = "";
                   2557:       if (document.msgcenter.subchk.checked) {
                   2558:          msgchk = "msgsub,";
                   2559:       }
                   2560:       var includemsg = 0;
                   2561:       for (var i=1; i<=nmsg; i++) {
                   2562:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   2563:           var frmmsg = document.msgcenter["msg"+i];
                   2564:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   2565:           var showflg = opener.document.SCORE["shownOnce"+i];
                   2566:           showflg.value = "1";
                   2567:           var chkbox = document.msgcenter["msgn"+i];
                   2568:           if (chkbox.checked) {
                   2569:              msgchk += "savemsg"+i+",";
                   2570:              includemsg = 1;
                   2571:           }
                   2572:       }
                   2573:       if (document.msgcenter.newmsgchk.checked) {
                   2574:          msgchk += "newmsg"+usrctr;
                   2575:          includemsg = 1;
                   2576:       }
                   2577:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   2578:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   2579:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   2580:       includemsg.value = msgchk;
                   2581: 
                   2582:       self.close()
                   2583: 
                   2584:     }
1.629     www      2585: </script>
1.350     albertel 2586: INNERJS
                   2587: 
1.773     raeburn  2588:     my $start_page_msg_central =
1.351     albertel 2589:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   2590: 				       {'js_ready'  => 1,
                   2591: 					'only_body' => 1,
                   2592: 					'bgcolor'   =>'#FFFFFF',});
1.773     raeburn  2593:     my $end_page_msg_central =
1.350     albertel 2594: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   2595: 
1.219     www      2596:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 2597:     $docopen=~s/^document\.//;
1.773     raeburn  2598: 
1.736     damieng  2599:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  2600:                 comp => 'Compose Message for: ',
                   2601:                 incl => 'Include',
1.656     raeburn  2602:                 type => 'Type',
1.652     raeburn  2603:                 subj => 'Subject',
                   2604:                 mesa => 'Message',
                   2605:                 new  => 'New',
                   2606:                 save => 'Save',
                   2607:                 canc => 'Cancel',
                   2608:              );
1.736     damieng  2609:     &html_escape(\%html_js_lt);
                   2610:     &js_escape(\%html_js_lt);
1.597     wenzelju 2611:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       2612: 
1.44      ng       2613: //===================== Script to view submitted by ==================
                   2614:   function viewSubmitter(submitter) {
                   2615:     document.SCORE.refresh.value = "on";
                   2616:     document.SCORE.NCT.value = "1";
                   2617:     document.SCORE.unamedom0.value = submitter;
                   2618:     document.SCORE.submit();
                   2619:     return;
                   2620:   }
                   2621: 
                   2622: //====================== Script for composing message ==============
1.80      ng       2623:    // preload images
                   2624:    img1 = new Image();
                   2625:    img1.src = "$iconpath/mailbkgrd.gif";
                   2626:    img2 = new Image();
                   2627:    img2.src = "$iconpath/mailto.gif";
                   2628: 
1.44      ng       2629:   function msgCenter(msgform,usrctr,fullname) {
                   2630:     var Nmsg  = msgform.savemsgN.value;
                   2631:     savedMsgHeader(Nmsg,usrctr,fullname);
                   2632:     var subject = msgform.msgsub.value;
1.127     ng       2633:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       2634:     re = /msgsub/;
                   2635:     var shwsel = "";
                   2636:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       2637:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   2638:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       2639:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       2640: 	var testmsg = "savemsg"+i+",";
                   2641: 	re = new RegExp(testmsg,"g");
1.44      ng       2642: 	shwsel = "";
                   2643: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       2644: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       2645: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       2646: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   2647: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       2648:     }
1.125     ng       2649:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       2650:     shwsel = "";
                   2651:     re = /newmsg/;
                   2652:     if (re.test(msgchk)) { shwsel = "checked" }
                   2653:     newMsg(newmsg,shwsel);
                   2654:     msgTail(); 
                   2655:     return;
                   2656:   }
                   2657: 
1.123     ng       2658:   function checkEntities(strx) {
                   2659:     if (strx.length == 0) return strx;
                   2660:     var orgStr = ["&", "<", ">", '"']; 
                   2661:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   2662:     var counter = 0;
                   2663:     while (counter < 4) {
                   2664: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   2665: 	counter++;
                   2666:     }
                   2667:     return strx;
                   2668:   }
                   2669: 
                   2670:   function strReplace(strx, orgStr, newStr) {
                   2671:     return strx.split(orgStr).join(newStr);
                   2672:   }
                   2673: 
1.44      ng       2674:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       2675:     var height = 70*Nmsg+250;
1.44      ng       2676:     if (height > 600) {
                   2677: 	height = 600;
                   2678:     }
1.118     ng       2679:     var xpos = (screen.width-600)/2;
                   2680:     xpos = (xpos < 0) ? '0' : xpos;
                   2681:     var ypos = (screen.height-height)/2-30;
                   2682:     ypos = (ypos < 0) ? '0' : ypos;
                   2683: 
1.668     www      2684:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       2685:     pWin.focus();
                   2686:     pDoc = pWin.document;
1.219     www      2687:     pDoc.$docopen;
1.351     albertel 2688:     pDoc.write('$start_page_msg_central');
1.76      ng       2689: 
                   2690:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   2691:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  2692:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       2693: 
1.676     golterma 2694:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  2695:     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       2696: }
                   2697:     function displaySubject(msg,shwsel) {
1.76      ng       2698:     pDoc = pWin.document;
1.676     golterma 2699:     pDoc.write("<tr>");
                   2700:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2701:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 2702:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       2703: }
                   2704: 
1.72      ng       2705:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       2706:     pDoc = pWin.document;
1.676     golterma 2707:     pDoc.write("<tr>");
                   2708:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 2709:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   2710:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2711: }
                   2712: 
                   2713:   function newMsg(newmsg,shwsel) {
1.76      ng       2714:     pDoc = pWin.document;
1.676     golterma 2715:     pDoc.write("<tr>");
                   2716:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2717:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 2718:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2719: }
                   2720: 
                   2721:   function msgTail() {
1.76      ng       2722:     pDoc = pWin.document;
1.676     golterma 2723:     //pDoc.write("<\\/table>");
1.465     albertel 2724:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  2725:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   2726:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 2727:     pDoc.write("<\\/form>");
1.351     albertel 2728:     pDoc.write('$end_page_msg_central');
1.128     ng       2729:     pDoc.close();
1.44      ng       2730: }
                   2731: 
1.773     raeburn  2732: SUBJAVASCRIPT
                   2733: }
                   2734: 
                   2735: #--- javascript for essay type problem --
                   2736: sub sub_page_kw_js {
                   2737:     my $request = shift;
                   2738: 
                   2739:     unless ($env{'form.compmsg'}) {
                   2740:         &commonJSfunctions($request);
                   2741:     }
                   2742: 
                   2743:     my $inner_js_highlight_central= (<<INNERJS);
                   2744: <script type="text/javascript">
                   2745:     function updateChoice(flag) {
                   2746:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   2747:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   2748:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   2749:       opener.document.SCORE.refresh.value = "on";
                   2750:       if (opener.document.SCORE.keywords.value!=""){
                   2751:          opener.document.SCORE.submit();
                   2752:       }
                   2753:       self.close()
                   2754:     }
                   2755: </script>
                   2756: INNERJS
                   2757: 
                   2758:     my $start_page_highlight_central =
                   2759:         &Apache::loncommon::start_page('Highlight Central',
                   2760:                                        $inner_js_highlight_central,
                   2761:                                        {'js_ready'  => 1,
                   2762:                                         'only_body' => 1,
                   2763:                                         'bgcolor'   =>'#FFFFFF',});
                   2764:     my $end_page_highlight_central =
                   2765:         &Apache::loncommon::end_page({'js_ready' => 1});
                   2766: 
                   2767:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   2768:     $docopen=~s/^document\.//;
                   2769: 
                   2770:     my %js_lt = &Apache::lonlocal::texthash(
                   2771:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   2772:                 plse => 'Please select a word or group of words from document and then click this link.',
                   2773:                 adds => 'Add selection to keyword list? Edit if desired.',
                   2774:                 col1 => 'red',
                   2775:                 col2 => 'green',
                   2776:                 col3 => 'blue',
                   2777:                 siz1 => 'normal',
                   2778:                 siz2 => '+1',
                   2779:                 siz3 => '+2',
                   2780:                 sty1 => 'normal',
                   2781:                 sty2 => 'italic',
                   2782:                 sty3 => 'bold',
                   2783:              );
                   2784:     my %html_js_lt = &Apache::lonlocal::texthash(
                   2785:                 save => 'Save',
                   2786:                 canc => 'Cancel',
                   2787:                 kehi => 'Keyword Highlight Options',
                   2788:                 txtc => 'Text Color',
                   2789:                 font => 'Font Size',
                   2790:                 fnst => 'Font Style',
                   2791:              );
                   2792:     &js_escape(\%js_lt);
                   2793:     &html_escape(\%html_js_lt);
                   2794:     &js_escape(\%html_js_lt);
                   2795:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   2796: 
                   2797: //===================== Show list of keywords ====================
                   2798:   function keywords(formname) {
                   2799:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   2800:     if (nret==null) return;
                   2801:     formname.keywords.value = nret;
                   2802: 
                   2803:     if (formname.keywords.value != "") {
                   2804:         formname.refresh.value = "on";
                   2805:         formname.submit();
                   2806:     }
                   2807:     return;
                   2808:   }
                   2809: 
                   2810: //===================== Script to add keyword(s) ==================
                   2811:   function getSel() {
                   2812:     if (document.getSelection) txt = document.getSelection();
                   2813:     else if (document.selection) txt = document.selection.createRange().text;
                   2814:     else return;
                   2815:     if (typeof(txt) != 'string') {
                   2816:         txt = String(txt);
                   2817:     }
                   2818:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   2819:     if (cleantxt=="") {
                   2820:         alert("$js_lt{'plse'}");
                   2821:         return;
                   2822:     }
                   2823:     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   2824:     if (nret==null) return;
                   2825:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   2826:     if (document.SCORE.keywords.value != "") {
                   2827:         document.SCORE.refresh.value = "on";
                   2828:         document.SCORE.submit();
                   2829:     }
                   2830:     return;
                   2831:   }
                   2832: 
1.44      ng       2833: //====================== Script for keyword highlight options ==============
                   2834:   function kwhighlight() {
                   2835:     var kwclr    = document.SCORE.kwclr.value;
                   2836:     var kwsize   = document.SCORE.kwsize.value;
                   2837:     var kwstyle  = document.SCORE.kwstyle.value;
                   2838:     var redsel = "";
                   2839:     var grnsel = "";
                   2840:     var blusel = "";
1.736     damieng  2841:     var txtcol1 = "$js_lt{'col1'}";
                   2842:     var txtcol2 = "$js_lt{'col2'}";
                   2843:     var txtcol3 = "$js_lt{'col3'}";
                   2844:     var txtsiz1 = "$js_lt{'siz1'}";
                   2845:     var txtsiz2 = "$js_lt{'siz2'}";
                   2846:     var txtsiz3 = "$js_lt{'siz3'}";
                   2847:     var txtsty1 = "$js_lt{'sty1'}";
                   2848:     var txtsty2 = "$js_lt{'sty2'}";
                   2849:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   2850:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   2851:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   2852:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       2853:     var sznsel = "";
                   2854:     var sz1sel = "";
                   2855:     var sz2sel = "";
1.718     bisitz   2856:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   2857:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   2858:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       2859:     var synsel = "";
                   2860:     var syisel = "";
                   2861:     var sybsel = "";
1.718     bisitz   2862:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   2863:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   2864:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       2865:     highlightCentral();
1.718     bisitz   2866:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   2867:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   2868:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       2869:     highlightend();
                   2870:     return;
                   2871:   }
                   2872: 
                   2873:   function highlightCentral() {
1.76      ng       2874: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       2875:     var xpos = (screen.width-400)/2;
                   2876:     xpos = (xpos < 0) ? '0' : xpos;
                   2877:     var ypos = (screen.height-330)/2-30;
                   2878:     ypos = (ypos < 0) ? '0' : ypos;
                   2879: 
1.206     albertel 2880:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       2881:     hwdWin.focus();
                   2882:     var hDoc = hwdWin.document;
1.219     www      2883:     hDoc.$docopen;
1.351     albertel 2884:     hDoc.write('$start_page_highlight_central');
1.76      ng       2885:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  2886:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       2887: 
1.718     bisitz   2888:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  2889:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       2890:   }
                   2891: 
                   2892:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       2893:     var hDoc = hwdWin.document;
1.718     bisitz   2894:     hDoc.write("<tr>");
1.76      ng       2895:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2896:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       2897:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2898:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       2899:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2900:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 2901:     hDoc.write("<\\/tr>");
1.44      ng       2902:   }
                   2903: 
                   2904:   function highlightend() { 
1.76      ng       2905:     var hDoc = hwdWin.document;
1.718     bisitz   2906:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  2907:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   2908:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 2909:     hDoc.write("<\\/form>");
1.351     albertel 2910:     hDoc.write('$end_page_highlight_central');
1.128     ng       2911:     hDoc.close();
1.44      ng       2912:   }
                   2913: 
                   2914: SUBJAVASCRIPT
                   2915: }
                   2916: 
1.349     albertel 2917: sub get_increment {
1.348     bowersj2 2918:     my $increment = $env{'form.increment'};
                   2919:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   2920:         $increment != .1) {
                   2921:         $increment = 1;
                   2922:     }
                   2923:     return $increment;
                   2924: }
                   2925: 
1.585     bisitz   2926: sub gradeBox_start {
                   2927:     return (
                   2928:         &Apache::loncommon::start_data_table()
                   2929:        .&Apache::loncommon::start_data_table_header_row()
                   2930:        .'<th>'.&mt('Part').'</th>'
                   2931:        .'<th>'.&mt('Points').'</th>'
                   2932:        .'<th>&nbsp;</th>'
                   2933:        .'<th>'.&mt('Assign Grade').'</th>'
                   2934:        .'<th>'.&mt('Weight').'</th>'
                   2935:        .'<th>'.&mt('Grade Status').'</th>'
                   2936:        .&Apache::loncommon::end_data_table_header_row()
                   2937:     );
                   2938: }
                   2939: 
                   2940: sub gradeBox_end {
                   2941:     return (
                   2942:         &Apache::loncommon::end_data_table()
                   2943:     );
                   2944: }
1.71      ng       2945: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   2946: sub gradeBox {
1.322     albertel 2947:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 2948:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2949: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2950:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2951:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2952:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2953:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2954:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2955: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   2956:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2957:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2958:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2959: 				       [$partid]);
                   2960:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2961:     if ($last_resets{$partid}) {
                   2962:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2963:     }
1.695     bisitz   2964:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2965:     my $ctr = 0;
1.348     bowersj2 2966:     my $thisweight = 0;
1.349     albertel 2967:     my $increment = &get_increment();
1.485     albertel 2968: 
                   2969:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2970:     while ($thisweight<=$wgt) {
1.532     bisitz   2971: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2972:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2973: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2974: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2975: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2976:         $thisweight += $increment;
1.71      ng       2977: 	$ctr++;
                   2978:     }
1.485     albertel 2979:     $radio.='</tr></table>';
                   2980: 
                   2981:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2982: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2983: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2984: 	$wgt.')" /></td>'."\n";
1.485     albertel 2985:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2986: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2987: 	' </td>'."\n";
                   2988:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2989: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2990:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2991: 	$line.='<option></option>'.
                   2992: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2993:     } else {
1.485     albertel 2994: 	$line.='<option selected="selected"></option>'.
                   2995: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2996:     }
1.485     albertel 2997:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2998: 
                   2999: 
                   3000:     $result .= 
1.695     bisitz   3001: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   3002:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   3003:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       3004:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   3005: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   3006: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  3007: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   3008:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   3009:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   3010:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   3011:         $aggtries.'" />'."\n";
1.582     raeburn  3012:     my $res_error;
                   3013:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   3014:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  3015:     if ($res_error) {
                   3016:         return &navmap_errormsg();
                   3017:     }
1.318     banghart 3018:     return $result;
                   3019: }
1.322     albertel 3020: 
                   3021: sub handback_box {
1.623     www      3022:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773     raeburn  3023:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   3024:     return unless ($numessay);
1.323     banghart 3025:     my (@respids);
1.652     raeburn  3026:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 3027:     foreach my $part_response_id (@part_response_id) {
                   3028:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 3029:         if ($part eq $partid) {
1.375     albertel 3030:             push(@respids,$resp);
1.323     banghart 3031:         }
                   3032:     }
1.318     banghart 3033:     my $result;
1.323     banghart 3034:     foreach my $respid (@respids) {
1.322     albertel 3035: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   3036: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3037: 	next if (!@$files);
1.654     raeburn  3038: 	my $file_counter = 0;
1.313     banghart 3039: 	foreach my $file (@$files) {
1.368     banghart 3040: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  3041:                 $file_counter++;
1.368     banghart 3042:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  3043:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 3044:     	        $file_disp = "$name.$ext";
                   3045:     	        $file = $file_path.$file_disp;
                   3046:     	        $result.=&mt('Return commented version of [_1] to student.',
                   3047:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   3048:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  3049:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 3050: 	    }
1.322     albertel 3051: 	}
1.654     raeburn  3052:         if ($file_counter) {
                   3053:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   3054:                        '<span class="LC_info">'.
                   3055:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   3056:         }
1.313     banghart 3057:     }
1.318     banghart 3058:     return $result;    
1.71      ng       3059: }
1.44      ng       3060: 
1.58      albertel 3061: sub show_problem {
1.382     albertel 3062:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 3063:     my $rendered;
1.382     albertel 3064:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 3065:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 3066:     if ($mode eq 'both' or $mode eq 'text') {
                   3067: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 3068: 						       $env{'request.course.id'},
                   3069: 						       undef,\%form);
1.144     albertel 3070:     }
1.58      albertel 3071:     if ($removeform) {
                   3072: 	$rendered=~s|<form(.*?)>||g;
                   3073: 	$rendered=~s|</form>||g;
1.374     albertel 3074: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 3075:     }
1.144     albertel 3076:     my $companswer;
                   3077:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 3078: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 3079: 	$companswer=
                   3080: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   3081: 						    $env{'request.course.id'},
                   3082: 						    %form);
1.144     albertel 3083:     }
1.58      albertel 3084:     if ($removeform) {
                   3085: 	$companswer=~s|<form(.*?)>||g;
                   3086: 	$companswer=~s|</form>||g;
1.144     albertel 3087: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 3088:     }
1.671     raeburn  3089:     my $renderheading = &mt('View of the problem');
                   3090:     my $answerheading = &mt('Correct answer');
                   3091:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   3092:         my $stu_fullname = $env{'form.fullname'};
                   3093:         if ($stu_fullname eq '') {
                   3094:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3095:         }
                   3096:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   3097:         if ($forwhom ne '') {
                   3098:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   3099:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   3100:         }
                   3101:     }
1.468     albertel 3102:     $rendered=
1.588     bisitz   3103:         '<div class="LC_Box">'
1.671     raeburn  3104:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   3105:        .$rendered
                   3106:        .'</div>';
1.468     albertel 3107:     $companswer=
1.588     bisitz   3108:         '<div class="LC_Box">'
1.671     raeburn  3109:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   3110:        .$companswer
                   3111:        .'</div>';
1.468     albertel 3112:     my $result;
1.144     albertel 3113:     if ($mode eq 'both') {
1.588     bisitz   3114:         $result=$rendered.$companswer;
1.144     albertel 3115:     } elsif ($mode eq 'text') {
1.588     bisitz   3116:         $result=$rendered;
1.144     albertel 3117:     } elsif ($mode eq 'answer') {
1.588     bisitz   3118:         $result=$companswer;
1.144     albertel 3119:     }
1.71      ng       3120:     return $result;
1.58      albertel 3121: }
1.397     albertel 3122: 
1.396     banghart 3123: sub files_exist {
                   3124:     my ($r, $symb) = @_;
                   3125:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   3126:     foreach my $student (@students) {
                   3127:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 3128:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3129: 					      $udom,$uname);
1.792     raeburn  3130:         my ($string)= &get_last_submission(\%record);
1.397     albertel 3131:         foreach my $submission (@$string) {
                   3132:             my ($partid,$respid) =
                   3133: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3134:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   3135: 					   \%record);
                   3136:             return 1 if (@$files);
1.396     banghart 3137:         }
                   3138:     }
1.397     albertel 3139:     return 0;
1.396     banghart 3140: }
1.397     albertel 3141: 
1.394     banghart 3142: sub download_all_link {
                   3143:     my ($r,$symb) = @_;
1.621     www      3144:     unless (&files_exist($r, $symb)) {
1.766     raeburn  3145:         $r->print(&mt('There are currently no submitted documents.'));
                   3146:         return;
1.621     www      3147:     }
1.395     albertel 3148:     my $all_students = 
                   3149: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   3150: 
                   3151:     my $parts =
                   3152: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   3153: 
1.394     banghart 3154:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  3155:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   3156:                              'cgi.'.$identifier.'.symb' => $symb,
                   3157:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 3158:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   3159: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      3160:     return;
                   3161: }
                   3162: 
                   3163: sub submit_download_link {
                   3164:     my ($request,$symb) = @_;
                   3165:     if (!$symb) { return ''; }
1.750     raeburn  3166:     my $res_error;
1.773     raeburn  3167:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   3168:         &response_type($symb,\$res_error);
                   3169:     if ($res_error) {
                   3170:         $request->print(&mt('An error occurred retrieving response types'));
                   3171:         return;
                   3172:     }
                   3173:     unless ($numessay) {
                   3174:         $request->print(&mt('No essayresponse items found'));
                   3175:         return;
1.750     raeburn  3176:     }
1.773     raeburn  3177:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3178:     if (@chosenparts) {
                   3179:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   3180:                                           undef,undef,1));
1.750     raeburn  3181:     }
1.773     raeburn  3182:     if ($numessay) {
1.750     raeburn  3183:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   3184:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3185:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   3186:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   3187:         if (ref($fullname) eq 'HASH') {
                   3188:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   3189:             if (@students) {
                   3190:                 @{$env{'form.stuinfo'}} = @students;
1.773     raeburn  3191:                 if ($numdropbox) {
1.750     raeburn  3192:                     &download_all_link($request,$symb);
1.773     raeburn  3193:                 } else {
                   3194:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  3195:                 }
1.773     raeburn  3196: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  3197: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   3198:             } else {
                   3199:                 $request->print(&mt('No students match the criteria you selected'));
                   3200:             }
                   3201:         } else {
                   3202:             $request->print(&mt('Could not retrieve student information'));
                   3203:         }
                   3204:     } else {
                   3205:         $request->print(&mt('No essayresponse items found'));
                   3206:     }
                   3207:     return;
1.394     banghart 3208: }
1.395     albertel 3209: 
1.432     banghart 3210: sub build_section_inputs {
                   3211:     my $section_inputs;
                   3212:     if ($env{'form.section'} eq '') {
                   3213:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   3214:     } else {
                   3215:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 3216:         foreach my $section (@sections) {
1.432     banghart 3217:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   3218:         }
                   3219:     }
                   3220:     return $section_inputs;
                   3221: }
                   3222: 
1.44      ng       3223: # --------------------------- show submissions of a student, option to grade 
                   3224: sub submission {
1.773     raeburn  3225:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 3226:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   3227:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   3228:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3229:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      3230: 
1.324     albertel 3231:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773     raeburn  3232:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  3233:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  3234:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 3235: 
                   3236:     if (!&canview($usec)) {
1.712     bisitz   3237:         $request->print(
                   3238:             '<span class="LC_warning">'.
1.713     bisitz   3239:             &mt('Unable to view requested student.').
1.712     bisitz   3240:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3241:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3242:             '</span>');
1.104     albertel 3243: 	return;
                   3244:     }
                   3245: 
1.773     raeburn  3246:     my $res_error;
                   3247:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   3248:         &response_type($symb,\$res_error);
                   3249:     if ($res_error) {
                   3250:         $request->print(&navmap_errormsg());
                   3251:         return;
                   3252:     }
                   3253: 
1.257     albertel 3254:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  3255:     unless ($is_tool) { 
                   3256:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   3257:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   3258:     }
1.773     raeburn  3259:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   3260:         $env{'form.compmsg'} = 1;
                   3261:     }
1.257     albertel 3262:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 3263:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   3264: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       3265: 	'/check.gif" height="16" border="0" />';
1.41      ng       3266: 
                   3267:     # header info
                   3268:     if ($counter == 0) {
1.773     raeburn  3269:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3270:         if (@chosenparts) {
                   3271:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   3272:         } elsif ($divforres) {
                   3273:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   3274:         } else {
                   3275:             $request->print('<br clear="all" />');
                   3276:         }
1.41      ng       3277: 	&sub_page_js($request);
1.773     raeburn  3278:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   3279: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       3280: 
1.44      ng       3281: 	# option to display problem, only once else it cause problems 
                   3282:         # with the form later since the problem has a form.
1.257     albertel 3283: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 3284: 	    my $mode;
1.257     albertel 3285: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 3286: 		$mode='both';
1.257     albertel 3287: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 3288: 		$mode='text';
1.257     albertel 3289: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 3290: 		$mode='answer';
                   3291: 	    }
1.329     albertel 3292: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 3293: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       3294: 	}
1.441     www      3295: 
1.41      ng       3296: 	my %keyhash = ();
1.773     raeburn  3297: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       3298: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 3299: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   3300: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773     raeburn  3301: 	}
                   3302: 	# kwclr is the only variable that is guaranteed not to be blank
                   3303: 	# if this subroutine has been called once.
                   3304: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 3305: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3306: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   3307: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   3308: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   3309: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773     raeburn  3310: 	}
                   3311: 	if ($env{'form.compmsg'}) {
                   3312: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      3313: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 3314: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       3315: 	}
1.773     raeburn  3316: 
1.257     albertel 3317: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 3318: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 3319: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       3320: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 3321: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       3322: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       3323: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       3324: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   3325: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 3326: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3327: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   3328: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   3329: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773     raeburn  3330: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 3331: 			&build_section_inputs().
1.326     albertel 3332: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       3333: 			'<input type="hidden" name="NCT"'.
1.257     albertel 3334: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773     raeburn  3335: 	if ($env{'form.compmsg'}) {
                   3336: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   3337: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   3338: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   3339: 	}
                   3340: 	if ($numessay) {
1.257     albertel 3341: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   3342: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   3343: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773     raeburn  3344: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       3345: 	}
1.773     raeburn  3346: 
1.41      ng       3347: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 3348: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       3349: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       3350: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 3351: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       3352: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       3353: 		'" />'."\n".
                   3354: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       3355: 	    $cts++;
                   3356: 	}
                   3357: 	$request->print($prnmsg);
1.32      ng       3358: 
1.773     raeburn  3359: 	if ($numessay) {
1.652     raeburn  3360: 
                   3361:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   3362:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  3363:                           keyw => 'Keyword Options',
1.655     raeburn  3364:                           list => 'List',
1.652     raeburn  3365:                           past => 'Paste Selection to List',
1.661     www      3366:                           high => 'Highlight Attribute',
1.773     raeburn  3367:                      );
1.88      www      3368: #
                   3369: # Print out the keyword options line
                   3370: #
1.718     bisitz   3371: 	    $request->print(
                   3372:                 '<div class="LC_columnSection">'
                   3373:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   3374:                .&Apache::lonhtmlcommon::funclist_from_array(
                   3375:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   3376:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   3377:  class="page">'.$lt{'past'}.'</a>',
                   3378:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   3379:                     {legend => $lt{'keyw'}})
                   3380:                .'</fieldset></div>'
                   3381:             );
                   3382: 
1.88      www      3383: #
                   3384: # Load the other essays for similarity check
                   3385: #
1.753     raeburn  3386:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   3387:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3388:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3389:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3390:                 if ($cdom ne '' && $cnum ne '') {
                   3391:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   3392:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   3393:                         my $apath = $1.'_'.$id;
                   3394:                         $apath=~s/\W/\_/gs;
                   3395:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   3396:                     }
                   3397:                 }
                   3398:             } else {
                   3399: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   3400: 	        $apath=&escape($apath);
                   3401: 	        $apath=~s/\W/\_/gs;
                   3402:                 &init_old_essays($symb,$apath,$adom,$aname);
                   3403:             }
1.41      ng       3404:         }
                   3405:     }
1.44      ng       3406: 
1.441     www      3407: # This is where output for one specific student would start
1.592     bisitz   3408:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   3409:     $request->print(
                   3410:         "\n\n"
                   3411:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   3412:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   3413:        ."\n"
                   3414:     );
1.441     www      3415: 
1.592     bisitz   3416:     # Show additional functions if allowed
                   3417:     if ($perm{'vgr'}) {
                   3418:         $request->print(
                   3419:             &Apache::loncommon::track_student_link(
1.708     bisitz   3420:                 'View recent activity',
1.592     bisitz   3421:                 $uname,$udom,'check')
                   3422:            .' '
                   3423:         );
                   3424:     }
                   3425:     if ($perm{'opa'}) {
                   3426:         $request->print(
                   3427:             &Apache::loncommon::pprmlink(
                   3428:                 &mt('Set/Change parameters'),
                   3429:                 $uname,$udom,$symb,'check'));
                   3430:     }
                   3431: 
                   3432:     # Show Problem
1.257     albertel 3433:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 3434: 	my $mode;
1.257     albertel 3435: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 3436: 	    $mode='both';
1.257     albertel 3437: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 3438: 	    $mode='text';
1.257     albertel 3439: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 3440: 	    $mode='answer';
                   3441: 	}
1.329     albertel 3442: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 3443: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 3444:     }
1.144     albertel 3445: 
1.257     albertel 3446:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       3447: 
1.44      ng       3448:     # Display student info
1.41      ng       3449:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   3450: 
1.745     raeburn  3451:     my $boxtitle = &mt('Submissions');
                   3452:     if ($is_tool) {
                   3453:         $boxtitle = &mt('Transactions')
                   3454:     }
1.590     bisitz   3455:     my $result='<div class="LC_Box">'
1.745     raeburn  3456:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       3457:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   3458:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773     raeburn  3459:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   3460:         $result.='<p class="LC_info">'
                   3461:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   3462:                 ."</p>\n";
1.469     albertel 3463:     }
                   3464: 
1.773     raeburn  3465:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 3466:     my $fullname;
                   3467:     my $col_fullnames = [];
1.773     raeburn  3468:     if ($numessay) {
1.464     albertel 3469: 	(my $sub_result,$fullname,$col_fullnames)=
                   3470: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   3471: 				 $counter);
                   3472: 	$result.=$sub_result;
1.41      ng       3473:     }
1.44      ng       3474:     $request->print($result."\n");
1.773     raeburn  3475: 
1.44      ng       3476:     # print student answer/submission
1.773     raeburn  3477:     # Options are (1) Last submission only
                   3478:     #             (2) Last submission (with detailed information for that submission)
                   3479:     #             (3) All transactions (by date)
                   3480:     #             (4) The whole record (with detailed information for all transactions)
                   3481: 
1.793     raeburn  3482:     my ($lastsubonly,$partinfo) =
                   3483:         &show_last_submission($uname,$udom,$symb,$essayurl,$responseType,$env{'form.lastSub'},
                   3484:                               $is_tool,$fullname,\%record,\%coursedesc_by_cid);
                   3485:     $request->print($partinfo);
                   3486:     $request->print($lastsubonly);
                   3487: 
                   3488:     if ($env{'form.lastSub'} eq 'datesub') {
                   3489:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3490: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
                   3491:     }
                   3492:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   3493:         my $identifier = (&canmodify($usec)? $counter : '');
                   3494:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
                   3495: 								 $env{'request.course.id'},
                   3496: 								 $last,'.submission',
                   3497: 								 'Apache::grades::keywords_highlight',
                   3498:                                                                  $usec,$identifier));
                   3499:     }
                   3500:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   3501: 	.$udom.'" />'."\n");
                   3502:     # return if view submission with no grading option
                   3503:     if (!&canmodify($usec)) {
                   3504: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   3505: 	return;
                   3506:     } else {
                   3507: 	$request->print('</div>'."\n");
                   3508:     }
                   3509: 
                   3510:     # grading message center
                   3511: 
                   3512:     if ($env{'form.compmsg'}) {
                   3513:         my $result='<div class="LC_Box">'.
                   3514:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   3515:                    '<div class="LC_grade_message_center_body">';
                   3516:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   3517:         my $msgfor = $givenn.' '.$lastname;
                   3518:         if (scalar(@$col_fullnames) > 0) {
                   3519:             my $lastone = pop(@$col_fullnames);
                   3520:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   3521:         }
                   3522:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   3523:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   3524:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   3525:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   3526:                  ',\''.$msgfor.'\');" target="_self">'.
                   3527:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   3528:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   3529:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   3530:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   3531:                  '<br />&nbsp;('.
                   3532:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   3533:                  '</div></div>';
                   3534:         $request->print($result);
                   3535:     }
                   3536: 
                   3537:     my %seen = ();
                   3538:     my @partlist;
                   3539:     my @gradePartRespid;
                   3540:     my @part_response_id;
                   3541:     if ($is_tool) {
                   3542:         @part_response_id = ([0,'']);
                   3543:     } else {
                   3544:         @part_response_id = &flatten_responseType($responseType);
                   3545:     }
                   3546:     $request->print(
                   3547:         '<div class="LC_Box">'
                   3548:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
                   3549:     );
                   3550:     $request->print(&gradeBox_start());
                   3551:     foreach my $part_response_id (@part_response_id) {
                   3552:     	my ($partid,$respid) = @{ $part_response_id };
                   3553: 	my $part_resp = join('_',@{ $part_response_id });
                   3554: 	next if ($seen{$partid} > 0);
                   3555: 	$seen{$partid}++;
                   3556: 	push(@partlist,$partid);
                   3557: 	push(@gradePartRespid,$partid.'.'.$respid);
                   3558: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
                   3559:     }
                   3560:     $request->print(&gradeBox_end()); # </div>
                   3561:     $request->print('</div>');
                   3562: 
                   3563:     $request->print('<div class="LC_grade_info_links">');
                   3564:     $request->print('</div>');
                   3565: 
                   3566:     $result='<input type="hidden" name="partlist'.$counter.
                   3567: 	'" value="'.(join ":",@partlist).'" />'."\n";
                   3568:     $result.='<input type="hidden" name="gradePartRespid'.
                   3569: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
                   3570:     my $ctr = 0;
                   3571:     while ($ctr < scalar(@partlist)) {
                   3572: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   3573: 	    $partlist[$ctr].'" />'."\n";
                   3574: 	$ctr++;
                   3575:     }
                   3576:     $request->print($result.''."\n");
                   3577: 
                   3578: # Done with printing info for one student
                   3579: 
                   3580:     $request->print('</div>');#LC_grade_show_user
                   3581: 
                   3582: 
                   3583:     # print end of form
                   3584:     if ($counter == $total) {
                   3585:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
                   3586: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
                   3587: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
                   3588: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
                   3589: 	my $ntstu ='<select name="NTSTU">'.
                   3590: 	    '<option>1</option><option>2</option>'.
                   3591: 	    '<option>3</option><option>5</option>'.
                   3592: 	    '<option>7</option><option>10</option></select>'."\n";
                   3593: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
                   3594: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
                   3595:         $endform.=&mt('[_1]student(s)',$ntstu);
                   3596: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
                   3597: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
                   3598: 	    '<input type="button" value="'.&mt('Next').'" '.
                   3599: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
                   3600:         $endform.='<span class="LC_warning">'.
                   3601:                   &mt('(Next and Previous (student) do not save the scores.)').
                   3602:                   '</span>'."\n" ;
                   3603:         $endform.="<input type='hidden' value='".&get_increment().
                   3604:             "' name='increment' />";
                   3605: 	$endform.='</td></tr></table></form>';
                   3606: 	$request->print($endform);
                   3607:     }
                   3608:     return '';
                   3609: }
                   3610: 
                   3611: sub show_last_submission {
                   3612:     my ($uname,$udom,$symb,$essayurl,$responseType,$viewtype,$is_tool,$fullname,
                   3613:         $record,$coursedesc_by_cid) = @_;
1.792     raeburn  3614:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
1.793     raeburn  3615:         &get_last_submission($record,$is_tool);
1.468     albertel 3616: 
1.793     raeburn  3617:     my ($lastsubonly,$partinfo);
1.792     raeburn  3618:     if ($timestamp eq '') {
1.793     raeburn  3619:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>';
1.745     raeburn  3620:     } elsif ($is_tool) {
                   3621:         $lastsubonly =
                   3622:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3623:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$timestamp."</div>\n";
1.702     kruse    3624:     } else {
1.792     raeburn  3625:         my ($shownsubmdate,$showngradedate);
                   3626:         if ($lastsubmittime && $lastgradetime) {
                   3627:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
                   3628:             if ($lastgradetime > $lastsubmittime) {
                   3629:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
                   3630:              }
                   3631:         } else {
                   3632:             $shownsubmdate = $timestamp;
                   3633:         }
1.702     kruse    3634:         $lastsubonly =
                   3635:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3636:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
                   3637:         if ($showngradedate) {
                   3638:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
                   3639:         }
1.702     kruse    3640: 
1.793     raeburn  3641:         my %seenparts;
                   3642:         my @part_response_id = &flatten_responseType($responseType);
                   3643:         foreach my $part (@part_response_id) {
                   3644:             my ($partid,$respid) = @{ $part };
                   3645:             my $display_part=&get_display_part($partid,$symb);
                   3646:             if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   3647:                 if (exists($seenparts{$partid})) { next; }
                   3648:                 $seenparts{$partid}=1;
                   3649:                 $partinfo .=
1.702     kruse    3650:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3651:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   3652:                                '<a href="javascript:viewSubmitter(\''.
                   3653:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   3654:                                '\');" target="_self">'.
                   3655:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
1.793     raeburn  3656:                     '<br />';
                   3657:                 next;
                   3658:             }
                   3659:             my $responsetype = $responseType->{$partid}->{$respid};
                   3660:             if (!exists($record->{"resource.$partid.$respid.submission"})) {
1.702     kruse    3661:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   3662:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3663:                     ' <span class="LC_internal_info">'.
                   3664:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   3665:                     '</span>&nbsp; &nbsp;'.
1.793     raeburn  3666:                     '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   3667:                 next;
                   3668:             }
                   3669:             foreach my $submission (@$string) {
                   3670:                 my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3671:                 if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   3672:                 my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   3673:                 # Similarity check
1.702     kruse    3674:                 my $similar='';
                   3675:                 my ($type,$trial,$rndseed);
                   3676:                 if ($hide eq 'rand') {
                   3677:                     $type = 'randomizetry';
1.793     raeburn  3678:                     $trial = $record->{"resource.$partid.tries"};
                   3679:                     $rndseed = $record->{"resource.$partid.rndseed"};
1.702     kruse    3680:                 }
1.793     raeburn  3681:                 if ($env{'form.checkPlag'}) {
                   3682:                     my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   3683:                     &most_similar($uname,$udom,$symb,$subval);
                   3684:                     if ($osim) {
                   3685:                         $osim=int($osim*100.0);
1.702     kruse    3686:                         if ($hide eq 'anon') {
                   3687:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   3688:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   3689:                         } else {
1.793     raeburn  3690:                             $similar='<hr />';
1.753     raeburn  3691:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3692:                                 $similar .= '<h3><span class="LC_warning">'.
                   3693:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   3694:                                                 $osim,
                   3695:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3696:                                             '</span></h3>';
                   3697:                             } else {
                   3698:                                 my %old_course_desc;
                   3699:                                 if ($ocrsid ne '') {
1.793     raeburn  3700:                                     if (ref($coursedesc_by_cid->{$ocrsid}) eq 'HASH') {
                   3701:                                         %old_course_desc = %{$coursedesc_by_cid->{$ocrsid}};
1.753     raeburn  3702:                                     } else {
                   3703:                                         my $args;
                   3704:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   3705:                                             $args = {'one_time' => 1};
                   3706:                                         }
                   3707:                                         %old_course_desc =
                   3708:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
1.793     raeburn  3709:                                         $coursedesc_by_cid->{$ocrsid} = \%old_course_desc;
1.753     raeburn  3710:                                     }
                   3711:                                     $similar .=
                   3712:                                         '<h3><span class="LC_warning">'.
                   3713:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   3714:                                             $osim,
                   3715:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   3716:                                             $old_course_desc{'description'},
                   3717:                                             $old_course_desc{'num'},
                   3718:                                             $old_course_desc{'domain'}).
                   3719:                                         '</span></h3>';
                   3720:                                 } else {
                   3721:                                     $similar .=
                   3722:                                         '<h3><span class="LC_warning">'.
                   3723:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   3724:                                             $osim,
                   3725:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3726:                                         '</span></h3>';
                   3727:                                 }
                   3728:                             }
                   3729:                             $similar .= '<blockquote><i>'.
                   3730:                                         &keywords_highlight($oessay).
                   3731:                                         '</i></blockquote><hr />';
1.702     kruse    3732:                         }
1.793     raeburn  3733:                     }
                   3734:                 }
                   3735:                 my $order=&get_order($partid,$respid,$symb,$uname,$udom,
1.702     kruse    3736:                                      undef,$type,$trial,$rndseed);
1.793     raeburn  3737:                 if (($viewtype eq 'lastonly') ||
                   3738:                     ($viewtype eq 'datesub')  ||
                   3739:                     ($viewtype =~ /^(last|all)$/)) {
                   3740:                     my $display_part=&get_display_part($partid,$symb);
1.702     kruse    3741:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   3742:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3743:                         ' <span class="LC_internal_info">'.
                   3744:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   3745:                         '</span>&nbsp; &nbsp;';
1.793     raeburn  3746:                     my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3747:                     if (@$files) {
1.702     kruse    3748:                         if ($hide eq 'anon') {
                   3749:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   3750:                         } else {
                   3751:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   3752:                                         .'<br /><span class="LC_warning">';
                   3753:                             if(@$files == 1) {
                   3754:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  3755:                             } else {
1.702     kruse    3756:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   3757:                             }
1.774     raeburn  3758:                             $lastsubonly .= '</span>';
1.702     kruse    3759:                             foreach my $file (@$files) {
                   3760:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   3761:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  3762:                             }
                   3763:                         }
1.793     raeburn  3764:                         $lastsubonly.='<br />';
1.702     kruse    3765:                     }
                   3766:                     if ($hide eq 'anon') {
1.793     raeburn  3767:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
1.702     kruse    3768:                     } else {
1.774     raeburn  3769:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  3770:                         if ($draft) {
                   3771:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   3772:                         }
                   3773:                         $subval =
1.793     raeburn  3774:                             &cleanRecord($subval,$responsetype,$symb,$partid,
                   3775:                                          $respid,$record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  3776:                         if ($responsetype eq 'essay') {
                   3777:                             $subval =~ s{\n}{<br />}g;
                   3778:                         }
                   3779:                         $lastsubonly.=$subval."\n";
1.702     kruse    3780:                     }
1.774     raeburn  3781:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.793     raeburn  3782:                     $lastsubonly.='</div>';
                   3783:                 }
1.702     kruse    3784:             }
1.773     raeburn  3785:         }
1.793     raeburn  3786:         $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.118     ng       3787:     }
1.793     raeburn  3788:     return ($lastsubonly,$partinfo);
1.38      ng       3789: }
                   3790: 
1.464     albertel 3791: sub check_collaborators {
                   3792:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   3793:     my ($result,@col_fullnames);
                   3794:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   3795:     foreach my $part (keys(%$handgrade)) {
                   3796: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   3797: 					'.maxcollaborators',
                   3798: 					$symb,$udom,$uname);
                   3799: 	next if ($ncol <= 0);
                   3800: 	$part =~ s/\_/\./g;
                   3801: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   3802: 	my (@good_collaborators, @bad_collaborators);
                   3803: 	foreach my $possible_collaborator
1.630     www      3804: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 3805: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   3806: 	    next if ($possible_collaborator eq '');
1.631     www      3807: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 3808: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   3809: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   3810: 	    # Doing this grep allows 'fuzzy' specification
                   3811: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   3812: 			       keys(%$classlist));
                   3813: 	    if (! scalar(@matches)) {
                   3814: 		push(@bad_collaborators, $possible_collaborator);
                   3815: 	    } else {
                   3816: 		push(@good_collaborators, @matches);
                   3817: 	    }
                   3818: 	}
                   3819: 	if (scalar(@good_collaborators) != 0) {
1.630     www      3820: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 3821: 	    foreach my $name (@good_collaborators) {
                   3822: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   3823: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      3824: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 3825: 	    }
1.630     www      3826: 	    $result.='</ol><br />'."\n";
1.466     albertel 3827: 	    my ($part)=split(/\./,$part);
1.464     albertel 3828: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   3829: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   3830: 		"\n";
                   3831: 	}
                   3832: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 3833: 	    $result.='<div class="LC_warning">';
1.464     albertel 3834: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   3835: 	    $result .= '</div>';
                   3836: 	}         
                   3837: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 3838: 	    $result .= '<div class="LC_warning">';
1.464     albertel 3839: 	    $result .= &mt('This student has submitted too many '.
                   3840: 		'collaborators.  Maximum is [_1].',$ncol);
                   3841: 	    $result .= '</div>';
                   3842: 	}
                   3843:     }
                   3844:     return ($result,$fullname,\@col_fullnames);
                   3845: }
                   3846: 
1.44      ng       3847: #--- Retrieve the last submission for all the parts
1.38      ng       3848: sub get_last_submission {
1.745     raeburn  3849:     my ($returnhash,$is_tool)=@_;
1.792     raeburn  3850:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
1.119     ng       3851:     if ($$returnhash{'version'}) {
1.46      ng       3852: 	my %lasthash=();
1.792     raeburn  3853:         my %prevsolved=();
                   3854:         my %solved=();
                   3855: 	my $version;
1.119     ng       3856: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.792     raeburn  3857:             my %handgraded = ();
1.397     albertel 3858: 	    foreach my $key (sort(split(/\:/,
                   3859: 					$$returnhash{$version.':keys'}))) {
                   3860: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
1.792     raeburn  3861:                 if ($key =~ /\.([^.]+)\.regrader$/) {
                   3862:                     $handgraded{$1} = 1;
                   3863:                 } elsif ($key =~ /\.portfiles$/) {
                   3864:                     if (($$returnhash{$version.':'.$key} ne '') &&
                   3865:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
                   3866:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3867:                     }
                   3868:                 } elsif ($key =~ /\.submission$/) {
                   3869:                     if ($$returnhash{$version.':'.$key} ne '') {
                   3870:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3871:                     }
                   3872:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
                   3873:                     $prevsolved{$1} = $solved{$1};
                   3874:                     $solved{$1} = $lasthash{$key};
                   3875:                 }
                   3876:             }
                   3877:             foreach my $partid (keys(%handgraded)) {
                   3878:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
                   3879:                     (($solved{$partid} eq 'incorrect_by_override') ||
                   3880:                      ($solved{$partid} eq 'correct_by_override'))) {
                   3881:                     $lastgradetime = $$returnhash{$version.':timestamp'};
                   3882:                 }
                   3883:                 if ($solved{$partid} ne '') {
                   3884:                     $prevsolved{$partid} = $solved{$partid};
                   3885:                 }
1.46      ng       3886: 	    }
                   3887: 	}
1.795     raeburn  3888: #
                   3889: # Timestamp is for last transaction for this resource, which does not
                   3890: # necessarily correspond to the time of last submission for problem (or part).
                   3891: #
                   3892:         if ($lasthash{'timestamp'} ne '') {
                   3893:             $timestamp = &Apache::lonlocal::locallocaltime($lasthash{'timestamp'});
                   3894:         }
1.640     raeburn  3895:         my (%typeparts,%randombytry);
1.596     raeburn  3896:         my $showsurv = 
                   3897:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   3898:         foreach my $key (sort(keys(%lasthash))) {
                   3899:             if ($key =~ /\.type$/) {
                   3900:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  3901:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   3902:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  3903:                     my ($ign,@parts) = split(/\./,$key);
                   3904:                     pop(@parts);
1.641     raeburn  3905:                     my $id = join('.',@parts);
1.640     raeburn  3906:                     if ($lasthash{$key} eq 'randomizetry') {
                   3907:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   3908:                     } else {
                   3909:                         unless ($showsurv) {
                   3910:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   3911:                         }
1.596     raeburn  3912:                     }
                   3913:                     delete($lasthash{$key});
                   3914:                 }
                   3915:             }
                   3916:         }
                   3917:         my @hidden = keys(%typeparts);
1.640     raeburn  3918:         my @randomize = keys(%randombytry);
1.397     albertel 3919: 	foreach my $key (keys(%lasthash)) {
                   3920: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  3921:             my $hide;
                   3922:             if (@hidden) {
                   3923:                 foreach my $id (@hidden) {
                   3924:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  3925:                         $hide = 'anon';
1.596     raeburn  3926:                         last;
                   3927:                     }
                   3928:                 }
                   3929:             }
1.640     raeburn  3930:             unless ($hide) {
                   3931:                 if (@randomize) {
1.732     raeburn  3932:                     foreach my $id (@randomize) {
1.640     raeburn  3933:                         if ($key =~ /^\Q$id\E/) {
                   3934:                             $hide = 'rand';
                   3935:                             last;
                   3936:                         }
                   3937:                     }
                   3938:                 }
                   3939:             }
1.397     albertel 3940: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  3941: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   3942:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   3943:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   3944:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       3945: 	}
                   3946:     }
1.397     albertel 3947:     if (!@string) {
1.745     raeburn  3948:         my $msg;
                   3949:         if ($is_tool) {
1.747     raeburn  3950:             $msg = &mt('No grade passed back.');
1.745     raeburn  3951:         } else {
                   3952:             $msg = &mt('Nothing submitted - no attempts.');
                   3953:         }
1.397     albertel 3954: 	$string[0] =
1.745     raeburn  3955: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 3956:     }
1.792     raeburn  3957:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       3958: }
1.35      ng       3959: 
1.44      ng       3960: #--- High light keywords, with style choosen by user.
1.38      ng       3961: sub keywords_highlight {
1.44      ng       3962:     my $string    = shift;
1.257     albertel 3963:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   3964:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       3965:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 3966:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 3967:     foreach my $keyword (@keylist) {
                   3968: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       3969:     }
                   3970:     return $string;
1.38      ng       3971: }
1.36      ng       3972: 
1.671     raeburn  3973: # For Tasks provide a mechanism to display previous version for one specific student
                   3974: 
                   3975: sub show_previous_task_version {
                   3976:     my ($request,$symb) = @_;
                   3977:     if ($symb eq '') {
1.717     bisitz   3978:         $request->print(
                   3979:             '<span class="LC_error">'.
                   3980:             &mt('Unable to handle ambiguous references.').
                   3981:             '</span>');
1.671     raeburn  3982:         return '';
                   3983:     }
                   3984:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3985:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3986:     if (!&canview($usec)) {
1.712     bisitz   3987:         $request->print(
                   3988:             '<span class="LC_warning">'.
1.713     bisitz   3989:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   3990:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3991:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3992:             '</span>');
1.671     raeburn  3993:         return;
                   3994:     }
                   3995:     my $mode = 'both';
                   3996:     my $isTask = ($symb =~/\.task$/);
                   3997:     if ($isTask) {
                   3998:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   3999:             if ($env{'form.fullname'} eq '') {
                   4000:                 $env{'form.fullname'} =
                   4001:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   4002:             }
                   4003:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   4004:             $request->print("\n\n".
                   4005:                             '<div class="LC_grade_show_user">'.
                   4006:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   4007:                             '</h2>'."\n");
                   4008:             &Apache::lonxml::clear_problem_counter();
                   4009:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   4010:                             {'previousversion' => $env{'form.previousversion'} }));
                   4011:             $request->print("\n</div>");
                   4012:         }
                   4013:     }
                   4014:     return;
                   4015: }
                   4016: 
                   4017: sub choose_task_version_form {
                   4018:     my ($symb,$uname,$udom,$nomenu) = @_;
                   4019:     my $isTask = ($symb =~/\.task$/);
                   4020:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   4021:     if ($isTask) {
                   4022:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4023:                                               $udom,$uname);
                   4024:         if (($record{'resource.0.version'} eq '') ||
                   4025:             ($record{'resource.0.version'} < 2)) {
                   4026:             return ($record{'resource.0.version'},
                   4027:                     $record{'resource.0.version'},$result,$js);
                   4028:         } else {
                   4029:             $current = $record{'resource.0.version'};
                   4030:         }
                   4031:         if ($env{'form.previousversion'}) {
                   4032:             $displayed = $env{'form.previousversion'};
                   4033:             $rowtitle = &mt('Choose another version:')
                   4034:         } else {
                   4035:             $displayed = $current;
                   4036:             $rowtitle = &mt('Show earlier version:');
                   4037:         }
                   4038:         $result = '<div class="LC_left_float">';
                   4039:         my $list;
                   4040:         my $numversions = 0;
                   4041:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   4042:             if ($i == $current) {
                   4043:                 if (!$env{'form.previousversion'} || $nomenu) {
                   4044:                     next;
                   4045:                 } else {
                   4046:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   4047:                     $numversions ++;
                   4048:                 }
                   4049:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   4050:                 unless ($i == $env{'form.previousversion'}) {
                   4051:                     $numversions ++;
                   4052:                 }
                   4053:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   4054:             }
                   4055:         }
                   4056:         if ($numversions) {
                   4057:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   4058:             $result .=
                   4059:                 '<form name="getprev" method="post" action=""'.
                   4060:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   4061:                 &Apache::loncommon::start_data_table().
                   4062:                 &Apache::loncommon::start_data_table_row().
                   4063:                 '<th align="left">'.$rowtitle.'</th>'.
                   4064:                 '<td><select name="version">'.
                   4065:                 '<option>'.&mt('Select').'</option>'.
                   4066:                 $list.
                   4067:                 '</select></td>'.
                   4068:                 &Apache::loncommon::end_data_table_row();
                   4069:             unless ($nomenu) {
                   4070:                 $result .= &Apache::loncommon::start_data_table_row().
                   4071:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   4072:                 '<td><span class="LC_nobreak">'.
                   4073:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   4074:                 &mt('Yes').'</label>'.
                   4075:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   4076:                 '</span></td>'.
                   4077:                 &Apache::loncommon::end_data_table_row();
                   4078:             }
                   4079:             $result .=
                   4080:                 &Apache::loncommon::start_data_table_row().
                   4081:                 '<th align="left">&nbsp;</th>'.
                   4082:                 '<td>'.
                   4083:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   4084:                 '</td>'.
                   4085:                 &Apache::loncommon::end_data_table_row().
                   4086:                 &Apache::loncommon::end_data_table().
                   4087:                 '</form>';
                   4088:             $js = &previous_display_javascript($nomenu,$current);
                   4089:         } elsif ($displayed && $nomenu) {
                   4090:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   4091:         } else {
                   4092:             $result .= &mt('No previous versions to show for this student');
                   4093:         }
                   4094:         $result .= '</div>';
                   4095:     }
                   4096:     return ($current,$displayed,$result,$js);
                   4097: }
                   4098: 
                   4099: sub previous_display_javascript {
                   4100:     my ($nomenu,$current) = @_;
                   4101:     my $js = <<"JSONE";
                   4102: <script type="text/javascript">
                   4103: // <![CDATA[
                   4104: function previousVersion(uname,udom,symb) {
                   4105:     var current = '$current';
                   4106:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   4107:     var prevstr = new RegExp("^\\\\d+\$");
                   4108:     if (!prevstr.test(version)) {
                   4109:         return false;
                   4110:     }
                   4111:     var url = '';
                   4112:     if (version == current) {
                   4113:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   4114:     } else {
                   4115:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   4116:     }
                   4117: JSONE
                   4118:     if ($nomenu) {
                   4119:         $js .= <<"JSTWO";
                   4120:     document.location.href = url;
                   4121: JSTWO
                   4122:     } else {
                   4123:         $js .= <<"JSTHREE";
                   4124:     var newwin = 0;
                   4125:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   4126:         if (document.getprev.prevwin[i].checked == true) {
                   4127:             newwin = document.getprev.prevwin[i].value;
                   4128:         }
                   4129:     }
                   4130:     if (newwin == 1) {
                   4131:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   4132:         url = url+'&inhibitmenu=yes';
                   4133:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   4134:             previousWin = window.open(url,'',options,1);
                   4135:         } else {
                   4136:             previousWin.location.href = url;
                   4137:         }
                   4138:         previousWin.focus();
                   4139:         return false;
                   4140:     } else {
                   4141:         document.location.href = url;
                   4142:         return false;
                   4143:     }
                   4144: JSTHREE
                   4145:     }
                   4146:     $js .= <<"ENDJS";
                   4147:     return false;
                   4148: }
                   4149: // ]]>
                   4150: </script>
                   4151: ENDJS
                   4152: 
                   4153: }
                   4154: 
1.44      ng       4155: #--- Called from submission routine
1.38      ng       4156: sub processHandGrade {
1.608     www      4157:     my ($request,$symb) = @_;
1.324     albertel 4158:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 4159:     my $button = $env{'form.gradeOpt'};
                   4160:     my $ngrade = $env{'form.NCT'};
                   4161:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 4162:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4163:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.786     raeburn  4164:     my ($res_error,%queueable);
                   4165:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   4166:     if ($res_error) {
                   4167:         $request->print(&navmap_errormsg());
                   4168:         return;
                   4169:     } else {
                   4170:         foreach my $part (@{$partlist}) {
                   4171:             if (ref($responseType->{$part}) eq 'HASH') {
                   4172:                 foreach my $id (keys(%{$responseType->{$part}})) {
                   4173:                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   4174:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   4175:                         $queueable{$part} = 1;
                   4176:                         last;
                   4177:                     }
                   4178:                 }
                   4179:             }
                   4180:         }
                   4181:     }
1.301     albertel 4182: 
1.44      ng       4183:     if ($button eq 'Save & Next') {
1.798     raeburn  4184:         my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   4185:         my (%skip_passback,%pbsave,%pbcollab);
1.44      ng       4186: 	my $ctr = 0;
                   4187: 	while ($ctr < $ngrade) {
1.257     albertel 4188: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  4189: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
1.798     raeburn  4190:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable,\%needpb,\%skip_passback,\%pbsave);
1.71      ng       4191: 	    if ($errorflag eq 'no_score') {
                   4192: 		$ctr++;
                   4193: 		next;
                   4194: 	    }
1.104     albertel 4195: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   4196: 		$request->print(
                   4197:                     '<span class="LC_error">'
                   4198:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   4199:                    .'</span>');
1.104     albertel 4200: 		$ctr++;
                   4201: 		next;
                   4202: 	    }
1.726     raeburn  4203:             if ($numhidden) {
                   4204:                 $request->print(
                   4205:                     '<span class="LC_info">'
                   4206:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   4207:                    .'</span><br />');
                   4208:             }
1.257     albertel 4209: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       4210: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 4211: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   4212:             my ($feedurl,$showsymb) =
                   4213: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   4214: 	    my $messagetail;
1.62      albertel 4215: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      4216: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      4217: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  4218: 		$subject.=' ['.$restitle.']';
1.44      ng       4219: 		my (@msgnum) = split(/,/,$includemsg);
                   4220: 		foreach (@msgnum) {
1.257     albertel 4221: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       4222: 		}
1.80      ng       4223: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      4224: 		if ($env{'form.withgrades'.$ctr}) {
                   4225: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  4226: 		    $messagetail = " for <a href=\"".
1.605     www      4227: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  4228: 		}
                   4229: 		$msgstatus = 
                   4230:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   4231: 						     $message.$messagetail,
1.418     albertel 4232:                                                      undef,$feedurl,undef,
1.386     raeburn  4233:                                                      undef,undef,$showsymb,
                   4234:                                                      $restitle);
1.574     bisitz   4235: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  4236: 				$msgstatus.'<br />');
1.44      ng       4237: 	    }
1.257     albertel 4238: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 4239: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 4240: 		foreach my $collabstr (@collabstrs) {
                   4241: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 4242: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 4243: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 4244: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.798     raeburn  4245: 					   $env{'form.unamedom'.$ctr},$part,\%queueable,\%needpb,\%skip_passback,%pbsave);
1.150     albertel 4246: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 4247: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 4248: 			    next;
1.798     raeburn  4249: 			} else {
                   4250:                             $pbcollab{$collaborator}{$part} = [$pts,$wgt];
                   4251:                             if ($message ne '') {
1.800     raeburn  4252: 			        my ($baseurl,$showsymb) = 
                   4253: 				    &get_feedurl_and_symb($symb,$collaborator,
1.801   ! raeburn  4254: 						          $udom);
1.800     raeburn  4255: 			        if ($env{'form.withgrades'.$ctr}) {
                   4256: 				    $messagetail = " for <a href=\"".
                   4257:                                         $baseurl."?symb=$showsymb\">$restitle</a>";
                   4258: 			        }
                   4259: 			        $msgstatus =
                   4260: 				    &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.150     albertel 4261: 			    }
1.800     raeburn  4262: 		        }
1.44      ng       4263: 		    }
                   4264: 		}
                   4265: 	    }
                   4266: 	    $ctr++;
                   4267: 	}
1.798     raeburn  4268:         if ((keys(%pbcollab)) && (keys(%needpb))) {
                   4269:             # FIXME passback scores for collaborators
                   4270:         }
1.44      ng       4271:     }
                   4272: 
1.773     raeburn  4273:     my %keyhash = ();
                   4274:     if ($numessay) {
1.119     ng       4275: 	# Keywords sorted in alphabatical order
1.257     albertel 4276: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   4277: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  4278: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 4279: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   4280: 	$env{'form.keywords'} = join(' ',@keywords);
                   4281: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   4282: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   4283: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   4284: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   4285: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  4286:     }
1.119     ng       4287: 
1.773     raeburn  4288:     if ($env{'form.compmsg'}) {
1.119     ng       4289: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 4290: 	# New messages are saved in env for the next student.
1.119     ng       4291: 	# All messages are saved in nohist_handgrade.db
                   4292: 	my ($ctr,$idx) = (1,1);
1.257     albertel 4293: 	while ($ctr <= $env{'form.savemsgN'}) {
                   4294: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   4295: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       4296: 		$idx++;
                   4297: 	    }
                   4298: 	    $ctr++;
1.41      ng       4299: 	}
1.119     ng       4300: 	$ctr = 0;
                   4301: 	while ($ctr < $ngrade) {
1.257     albertel 4302: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  4303: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4304: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4305: 	        $idx++;
1.119     ng       4306: 	    }
                   4307: 	    $ctr++;
1.41      ng       4308: 	}
1.257     albertel 4309: 	$env{'form.savemsgN'} = --$idx;
                   4310: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       4311:     }
1.773     raeburn  4312:     if (($numessay) || ($env{'form.compmsg'})) {
                   4313:         my $putresult = &Apache::lonnet::put
                   4314:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   4315:     }
                   4316: 
1.44      ng       4317:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 4318:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   4319:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       4320: 	my ($ctr,$total) = (0,0);
                   4321: 	while ($ctr < $ngrade) {
1.257     albertel 4322: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       4323: 	    $ctr++;
                   4324: 	}
1.257     albertel 4325: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       4326: 	$ctr = 0;
                   4327: 	while ($ctr < $total) {
1.257     albertel 4328: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   4329: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   4330: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      4331: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       4332: 	    $ctr++;
                   4333: 	}
                   4334: 	return '';
                   4335:     }
1.36      ng       4336: 
1.44      ng       4337:     # Get the next/previous one or group of students
1.257     albertel 4338:     my $firststu = $env{'form.unamedom0'};
                   4339:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       4340:     my $ctr = 2;
1.41      ng       4341:     while ($laststu eq '') {
1.257     albertel 4342: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       4343: 	$ctr++;
                   4344: 	$laststu = $firststu if ($ctr > $ngrade);
                   4345:     }
1.44      ng       4346: 
1.41      ng       4347:     my (@parsedlist,@nextlist);
                   4348:     my ($nextflg) = 0;
1.524     raeburn  4349:     foreach my $item (sort 
1.294     albertel 4350: 	     {
                   4351: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4352: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4353: 		 }
                   4354: 		 return $a cmp $b;
                   4355: 	     } (keys(%$fullname))) {
1.41      ng       4356: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  4357: 	    push(@parsedlist,$item);
1.41      ng       4358: 	}
1.524     raeburn  4359: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       4360: 	if ($button eq 'Previous') {
1.524     raeburn  4361: 	    last if ($item eq $firststu);
                   4362: 	    push(@parsedlist,$item);
1.41      ng       4363: 	}
                   4364:     }
                   4365:     $ctr = 0;
                   4366:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   4367:     foreach my $student (@parsedlist) {
1.257     albertel 4368: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       4369: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 4370: 	
                   4371: 	if ($submitonly eq 'queued') {
                   4372: 	    my %queue_status = 
                   4373: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4374: 							$udom,$uname);
                   4375: 	    next if (!defined($queue_status{'gradingqueue'}));
                   4376: 	}
                   4377: 
1.156     albertel 4378: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 4379: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 4380: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 4381: 	    my $submitted = 0;
1.248     albertel 4382: 	    my $ungraded = 0;
                   4383: 	    my $incorrect = 0;
1.524     raeburn  4384: 	    foreach my $item (keys(%status)) {
                   4385: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   4386: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   4387: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   4388: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 4389: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   4390: 		    $submitted = 0;
                   4391: 		}
1.41      ng       4392: 	    }
1.156     albertel 4393: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   4394: 				     $submitonly eq 'incorrect' ||
                   4395: 				     $submitonly eq 'graded'));
1.248     albertel 4396: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   4397: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       4398: 	}
1.524     raeburn  4399: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       4400: 	last if ($ctr == $ntstu);
1.41      ng       4401: 	$ctr++;
                   4402:     }
1.36      ng       4403: 
1.41      ng       4404:     $ctr = 0;
                   4405:     my $total = scalar(@nextlist)-1;
1.39      ng       4406: 
1.524     raeburn  4407:     foreach (sort(@nextlist)) {
1.41      ng       4408: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 4409: 	$env{'form.student'}  = $uname;
                   4410: 	$env{'form.userdom'}  = $udom;
                   4411: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      4412: 	&submission($request,$ctr,$total,$symb);
1.41      ng       4413: 	$ctr++;
                   4414:     }
                   4415:     if ($total < 0) {
1.653     raeburn  4416: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       4417: 	$request->print($the_end);
                   4418:     }
                   4419:     return '';
1.38      ng       4420: }
1.36      ng       4421: 
1.44      ng       4422: #---- Save the score and award for each student, if changed
1.38      ng       4423: sub saveHandGrade {
1.798     raeburn  4424:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable,$needpb,$skip_passback,$pbsave) = @_;
1.342     banghart 4425:     my @version_parts;
1.104     albertel 4426:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 4427: 					   $env{'request.course.id'});
1.104     albertel 4428:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 4429:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 4430:     my @parts_graded;
1.77      ng       4431:     my %newrecord  = ();
1.726     raeburn  4432:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  4433:     my %aggregate = ();
                   4434:     my $aggregateflag = 0;
1.798     raeburn  4435:     my $sendupdate;
1.726     raeburn  4436:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  4437:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  4438:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  4439:         $totchg += $numchgs;
1.798     raeburn  4440:         if ($numchgs) {
                   4441:             $sendupdate = 1;
                   4442:         }
1.726     raeburn  4443:     }
1.798     raeburn  4444:     my (%weights,%awardeds,%excuseds);
1.301     albertel 4445:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   4446:     foreach my $new_part (@parts) {
1.337     banghart 4447: 	#collaborator ($submi may vary for different parts
1.259     banghart 4448: 	if ($submitter && $new_part ne $part) { next; }
                   4449: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.798     raeburn  4450:         if ($env{'form.WGT'.$newflg.'_'.$new_part} eq '') {
                   4451:             $weights{$symb}{$new_part} = 1;
                   4452:         } else {
                   4453:             $weights{$symb}{$new_part} = $env{'form.WGT'.$newflg.'_'.$new_part};
                   4454:         }
1.125     ng       4455: 	if ($dropMenu eq 'excused') {
1.798     raeburn  4456:             $excuseds{$symb}{$new_part} = 1;
                   4457:             $awardeds{$symb}{$new_part} = '';
1.259     banghart 4458: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   4459: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   4460: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   4461: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 4462: 		}
1.364     banghart 4463: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.798     raeburn  4464:                 $sendupdate = 1;
1.58      albertel 4465: 	    }
1.125     ng       4466: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 4467: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  4468: 	    foreach my $key (keys(%record)) {
1.259     banghart 4469: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 4470: 	    }
1.259     banghart 4471: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4472: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 4473:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   4474: 
                   4475:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   4476: 					       [$new_part]);
                   4477:             my $aggtries =$totaltries;
1.269     raeburn  4478:             if ($last_resets{$new_part}) {
1.270     albertel 4479:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   4480: 					   $new_part);
1.269     raeburn  4481:             }
1.270     albertel 4482: 
                   4483:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  4484:             if ($aggtries > 0) {
1.327     albertel 4485:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  4486:                 $aggregateflag = 1;
                   4487:             }
1.798     raeburn  4488:             $sendupdate = 1;
                   4489:             $excuseds{$symb}{$new_part} = '';
                   4490:             $awardeds{$symb}{$new_part} = '';
1.125     ng       4491: 	} elsif ($dropMenu eq '') {
1.259     banghart 4492: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   4493: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   4494: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   4495: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 4496: 		next;
                   4497: 	    }
1.259     banghart 4498: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   4499: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       4500: 	    my $partial= $pts/$wgt;
1.798     raeburn  4501:             $awardeds{$symb}{$new_part} = $partial;
                   4502:             $excuseds{$symb}{$new_part} = '';
1.259     banghart 4503: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 4504: 		#do not update score for part if not changed.
1.346     banghart 4505:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 4506: 		next;
1.251     banghart 4507: 	    } else {
1.524     raeburn  4508: 	        push(@parts_graded,$new_part);
1.798     raeburn  4509:                 $sendupdate = 1;
1.153     albertel 4510: 	    }
1.259     banghart 4511: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   4512: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 4513: 	    }
1.259     banghart 4514: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       4515: 	    if ($partial == 0) {
1.153     albertel 4516: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   4517: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   4518: 		}
1.41      ng       4519: 	    } else {
1.153     albertel 4520: 		if ($record{$reckey} ne 'correct_by_override') {
                   4521: 		    $newrecord{$reckey} = 'correct_by_override';
                   4522: 		}
                   4523: 	    }	    
                   4524: 	    if ($submitter && 
1.259     banghart 4525: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   4526: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       4527: 	    }
1.259     banghart 4528: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4529: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       4530: 	}
1.259     banghart 4531: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 4532: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   4533: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   4534: 	        $dropMenu eq 'reset status')
                   4535: 	   {
1.524     raeburn  4536: 	    push(@version_parts,$new_part);
1.259     banghart 4537: 	}
1.41      ng       4538:     }
1.301     albertel 4539:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4540:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4541: 
1.344     albertel 4542:     if (%newrecord) {
                   4543:         if (@version_parts) {
1.364     banghart 4544:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   4545:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 4546: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 4547: 	    foreach my $new_part (@version_parts) {
                   4548: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   4549: 				$new_part,\%newrecord);
                   4550: 	    }
1.259     banghart 4551:         }
1.44      ng       4552: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 4553: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 4554: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.786     raeburn  4555: 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       4556:     }
1.269     raeburn  4557:     if ($aggregateflag) {
                   4558:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4559: 			      $cdom,$cnum);
1.269     raeburn  4560:     }
1.798     raeburn  4561:     if (($sendupdate) && (!$submitter)) {
                   4562:         if ((ref($needpb) eq 'HASH') &&
                   4563:             (keys(%{$needpb}))) {
                   4564:             &process_passbacks('handgrade',[$symb],$cdom,$cnum,$domain,$stuname,\%weights,
                   4565:                                \%awardeds,\%excuseds,$needpb,$skip_passback,$pbsave);
                   4566:         }
                   4567:     }
1.726     raeburn  4568:     return ('',$pts,$wgt,$totchg);
                   4569: }
                   4570: 
                   4571: sub makehidden {
1.728     raeburn  4572:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  4573:     return unless (ref($record) eq 'HASH');
                   4574:     my %modified;
                   4575:     my $numchanged = 0;
                   4576:     if (exists($record->{$version.':keys'})) {
                   4577:         my $partsregexp = $parts;
                   4578:         $partsregexp =~ s/,/|/g;
                   4579:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   4580:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   4581:                  my $item = $1;
                   4582:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   4583:                      $modified{$key} = $record->{$version.':'.$key};
                   4584:                  }
                   4585:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   4586:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   4587:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   4588:                 $modified{$key} = $record->{$version.':'.$key};
                   4589:             }
                   4590:         }
                   4591:         if (keys(%modified)) {
                   4592:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  4593:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  4594:                 $numchanged ++;
                   4595:             }
                   4596:         }
                   4597:     }
                   4598:     return $numchanged;
1.36      ng       4599: }
1.322     albertel 4600: 
1.380     albertel 4601: sub check_and_remove_from_queue {
1.786     raeburn  4602:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 4603:     my @ungraded_parts;
                   4604:     foreach my $part (@{$parts}) {
                   4605: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   4606: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   4607: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   4608: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   4609: 		) {
1.786     raeburn  4610:             if ($queueable->{$part}) {
                   4611: 	        push(@ungraded_parts, $part);
                   4612:             }
1.380     albertel 4613: 	}
                   4614:     }
                   4615:     if ( !@ungraded_parts ) {
                   4616: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   4617: 					       $cnum,$domain,$stuname);
                   4618:     }
                   4619: }
                   4620: 
1.337     banghart 4621: sub handback_files {
                   4622:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  4623:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  4624:     my $res_error;
                   4625:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4626:     if ($res_error) {
                   4627:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   4628:         return;
                   4629:     }
1.654     raeburn  4630:     my @handedback;
                   4631:     my $file_msg;
1.375     albertel 4632:     my @part_response_id = &flatten_responseType($responseType);
                   4633:     foreach my $part_response_id (@part_response_id) {
                   4634:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   4635: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  4636:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   4637:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   4638:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   4639:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   4640:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 4641:                     my ($directory,$answer_file) = 
1.654     raeburn  4642:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 4643:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  4644: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 4645: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  4646:                     my $getpropath = 1;
1.773     raeburn  4647:                     my ($dir_list,$listerror) =
1.662     raeburn  4648:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   4649:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  4650: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   4651:                     # fix filename
1.355     banghart 4652:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   4653:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  4654:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 4655:             	                                $save_file_name);
1.337     banghart 4656:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  4657:                         $request->print('<br /><span class="LC_error">'.
                   4658:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  4659:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  4660:                                         '</span>');
1.356     banghart 4661:                     } else {
1.360     banghart 4662:                         # mark the file as read only
1.654     raeburn  4663:                         push(@handedback,$save_file_name);
1.367     albertel 4664: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   4665: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   4666: 			}
                   4667:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  4668: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 4669:                     }
1.686     bisitz   4670:                     $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 4671:                 }
                   4672:             }
                   4673:         }
1.654     raeburn  4674:     }
                   4675:     if (@handedback > 0) {
                   4676:         $request->print('<br />');
                   4677:         my @what = ($symb,$env{'request.course.id'},'handback');
                   4678:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   4679:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   4680:         my ($subject,$message);
                   4681:         if (scalar(@handedback) == 1) {
                   4682:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   4683:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   4684:         } else {
                   4685:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   4686:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   4687:         }
                   4688:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   4689:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   4690:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   4691:         my ($feedurl,$showsymb) =
                   4692:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   4693:         my $restitle = &Apache::lonnet::gettitle($symb);
                   4694:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   4695:         my $msgstatus =
                   4696:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   4697:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   4698:                  $restitle);
                   4699:         if ($msgstatus) {
                   4700:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   4701:         }
                   4702:     }
1.338     banghart 4703:     return;
1.337     banghart 4704: }
                   4705: 
1.418     albertel 4706: sub get_feedurl_and_symb {
                   4707:     my ($symb,$uname,$udom) = @_;
                   4708:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   4709:     $url = &Apache::lonnet::clutter($url);
                   4710:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   4711: 					$symb,$udom,$uname);
                   4712:     if ($encrypturl =~ /^yes$/i) {
                   4713: 	&Apache::lonenc::encrypted(\$url,1);
                   4714: 	&Apache::lonenc::encrypted(\$symb,1);
                   4715:     }
                   4716:     return ($url,$symb);
                   4717: }
                   4718: 
1.313     banghart 4719: sub get_submitted_files {
                   4720:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   4721:     my @files;
                   4722:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   4723:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   4724:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   4725:     	    push(@files,$file_url.$file);
                   4726:         }
                   4727:     }
                   4728:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   4729:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   4730:     }
                   4731:     return (\@files);
                   4732: }
1.322     albertel 4733: 
1.269     raeburn  4734: # ----------- Provides number of tries since last reset.
                   4735: sub get_num_tries {
                   4736:     my ($record,$last_reset,$part) = @_;
                   4737:     my $timestamp = '';
                   4738:     my $num_tries = 0;
                   4739:     if ($$record{'version'}) {
                   4740:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   4741:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   4742:                 $timestamp = $$record{$version.':timestamp'};
                   4743:                 if ($timestamp > $last_reset) {
                   4744:                     $num_tries ++;
                   4745:                 } else {
                   4746:                     last;
                   4747:                 }
                   4748:             }
                   4749:         }
                   4750:     }
                   4751:     return $num_tries;
                   4752: }
                   4753: 
                   4754: # ----------- Determine decrements required in aggregate totals 
                   4755: sub decrement_aggs {
                   4756:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   4757:     my %decrement = (
                   4758:                         attempts => 0,
                   4759:                         users => 0,
                   4760:                         correct => 0
                   4761:                     );
                   4762:     $decrement{'attempts'} = $aggtries;
                   4763:     if ($solvedstatus =~ /^correct/) {
                   4764:         $decrement{'correct'} = 1;
                   4765:     }
                   4766:     if ($aggtries == $totaltries) {
                   4767:         $decrement{'users'} = 1;
                   4768:     }
1.524     raeburn  4769:     foreach my $type (keys(%decrement)) {
1.269     raeburn  4770:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   4771:     }
                   4772:     return;
                   4773: }
                   4774: 
                   4775: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   4776: sub get_last_resets {
1.270     albertel 4777:     my ($symb,$courseid,$partids) =@_;
                   4778:     my %last_resets;
1.269     raeburn  4779:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   4780:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 4781:     my @keys;
                   4782:     foreach my $part (@{$partids}) {
                   4783: 	push(@keys,"$symb\0$part\0resettime");
                   4784:     }
                   4785:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   4786: 				     $cdom,$cname);
                   4787:     foreach my $part (@{$partids}) {
                   4788: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  4789:     }
1.270     albertel 4790:     return %last_resets;
1.269     raeburn  4791: }
                   4792: 
1.251     banghart 4793: # ----------- Handles creating versions for portfolio files as answers
                   4794: sub version_portfiles {
1.343     banghart 4795:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 4796:     my $version_parts = join('|',@$v_flag);
1.343     banghart 4797:     my @returned_keys;
1.255     banghart 4798:     my $parts = join('|', @$parts_graded);
1.277     albertel 4799:     foreach my $key (keys(%$record)) {
1.259     banghart 4800:         my $new_portfiles;
1.263     banghart 4801:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 4802:             my @versioned_portfiles;
1.367     albertel 4803:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  4804:             if (@portfiles) {
                   4805:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   4806:                                                       \@versioned_portfiles);
1.252     banghart 4807:             }
1.343     banghart 4808:             $$record{$key} = join(',',@versioned_portfiles);
                   4809:             push(@returned_keys,$key);
1.251     banghart 4810:         }
1.794     raeburn  4811:     }
                   4812:     return (@returned_keys);
1.305     banghart 4813: }
                   4814: 
1.44      ng       4815: #--------------------------------------------------------------------------------------
                   4816: #
                   4817: #-------------------------- Next few routines handles grading by section or whole class
                   4818: #
                   4819: #--- Javascript to handle grading by section or whole class
1.42      ng       4820: sub viewgrades_js {
                   4821:     my ($request) = shift;
                   4822: 
1.539     riegler  4823:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  4824:     &js_escape(\$alertmsg);
1.597     wenzelju 4825:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       4826:    function writePoint(partid,weight,point) {
1.125     ng       4827: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   4828: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       4829: 	if (point == "textval") {
1.125     ng       4830: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  4831: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4832: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       4833: 		var resetbox = false;
                   4834: 		for (var i=0; i<radioButton.length; i++) {
                   4835: 		    if (radioButton[i].checked) {
                   4836: 			textbox.value = i;
                   4837: 			resetbox = true;
                   4838: 		    }
                   4839: 		}
                   4840: 		if (!resetbox) {
                   4841: 		    textbox.value = "";
                   4842: 		}
                   4843: 		return;
                   4844: 	    }
1.109     matthew  4845: 	    if (parseFloat(point) > parseFloat(weight)) {
                   4846: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4847: 				   ") greater than the weight for the part. Accept?");
                   4848: 		if (resp == false) {
                   4849: 		    textbox.value = "";
                   4850: 		    return;
                   4851: 		}
                   4852: 	    }
1.42      ng       4853: 	    for (var i=0; i<radioButton.length; i++) {
                   4854: 		radioButton[i].checked=false;
1.109     matthew  4855: 		if (parseFloat(point) == i) {
1.42      ng       4856: 		    radioButton[i].checked=true;
                   4857: 		}
                   4858: 	    }
1.41      ng       4859: 
1.42      ng       4860: 	} else {
1.125     ng       4861: 	    textbox.value = parseFloat(point);
1.42      ng       4862: 	}
1.41      ng       4863: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4864: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 4865: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4866: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4867: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4868: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4869: 	    if (saveval != "correct") {
                   4870: 		scorename.value = point;
1.43      ng       4871: 		if (selname[0].selected != true) {
                   4872: 		    selname[0].selected = true;
                   4873: 		}
1.42      ng       4874: 	    }
                   4875: 	}
1.125     ng       4876: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       4877:     }
                   4878: 
                   4879:     function writeRadText(partid,weight) {
1.125     ng       4880: 	var selval   = document.classgrade["SELVAL_"+partid];
                   4881: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      4882:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       4883: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   4884: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       4885: 	    for (var i=0; i<radioButton.length; i++) {
                   4886: 		radioButton[i].checked=false;
                   4887: 
                   4888: 	    }
                   4889: 	    textbox.value = "";
                   4890: 
                   4891: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4892: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4893: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4894: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4895: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4896: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4897: 		if ((saveval != "correct") || override) {
1.42      ng       4898: 		    scorename.value = "";
1.125     ng       4899: 		    if (selval[1].selected) {
                   4900: 			selname[1].selected = true;
                   4901: 		    } else {
                   4902: 			selname[2].selected = true;
                   4903: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   4904: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   4905: 		    }
1.42      ng       4906: 		}
                   4907: 	    }
1.43      ng       4908: 	} else {
                   4909: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4910: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4911: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4912: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4913: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4914: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4915: 		if ((saveval != "correct") || override) {
1.125     ng       4916: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       4917: 		    selname[0].selected = true;
                   4918: 		}
                   4919: 	    }
                   4920: 	}	    
1.42      ng       4921:     }
                   4922: 
                   4923:     function changeSelect(partid,user) {
1.125     ng       4924: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4925: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       4926: 	var point  = textbox.value;
1.125     ng       4927: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       4928: 
1.109     matthew  4929: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4930: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       4931: 	    textbox.value = "";
                   4932: 	    return;
                   4933: 	}
1.109     matthew  4934: 	if (parseFloat(point) > parseFloat(weight)) {
                   4935: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4936: 			       ") greater than the weight of the part. Accept?");
                   4937: 	    if (resp == false) {
                   4938: 		textbox.value = "";
                   4939: 		return;
                   4940: 	    }
                   4941: 	}
1.42      ng       4942: 	selval[0].selected = true;
                   4943:     }
                   4944: 
                   4945:     function changeOneScore(partid,user) {
1.125     ng       4946: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4947: 	if (selval[1].selected || selval[2].selected) {
                   4948: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   4949: 	    if (selval[2].selected) {
                   4950: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   4951: 	    }
1.269     raeburn  4952:         }
1.42      ng       4953:     }
                   4954: 
                   4955:     function resetEntry(numpart) {
                   4956: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       4957: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   4958: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   4959: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   4960: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       4961: 	    for (var i=0; i<radioButton.length; i++) {
                   4962: 		radioButton[i].checked=false;
                   4963: 
                   4964: 	    }
                   4965: 	    textbox.value = "";
                   4966: 	    selval[0].selected = true;
                   4967: 
                   4968: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4969: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4970: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4971: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4972: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   4973: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   4974: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   4975: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4976: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4977: 		if (saveselval == "excused") {
1.43      ng       4978: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       4979: 		} else {
1.43      ng       4980: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       4981: 		}
                   4982: 	    }
1.41      ng       4983: 	}
1.42      ng       4984:     }
                   4985: 
1.41      ng       4986: VIEWJAVASCRIPT
1.42      ng       4987: }
                   4988: 
1.44      ng       4989: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       4990: sub viewgrades {
1.608     www      4991:     my ($request,$symb) = @_;
1.745     raeburn  4992:     my ($is_tool,$toolsymb);
                   4993:     if ($symb =~ /ext\.tool$/) {
                   4994:         $is_tool = 1;
                   4995:         $toolsymb = $symb;
                   4996:     }
1.42      ng       4997:     &viewgrades_js($request);
1.41      ng       4998: 
1.168     albertel 4999:     #need to make sure we have the correct data for later EXT calls, 
                   5000:     #thus invalidate the cache
                   5001:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5002:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5003:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5004:     &Apache::lonnet::clear_EXT_cache_status();
                   5005: 
1.398     albertel 5006:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       5007: 
                   5008:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 5009:     $result.=&jscriptNform($symb);
1.41      ng       5010: 
1.44      ng       5011:     #beginning of class grading form
1.442     banghart 5012:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       5013:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 5014: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       5015: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 5016: 	&build_section_inputs().
1.442     banghart 5017: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       5018: 
1.738     raeburn  5019:     #retrieve selected groups
                   5020:     my (@groups,$group_display);
                   5021:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   5022:     if (grep(/^all$/,@groups)) {
                   5023:         @groups = ('all');
                   5024:     } elsif (grep(/^none$/,@groups)) {
                   5025:         @groups = ('none');
                   5026:     } elsif (@groups > 0) {
                   5027:         $group_display = join(', ',@groups);
                   5028:     }
                   5029: 
                   5030:     my ($common_header,$specific_header,@sections,$section_display);
1.780     raeburn  5031:     if ($env{'request.course.sec'} ne '') {
                   5032:         @sections = ($env{'request.course.sec'});
                   5033:     } else {
                   5034:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   5035:     }
                   5036: 
                   5037: # Check if Save button should be usable
                   5038:     my $disabled = ' disabled="disabled"';
                   5039:     if ($perm{'mgr'}) {
                   5040:         if (grep(/^all$/,@sections)) {
                   5041:             undef($disabled);
                   5042:         } else {
                   5043:             foreach my $sec (@sections) {
                   5044:                 if (&canmodify($sec)) {
                   5045:                     undef($disabled);
                   5046:                     last;
                   5047:                 }
                   5048:             }
                   5049:         }
                   5050:     }
1.738     raeburn  5051:     if (grep(/^all$/,@sections)) {
                   5052:         @sections = ('all');
                   5053:         if ($group_display) {
                   5054:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   5055:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   5056:         } elsif (grep(/^none$/,@groups)) {
                   5057:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   5058:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   5059:         } else {
                   5060: 	    $common_header = &mt('Assign Common Grade to Class');
                   5061:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   5062:         }
                   5063:     } elsif (grep(/^none$/,@sections)) {
                   5064:         @sections = ('none');
                   5065:         if ($group_display) {
                   5066:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   5067:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   5068:         } elsif (grep(/^none$/,@groups)) {
                   5069:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   5070:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   5071:         } else {
                   5072:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   5073: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   5074:         }
                   5075:     } else {
                   5076:         $section_display = join (", ",@sections);
                   5077:         if ($group_display) {
                   5078:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   5079:                                  $section_display,$group_display);
                   5080:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   5081:                                    $section_display,$group_display);
                   5082:         } elsif (grep(/^none$/,@groups)) {
                   5083:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   5084:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   5085:         } else {
                   5086:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   5087: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   5088:         }
                   5089:     }
                   5090:     my %submit_types = &substatus_options();
                   5091:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   5092: 
                   5093:     if ($env{'form.submitonly'} eq 'all') {
                   5094:         $result.= '<h3>'.$common_header.'</h3>';
                   5095:     } else {
1.745     raeburn  5096:         my $text;
                   5097:         if ($is_tool) {
                   5098:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5099:         } else {
                   5100:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5101:         }
                   5102:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 5103:     }
1.738     raeburn  5104:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       5105:     #radio buttons/text box for assigning points for a section or class.
                   5106:     #handles different parts of a problem
1.582     raeburn  5107:     my $res_error;
                   5108:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   5109:     if ($res_error) {
                   5110:         return &navmap_errormsg();
                   5111:     }
1.42      ng       5112:     my %weight = ();
                   5113:     my $ctsparts = 0;
1.45      ng       5114:     my %seen = ();
1.745     raeburn  5115:     my @part_response_id;
                   5116:     if ($is_tool) {
                   5117:         @part_response_id = ([0,'']);
                   5118:     } else {
                   5119:         @part_response_id = &flatten_responseType($responseType);
                   5120:     }
1.375     albertel 5121:     foreach my $part_response_id (@part_response_id) {
                   5122:     	my ($partid,$respid) = @{ $part_response_id };
                   5123: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       5124: 	next if $seen{$partid};
                   5125: 	$seen{$partid}++;
1.42      ng       5126: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   5127: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   5128: 
1.324     albertel 5129: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 5130: 	my $radio.='<table border="0"><tr>';  
1.41      ng       5131: 	my $ctr = 0;
1.42      ng       5132: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 5133: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 5134: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 5135: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       5136: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   5137: 	    $ctr++;
                   5138: 	}
1.485     albertel 5139: 	$radio.='</tr></table>';
                   5140: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   5141: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 5142: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  5143: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   5144:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   5145:             '<select name="SELVAL_'.$partid.'" '.
                   5146:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   5147:                 $weight{$partid}.')"> '.
1.401     albertel 5148: 	    '<option selected="selected"> </option>'.
1.485     albertel 5149: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   5150: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   5151: 	    '</select></td>'.
                   5152:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   5153: 	$line.='<input type="hidden" name="partid_'.
                   5154: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   5155: 	$line.='<input type="hidden" name="weight_'.
                   5156: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   5157: 
                   5158: 	$result.=
                   5159: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   5160: 	    '<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 5161: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       5162: 	$ctsparts++;
1.41      ng       5163:     }
1.474     albertel 5164:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 5165: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 5166:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   5167: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       5168: 
1.44      ng       5169:     #table listing all the students in a section/class
                   5170:     #header of table
1.738     raeburn  5171:     if ($env{'form.submitonly'} eq 'all') {
                   5172:         $result.= '<h3>'.$specific_header.'</h3>';
                   5173:     } else {
1.745     raeburn  5174:         my $text;
                   5175:         if ($is_tool) {
                   5176:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5177:         } else {
                   5178:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5179:         }
                   5180:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  5181:     }
                   5182:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  5183: 	      &Apache::loncommon::start_data_table_header_row().
                   5184: 	      '<th>'.&mt('No.').'</th>'.
                   5185: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  5186:     my $partserror;
                   5187:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5188:     if ($partserror) {
                   5189:         return &navmap_errormsg();
                   5190:     }
1.324     albertel 5191:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  5192:     my @partids = ();
1.41      ng       5193:     foreach my $part (@parts) {
1.745     raeburn  5194: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  5195:         my $narrowtext = &mt('Tries');
                   5196: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  5197: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 5198: 	my ($partid) = &split_part_type($part);
1.524     raeburn  5199:         push(@partids,$partid);
1.628     www      5200: #
                   5201: # FIXME: Looks like $display looks at English text
                   5202: #
1.324     albertel 5203: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       5204: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 5205: 	    $result.='<th>'.
1.697     bisitz   5206: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   5207: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       5208: 	    next;
1.485     albertel 5209: 	    
1.207     albertel 5210: 	} else {
1.485     albertel 5211: 	    if ($display =~ /Problem Status/) {
                   5212: 		my $grade_status_mt = &mt('Grade Status');
                   5213: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   5214: 	    }
                   5215: 	    my $part_mt = &mt('Part:');
                   5216: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       5217: 	}
1.485     albertel 5218: 
1.474     albertel 5219: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       5220:     }
1.474     albertel 5221:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       5222: 
1.270     albertel 5223:     my %last_resets = 
                   5224: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  5225: 
1.41      ng       5226:     #get info for each student
1.44      ng       5227:     #list all the students - with points and grade status
1.738     raeburn  5228:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       5229:     my $ctr = 0;
1.294     albertel 5230:     foreach (sort 
                   5231: 	     {
                   5232: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5233: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5234: 		 }
                   5235: 		 return $a cmp $b;
                   5236: 	     } (keys(%$fullname))) {
1.324     albertel 5237: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  5238: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       5239:     }
1.474     albertel 5240:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       5241:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.780     raeburn  5242:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5243: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  5244:     if ($ctr == 0) {
1.442     banghart 5245:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  5246:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   5247:                 '<span class="LC_warning">';
                   5248:         if ($env{'form.submitonly'} eq 'all') {
                   5249:             if (grep(/^all$/,@sections)) {
                   5250:                 if (grep(/^all$/,@groups)) {
                   5251:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   5252:                                    $stu_status);
                   5253:                 } elsif (grep(/^none$/,@groups)) {
                   5254:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   5255:                                    $stu_status); 
                   5256:                 } else {
                   5257:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5258:                                    $group_display,$stu_status);
                   5259:                 }
                   5260:             } elsif (grep(/^none$/,@sections)) {
                   5261:                 if (grep(/^all$/,@groups)) {
                   5262:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   5263:                                    $stu_status);
                   5264:                 } elsif (grep(/^none$/,@groups)) {
                   5265:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   5266:                                    $stu_status);
                   5267:                 } else {
                   5268:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5269:                                    $group_display,$stu_status);
                   5270:                 }
                   5271:             } else {
                   5272:                 if (grep(/^all$/,@groups)) {
                   5273:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   5274:                                    $section_display,$stu_status);
                   5275:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  5276:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  5277:                                    $section_display,$stu_status);
                   5278:                 } else {
                   5279:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   5280:                                    $section_display,$group_display,$stu_status);
                   5281:                 }
                   5282:             }
                   5283:         } else {
                   5284:             if (grep(/^all$/,@sections)) {
                   5285:                 if (grep(/^all$/,@groups)) {
                   5286:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5287:                                    $stu_status,$submission_status);
                   5288:                 } elsif (grep(/^none$/,@groups)) {
                   5289:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5290:                                    $stu_status,$submission_status);
                   5291:                 } else {
                   5292:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5293:                                    $group_display,$stu_status,$submission_status);
                   5294:                 }
                   5295:             } elsif (grep(/^none$/,@sections)) {
                   5296:                 if (grep(/^all$/,@groups)) {
                   5297:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5298:                                    $stu_status,$submission_status);
                   5299:                 } elsif (grep(/^none$/,@groups)) {
                   5300:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5301:                                    $stu_status,$submission_status);
                   5302:                 } else {
                   5303:                     $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.',
                   5304:                                    $group_display,$stu_status,$submission_status);
                   5305:                 }
                   5306:             } else {
                   5307:                 if (grep(/^all$/,@groups)) {
                   5308: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5309: 	                           $section_display,$stu_status,$submission_status);
                   5310:                 } elsif (grep(/^none$/,@groups)) {
                   5311:                     $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.',
                   5312:                                    $section_display,$stu_status,$submission_status);
                   5313:                 } else {
                   5314:                     $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.',
                   5315:                                    $section_display,$group_display,$stu_status,$submission_status);
                   5316:                 }
                   5317:             }
                   5318:         }
                   5319: 	$result .= '</span><br />';
1.96      albertel 5320:     }
1.41      ng       5321:     return $result;
                   5322: }
                   5323: 
1.738     raeburn  5324: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       5325: sub viewstudentgrade {
1.745     raeburn  5326:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       5327:     my ($uname,$udom) = split(/:/,$student);
                   5328:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  5329:     my $submitonly = $env{'form.submitonly'};
                   5330:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   5331:         my %partstatus = ();
                   5332:         if (ref($parts) eq 'ARRAY') {
                   5333:             foreach my $apart (@{$parts}) {
                   5334:                 my ($part,$type) = &split_part_type($apart);
                   5335:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   5336:                 $status = 'nothing' if ($status eq '');
                   5337:                 $partstatus{$part}      = $status;
                   5338:                 my $subkey = "resource.$part.submitted_by";
                   5339:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   5340:             }
                   5341:             my $submitted = 0;
                   5342:             my $graded = 0;
                   5343:             my $incorrect = 0;
                   5344:             foreach my $key (keys(%partstatus)) {
                   5345:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   5346:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   5347:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   5348: 
                   5349:                 my $partid = (split(/\./,$key))[1];
                   5350:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   5351:                     $submitted = 0;
                   5352:                 }
                   5353:             }
                   5354:             return if (!$submitted && ($submitonly eq 'yes' ||
                   5355:                                        $submitonly eq 'incorrect' ||
                   5356:                                        $submitonly eq 'graded'));
                   5357:             return if (!$graded && ($submitonly eq 'graded'));
                   5358:             return if (!$incorrect && $submitonly eq 'incorrect');
                   5359:         }
                   5360:     }
                   5361:     if ($submitonly eq 'queued') {
                   5362:         my ($cdom,$cnum) = split(/_/,$courseid);
                   5363:         my %queue_status =
                   5364:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   5365:                                                     $udom,$uname);
                   5366:         return if (!defined($queue_status{'gradingqueue'}));
                   5367:     }
                   5368:     $$ctr++;
                   5369:     my %aggregates = ();
1.474     albertel 5370:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  5371: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   5372: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       5373: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 5374: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 5375: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 5376:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 5377:     foreach my $apart (@$parts) {
                   5378: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       5379: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 5380:         $result.='<td align="center">';
1.269     raeburn  5381:         my ($aggtries,$totaltries);
                   5382:         unless (exists($aggregates{$part})) {
1.270     albertel 5383: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   5384: 	    $aggtries = $totaltries;
1.269     raeburn  5385:             if ($$last_resets{$part}) {  
1.270     albertel 5386:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   5387: 					   $part);
                   5388:             }
1.269     raeburn  5389:             $result.='<input type="hidden" name="'.
                   5390:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   5391:             $result.='<input type="hidden" name="'.
                   5392:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   5393:             $aggregates{$part} = 1;
                   5394:         }
1.41      ng       5395: 	if ($type eq 'awarded') {
1.320     albertel 5396: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       5397: 	    $result.='<input type="hidden" name="'.
1.89      albertel 5398: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 5399: 	    $result.='<input type="text" name="'.
1.89      albertel 5400: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   5401:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       5402: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       5403: 	} elsif ($type eq 'solved') {
                   5404: 	    my ($status,$foo)=split(/_/,$score,2);
                   5405: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 5406: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 5407: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 5408: 	    $result.='&nbsp;<select name="'.
1.89      albertel 5409: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   5410:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 5411: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   5412: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   5413: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       5414: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       5415: 	} else {
                   5416: 	    $result.='<input type="hidden" name="'.
                   5417: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   5418: 		    "\n";
1.233     albertel 5419: 	    $result.='<input type="text" name="'.
1.122     ng       5420: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   5421: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       5422: 	}
                   5423:     }
1.474     albertel 5424:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       5425:     return $result;
1.38      ng       5426: }
                   5427: 
1.44      ng       5428: #--- change scores for all the students in a section/class
                   5429: #    record does not get update if unchanged
1.38      ng       5430: sub editgrades {
1.608     www      5431:     my ($request,$symb) = @_;
1.745     raeburn  5432:     my $toolsymb;
                   5433:     if ($symb =~ /ext\.tool$/) {
                   5434:         $toolsymb = $symb;
                   5435:     }
1.41      ng       5436: 
1.433     banghart 5437:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 5438:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  5439:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       5440: 
1.477     albertel 5441:     my $result= &Apache::loncommon::start_data_table().
                   5442: 	&Apache::loncommon::start_data_table_header_row().
                   5443: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   5444: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       5445:     my %scoreptr = (
                   5446: 		    'correct'  =>'correct_by_override',
                   5447: 		    'incorrect'=>'incorrect_by_override',
                   5448: 		    'excused'  =>'excused',
                   5449: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  5450:                     'credited' =>'credit_attempted',
1.43      ng       5451: 		    'nothing'  => '',
                   5452: 		    );
1.257     albertel 5453:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       5454: 
1.798     raeburn  5455:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5456:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5457:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   5458: 
1.44      ng       5459:     my (@partid);
                   5460:     my %weight = ();
1.54      albertel 5461:     my %columns = ();
1.44      ng       5462:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 5463: 
1.582     raeburn  5464:     my $partserror;
                   5465:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5466:     if ($partserror) {
                   5467:         return &navmap_errormsg();
                   5468:     }
1.54      albertel 5469:     my $header;
1.257     albertel 5470:     while ($ctr < $env{'form.totalparts'}) {
                   5471: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  5472: 	push(@partid,$partid);
1.257     albertel 5473: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       5474: 	$ctr++;
1.54      albertel 5475:     }
1.324     albertel 5476:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  5477:     my $totcolspan = 0;
1.54      albertel 5478:     foreach my $partid (@partid) {
1.478     albertel 5479: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   5480: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 5481: 	$columns{$partid}=2;
                   5482: 	foreach my $stores (@parts) {
                   5483: 	    my ($part,$type) = &split_part_type($stores);
                   5484: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   5485: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  5486: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  5487: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  5488:             my $narrowtext = &mt('Tries');
                   5489: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   5490: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   5491: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 5492: 	    $columns{$partid}+=2;
                   5493: 	}
1.748     raeburn  5494:         $totcolspan += $columns{$partid};
1.54      albertel 5495:     }
                   5496:     foreach my $partid (@partid) {
1.324     albertel 5497: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 5498: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   5499: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   5500: 	    '</th>';
1.54      albertel 5501: 
1.44      ng       5502:     }
1.477     albertel 5503:     $result .= &Apache::loncommon::end_data_table_header_row().
                   5504: 	&Apache::loncommon::start_data_table_header_row().
                   5505: 	$header.
                   5506: 	&Apache::loncommon::end_data_table_header_row();
                   5507:     my @noupdate;
1.126     ng       5508:     my ($updateCtr,$noupdateCtr) = (1,1);
1.798     raeburn  5509:     my ($got_types,%queueable,%pbsave,%skip_passback);
1.257     albertel 5510:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   5511: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 5512: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       5513: 	my %newrecord;
                   5514: 	my $updateflag = 0;
1.108     albertel 5515: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  5516: 	my $canmodify = &canmodify($usec);
                   5517: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   5518: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   5519: 	if (!$canmodify) {
1.477     albertel 5520: 	    push(@noupdate,
1.748     raeburn  5521: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   5522: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 5523: 	    next;
                   5524: 	}
1.269     raeburn  5525:         my %aggregate = ();
                   5526:         my $aggregateflag = 0;
1.281     albertel 5527: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.798     raeburn  5528:         my (%weights,%awardeds,%excuseds);
1.44      ng       5529: 	foreach (@partid) {
1.257     albertel 5530: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 5531: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   5532: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 5533: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   5534: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 5535: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   5536: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.798     raeburn  5537:             $awardeds{$symb}{$_} = $partial;
1.44      ng       5538: 	    my $score;
                   5539: 	    if ($partial eq '') {
1.257     albertel 5540: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       5541: 	    } elsif ($partial > 0) {
                   5542: 		$score = 'correct_by_override';
                   5543: 	    } elsif ($partial == 0) {
                   5544: 		$score = 'incorrect_by_override';
                   5545: 	    }
1.257     albertel 5546: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       5547: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   5548: 
1.292     albertel 5549: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   5550: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5551: 	    if ($dropMenu eq 'reset status' &&
                   5552: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 5553: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       5554: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   5555: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 5556: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       5557: 		$updateflag = 1;
1.269     raeburn  5558:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   5559:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   5560:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   5561:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   5562:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5563:                     $aggregateflag = 1;
                   5564:                 }
1.139     albertel 5565: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   5566: 		$updateflag = 1;
                   5567: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   5568: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   5569: 		$rec_update++;
1.125     ng       5570: 	    }
                   5571: 
1.93      albertel 5572: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       5573: 		'<td align="center">'.$awarded.
                   5574: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 5575: 
1.54      albertel 5576: 
                   5577: 	    my $partid=$_;
1.798     raeburn  5578:             if ($score eq 'excused') {
                   5579:                 $excuseds{$symb}{$partid} = 1;
                   5580:             } else {
                   5581:                 $excuseds{$symb}{$partid} = '';
                   5582:             }
1.54      albertel 5583: 	    foreach my $stores (@parts) {
                   5584: 		my ($part,$type) = &split_part_type($stores);
                   5585: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   5586: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 5587: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   5588: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 5589: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   5590: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 5591: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 5592: 		    $updateflag=1;
                   5593: 		}
1.93      albertel 5594: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 5595: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   5596: 	    }
1.44      ng       5597: 	}
1.477     albertel 5598: 	$line.="\n";
1.301     albertel 5599: 
1.44      ng       5600: 	if ($updateflag) {
                   5601: 	    $count++;
1.257     albertel 5602: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 5603: 				    $udom,$uname);
1.301     albertel 5604: 
                   5605: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   5606: 					      $cnum,$udom,$uname)) {
                   5607: 		# need to figure out if should be in queue.
                   5608: 		my %record =  
                   5609: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   5610: 					     $udom,$uname);
                   5611: 		my $all_graded = 1;
                   5612: 		my $none_graded = 1;
1.786     raeburn  5613:                 unless ($got_types) {
                   5614:                     my $error;
                   5615:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   5616:                     unless ($error) {
                   5617:                         foreach my $part (@parts) {
                   5618:                             if (ref($resptype->{$part}) eq 'HASH') {
                   5619:                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   5620:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   5621:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   5622:                                         $queueable{$part} = 1;
                   5623:                                         last;
                   5624:                                     }
                   5625:                                 }
                   5626:                             }
                   5627:                         }
                   5628:                     }
                   5629:                     $got_types = 1;
                   5630:                 }
1.301     albertel 5631: 		foreach my $part (@parts) {
1.786     raeburn  5632:                     if ($queueable{$part}) {
                   5633: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   5634: 			    $all_graded = 0;
                   5635: 		        } else {
                   5636: 			    $none_graded = 0;
                   5637: 		        }
1.301     albertel 5638: 		    }
1.786     raeburn  5639:                 }
1.301     albertel 5640: 		if ($all_graded || $none_graded) {
                   5641: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   5642: 							   $symb,$cdom,$cnum,
                   5643: 							   $udom,$uname);
                   5644: 		}
                   5645: 	    }
                   5646: 
1.477     albertel 5647: 	    $result.=&Apache::loncommon::start_data_table_row().
                   5648: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   5649: 		&Apache::loncommon::end_data_table_row();
1.126     ng       5650: 	    $updateCtr++;
1.798     raeburn  5651:             if (keys(%needpb)) {
                   5652:                 $weights{$symb} = \%weight;
                   5653:                 &process_passbacks('editgrades',[$symb],$cdom,$cnum,$udom,$uname,\%weights,
                   5654:                                    \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   5655:             }
1.93      albertel 5656: 	} else {
1.477     albertel 5657: 	    push(@noupdate,
                   5658: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       5659: 	    $noupdateCtr++;
1.44      ng       5660: 	}
1.269     raeburn  5661:         if ($aggregateflag) {
                   5662:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 5663: 				  $cdom,$cnum);
1.269     raeburn  5664:         }
1.93      albertel 5665:     }
1.477     albertel 5666:     if (@noupdate) {
1.748     raeburn  5667:         my $numcols=$totcolspan+2;
1.477     albertel 5668: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 5669: 	    '<td align="center" colspan="'.$numcols.'">'.
                   5670: 	    &mt('No Changes Occurred For the Students Below').
                   5671: 	    '</td>'.
1.477     albertel 5672: 	    &Apache::loncommon::end_data_table_row();
                   5673: 	foreach my $line (@noupdate) {
                   5674: 	    $result.=
                   5675: 		&Apache::loncommon::start_data_table_row().
                   5676: 		$line.
                   5677: 		&Apache::loncommon::end_data_table_row();
                   5678: 	}
1.44      ng       5679:     }
1.614     www      5680:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 5681:     my $msg = '<p><b>'.
                   5682: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   5683: 	    $rec_update,$count).'</b><br />'.
                   5684: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   5685: 	'</b></p>';
1.44      ng       5686:     return $title.$msg.$result;
1.5       albertel 5687: }
1.54      albertel 5688: 
                   5689: sub split_part_type {
                   5690:     my ($partstr) = @_;
                   5691:     my ($temp,@allparts)=split(/_/,$partstr);
                   5692:     my $type=pop(@allparts);
1.439     albertel 5693:     my $part=join('_',@allparts);
1.54      albertel 5694:     return ($part,$type);
                   5695: }
                   5696: 
1.44      ng       5697: #------------- end of section for handling grading by section/class ---------
                   5698: #
                   5699: #----------------------------------------------------------------------------
                   5700: 
1.5       albertel 5701: 
1.44      ng       5702: #----------------------------------------------------------------------------
                   5703: #
                   5704: #-------------------------- Next few routines handles grading by csv upload
                   5705: #
                   5706: #--- Javascript to handle csv upload
1.27      albertel 5707: sub csvupload_javascript_reverse_associate {
1.743     raeburn  5708:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5709:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5710:   &js_escape(\$error1);
                   5711:   &js_escape(\$error2);
1.27      albertel 5712:   return(<<ENDPICK);
                   5713:   function verify(vf) {
                   5714:     var foundsomething=0;
                   5715:     var founduname=0;
1.243     albertel 5716:     var foundID=0;
1.743     raeburn  5717:     var foundclicker=0;
1.27      albertel 5718:     for (i=0;i<=vf.nfields.value;i++) {
                   5719:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5720:       if (i==0 && tw!=0) { foundID=1; }
                   5721:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  5722:       if (i==2 && tw!=0) { foundclicker=1; }
                   5723:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 5724:     }
1.743     raeburn  5725:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 5726: 	alert('$error1');
                   5727: 	return;
1.27      albertel 5728:     }
                   5729:     if (foundsomething==0) {
1.246     albertel 5730: 	alert('$error2');
                   5731: 	return;
1.27      albertel 5732:     }
                   5733:     vf.submit();
                   5734:   }
                   5735:   function flip(vf,tf) {
                   5736:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5737:     var i;
                   5738:     for (i=0;i<=vf.nfields.value;i++) {
                   5739:       //can not pick the same destination field for both name and domain
                   5740:       if (((i ==0)||(i ==1)) && 
                   5741:           ((tf==0)||(tf==1)) && 
                   5742:           (i!=tf) &&
                   5743:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5744:         eval('vf.f'+i+'.selectedIndex=0;')
                   5745:       }
                   5746:     }
                   5747:   }
                   5748: ENDPICK
                   5749: }
                   5750: 
                   5751: sub csvupload_javascript_forward_associate {
1.743     raeburn  5752:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5753:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5754:   &js_escape(\$error1);
                   5755:   &js_escape(\$error2);
1.27      albertel 5756:   return(<<ENDPICK);
                   5757:   function verify(vf) {
                   5758:     var foundsomething=0;
                   5759:     var founduname=0;
1.243     albertel 5760:     var foundID=0;
1.743     raeburn  5761:     var foundclicker=0;
1.27      albertel 5762:     for (i=0;i<=vf.nfields.value;i++) {
                   5763:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5764:       if (tw==1) { foundID=1; }
                   5765:       if (tw==2) { founduname=1; }
1.745     raeburn  5766:       if (tw==3) { foundclicker=1; }
1.743     raeburn  5767:       if (tw>4) { foundsomething=1; }
1.27      albertel 5768:     }
1.743     raeburn  5769:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 5770: 	alert('$error1');
                   5771: 	return;
1.27      albertel 5772:     }
                   5773:     if (foundsomething==0) {
1.246     albertel 5774: 	alert('$error2');
                   5775: 	return;
1.27      albertel 5776:     }
                   5777:     vf.submit();
                   5778:   }
                   5779:   function flip(vf,tf) {
                   5780:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5781:     var i;
                   5782:     //can not pick the same destination field twice
                   5783:     for (i=0;i<=vf.nfields.value;i++) {
                   5784:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5785:         eval('vf.f'+i+'.selectedIndex=0;')
                   5786:       }
                   5787:     }
                   5788:   }
                   5789: ENDPICK
                   5790: }
                   5791: 
1.26      albertel 5792: sub csvuploadmap_header {
1.324     albertel 5793:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       5794:     my $javascript;
1.257     albertel 5795:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       5796: 	$javascript=&csvupload_javascript_reverse_associate();
                   5797:     } else {
                   5798: 	$javascript=&csvupload_javascript_forward_associate();
                   5799:     }
1.45      ng       5800: 
1.418     albertel 5801:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      5802:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   5803:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   5804:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   5805:     my $reverse=&mt("Reverse Association");
1.41      ng       5806:     $request->print(<<ENDPICK);
1.632     www      5807: <br />
                   5808: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 5809: <input type="hidden" name="associate"  value="" />
                   5810: <input type="hidden" name="phase"      value="three" />
                   5811: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 5812: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   5813: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 5814: <input type="hidden" name="upfile_associate" 
1.257     albertel 5815:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 5816: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 5817: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 5818: <hr />
                   5819: ENDPICK
1.597     wenzelju 5820:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       5821:     return '';
1.26      albertel 5822: 
                   5823: }
                   5824: 
                   5825: sub csvupload_fields {
1.582     raeburn  5826:     my ($symb,$errorref) = @_;
1.745     raeburn  5827:     my $toolsymb;
                   5828:     if ($symb =~ /ext\.tool$/) {
                   5829:         $toolsymb = $symb;
                   5830:     }
1.582     raeburn  5831:     my (@parts) = &getpartlist($symb,$errorref);
                   5832:     if (ref($errorref)) {
                   5833:         if ($$errorref) {
                   5834:             return;
                   5835:         }
                   5836:     }
                   5837: 
1.556     weissno  5838:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 5839: 		['username','Student Username'],
1.743     raeburn  5840: 		['clicker','Clicker ID'],
1.243     albertel 5841: 		['domain','Student Domain']);
1.324     albertel 5842:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       5843:     foreach my $part (sort(@parts)) {
                   5844: 	my @datum;
1.745     raeburn  5845: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       5846: 	my $name=$part;
1.745     raeburn  5847: 	if (!$display) { $display = $name; }
1.41      ng       5848: 	@datum=($name,$display);
1.244     albertel 5849: 	if ($name=~/^stores_(.*)_awarded/) {
                   5850: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   5851: 	}
1.41      ng       5852: 	push(@fields,\@datum);
                   5853:     }
                   5854:     return (@fields);
1.26      albertel 5855: }
                   5856: 
                   5857: sub csvuploadmap_footer {
1.41      ng       5858:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   5859:     my $buttontext = &mt('Assign Grades');
1.41      ng       5860:     $request->print(<<ENDPICK);
1.26      albertel 5861: </table>
                   5862: <input type="hidden" name="nfields" value="$i" />
                   5863: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   5864: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 5865: </form>
                   5866: ENDPICK
                   5867: }
                   5868: 
1.283     albertel 5869: sub checkforfile_js {
1.638     www      5870:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  5871:     &js_escape(\$alertmsg);
1.597     wenzelju 5872:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       5873:     function checkUpload(formname) {
                   5874: 	if (formname.upfile.value == "") {
1.539     riegler  5875: 	    alert("$alertmsg");
1.86      ng       5876: 	    return false;
                   5877: 	}
                   5878: 	formname.submit();
                   5879:     }
                   5880: CSVFORMJS
1.283     albertel 5881:     return $result;
                   5882: }
                   5883: 
                   5884: sub upcsvScores_form {
1.608     www      5885:     my ($request,$symb) = @_;
1.283     albertel 5886:     if (!$symb) {return '';}
                   5887:     my $result=&checkforfile_js();
1.632     www      5888:     $result.=&Apache::loncommon::start_data_table().
                   5889:              &Apache::loncommon::start_data_table_header_row().
                   5890:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   5891:              &Apache::loncommon::end_data_table_header_row().
                   5892:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      5893:     my $upload=&mt("Upload Scores");
1.86      ng       5894:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 5895:     my $ignore=&mt('Ignore First Line');
1.418     albertel 5896:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       5897:     $result.=<<ENDUPFORM;
1.106     albertel 5898: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       5899: <input type="hidden" name="symb" value="$symb" />
                   5900: <input type="hidden" name="command" value="csvuploadmap" />
                   5901: $upfile_select
1.589     bisitz   5902: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       5903: </form>
                   5904: ENDUPFORM
1.370     www      5905:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      5906:                            &mt("How do I create a CSV file from a spreadsheet")).
                   5907:              '</td>'.
                   5908:             &Apache::loncommon::end_data_table_row().
                   5909:             &Apache::loncommon::end_data_table();
1.86      ng       5910:     return $result;
                   5911: }
                   5912: 
                   5913: 
1.26      albertel 5914: sub csvuploadmap {
1.768     raeburn  5915:     my ($request,$symb) = @_;
1.41      ng       5916:     if (!$symb) {return '';}
1.72      ng       5917: 
1.41      ng       5918:     my $datatoken;
1.257     albertel 5919:     if (!$env{'form.datatoken'}) {
1.41      ng       5920: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 5921:     } else {
1.742     raeburn  5922: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5923:         if ($datatoken ne '') {
                   5924: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5925:         }
1.26      albertel 5926:     }
1.41      ng       5927:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 5928:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       5929:     my ($i,$keyfields);
                   5930:     if (@records) {
1.582     raeburn  5931:         my $fieldserror;
                   5932: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   5933:         if ($fieldserror) {
                   5934:             $request->print(&navmap_errormsg());
                   5935:             return;
                   5936:         }
1.257     albertel 5937: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       5938: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   5939: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   5940: 							  \@fields);
                   5941: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   5942: 	    chop($keyfields);
                   5943: 	} else {
                   5944: 	    unshift(@fields,['none','']);
                   5945: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   5946: 							    \@fields);
1.311     banghart 5947:             foreach my $rec (@records) {
                   5948:                 my %temp = &Apache::loncommon::record_sep($rec);
                   5949:                 if (%temp) {
                   5950:                     $keyfields=join(',',sort(keys(%temp)));
                   5951:                     last;
                   5952:                 }
                   5953:             }
1.41      ng       5954: 	}
                   5955:     }
                   5956:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       5957: 
1.41      ng       5958:     return '';
1.27      albertel 5959: }
                   5960: 
1.246     albertel 5961: sub csvuploadoptions {
1.608     www      5962:     my ($request,$symb)= @_;
1.632     www      5963:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 5964:     $request->print(<<ENDPICK);
                   5965: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   5966: <input type="hidden" name="command"    value="csvuploadassign" />
                   5967: <p>
                   5968: <label>
                   5969:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      5970:    $overwrite
1.246     albertel 5971: </label>
                   5972: </p>
                   5973: ENDPICK
                   5974:     my %fields=&get_fields();
                   5975:     if (!defined($fields{'domain'})) {
1.257     albertel 5976: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      5977: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 5978:     }
1.257     albertel 5979:     foreach my $key (sort(keys(%env))) {
1.246     albertel 5980: 	if ($key !~ /^form\.(.*)$/) { next; }
                   5981: 	my $cleankey=$1;
                   5982: 	if ($cleankey eq 'command') { next; }
                   5983: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 5984: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 5985:     }
                   5986:     # FIXME do a check for any duplicated user ids...
                   5987:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   5988:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 5989: <hr /></form>'."\n");
1.246     albertel 5990:     return '';
                   5991: }
                   5992: 
                   5993: sub get_fields {
                   5994:     my %fields;
1.257     albertel 5995:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   5996:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   5997: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   5998: 	    if ($env{'form.f'.$i} ne 'none') {
                   5999: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       6000: 	    }
                   6001: 	} else {
1.257     albertel 6002: 	    if ($env{'form.f'.$i} ne 'none') {
                   6003: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       6004: 	    }
                   6005: 	}
1.27      albertel 6006:     }
1.246     albertel 6007:     return %fields;
                   6008: }
                   6009: 
                   6010: sub csvuploadassign {
1.766     raeburn  6011:     my ($request,$symb) = @_;
1.246     albertel 6012:     if (!$symb) {return '';}
1.345     bowersj2 6013:     my $error_msg = '';
1.742     raeburn  6014:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   6015:     if ($datatoken ne '') { 
                   6016:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   6017:     }
1.246     albertel 6018:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   6019:     my %fields=&get_fields();
1.257     albertel 6020:     my $courseid=$env{'request.course.id'};
1.798     raeburn  6021:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6022:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.97      albertel 6023:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 6024:     my @notallowed;
1.41      ng       6025:     my @skipped;
1.657     raeburn  6026:     my @warnings;
1.41      ng       6027:     my $countdone=0;
1.798     raeburn  6028:     my @parts;
                   6029:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   6030:     my $passback;
                   6031:     if (keys(%needpb)) {
                   6032:         $passback = 1;
                   6033:         my $navmap = Apache::lonnavmaps::navmap->new();
                   6034:         if (ref($navmap)) {
                   6035:             my $res = $navmap->getBySymb($symb);
                   6036:             if (ref($res)) {
                   6037:                 my $partlist = $res->parts();
                   6038:                 if (ref($partlist) eq 'ARRAY') {
                   6039:                     @parts = sort(@{$partlist});
                   6040:                 }
                   6041:             }
                   6042:         } else {
                   6043:             return &navmap_errormsg();
                   6044:         }
                   6045:     }
                   6046:     my (%skip_passback,%pbsave,%weights,%awardeds,%excuseds);
                   6047: 
1.41      ng       6048:     foreach my $grade (@gradedata) {
                   6049: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 6050: 	my $domain;
                   6051: 	if ($entries{$fields{'domain'}}) {
                   6052: 	    $domain=$entries{$fields{'domain'}};
                   6053: 	} else {
1.257     albertel 6054: 	    $domain=$env{'form.default_domain'};
1.246     albertel 6055: 	}
1.243     albertel 6056: 	$domain=~s/\s//g;
1.41      ng       6057: 	my $username=$entries{$fields{'username'}};
1.160     albertel 6058: 	$username=~s/\s//g;
1.243     albertel 6059: 	if (!$username) {
                   6060: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 6061: 	    $id=~s/\s//g;
1.737     raeburn  6062:             if ($id ne '') {
                   6063: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   6064: 	        $username=$ids{$id};
                   6065:             } else {
                   6066:                 if ($entries{$fields{'clicker'}}) {
                   6067:                     my $clicker = $entries{$fields{'clicker'}};
                   6068:                     $clicker=~s/\s//g;
                   6069:                     if ($clicker ne '') {
                   6070:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   6071:                         if ($clickers{$clicker} ne '') {  
                   6072:                             my $match = 0;
                   6073:                             my @inclass;
                   6074:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   6075:                                 if (exists($$classlist{"$poss:$domain"})) {
                   6076:                                     $username = $poss;
                   6077:                                     push(@inclass,$poss);
                   6078:                                     $match ++;
                   6079:                                     
                   6080:                                 }
                   6081:                             }
                   6082:                             if ($match > 1) {
                   6083:                                 undef($username); 
                   6084:                                 $request->print('<p class="LC_warning">'.
                   6085:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   6086:                                                 $clicker,join(', ',@inclass)).'</p>');
                   6087:                             }
                   6088:                         }
                   6089:                     }
                   6090:                 }
                   6091:             }
1.243     albertel 6092: 	}
1.41      ng       6093: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 6094: 	    my $id=$entries{$fields{'ID'}};
                   6095: 	    $id=~s/\s//g;
1.737     raeburn  6096:             my $clicker = $entries{$fields{'clicker'}};
                   6097:             $clicker=~s/\s//g;
                   6098:             if ($clicker) {
                   6099:                 push(@skipped,"$clicker:$domain");
                   6100: 	    } elsif ($id) {
1.247     albertel 6101: 		push(@skipped,"$id:$domain");
                   6102: 	    } else {
                   6103: 		push(@skipped,"$username:$domain");
                   6104: 	    }
1.41      ng       6105: 	    next;
                   6106: 	}
1.108     albertel 6107: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 6108: 	if (!&canmodify($usec)) {
                   6109: 	    push(@notallowed,"$username:$domain");
                   6110: 	    next;
                   6111: 	}
1.244     albertel 6112: 	my %points;
1.41      ng       6113: 	my %grades;
                   6114: 	foreach my $dest (keys(%fields)) {
1.244     albertel 6115: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   6116: 		$dest eq 'domain') { next; }
                   6117: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   6118: 	    if ($dest=~/stores_(.*)_points/) {
                   6119: 		my $part=$1;
                   6120: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6121: 					      $symb,$domain,$username);
1.798     raeburn  6122:                 $weights{$symb}{$part} = $wgt;
1.345     bowersj2 6123:                 if ($wgt) {
                   6124:                     $entries{$fields{$dest}}=~s/\s//g;
                   6125:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.798     raeburn  6126:                     if ($passback) {
                   6127:                         $awardeds{$symb}{$part} = $pcr;
                   6128:                         $excuseds{$symb}{$part} = '';
                   6129:                     }
1.463     albertel 6130:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   6131:                                           : 'correct_by_override';
1.638     www      6132:                     if ($pcr>1) {
1.657     raeburn  6133:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      6134:                     }
1.345     bowersj2 6135:                     $grades{"resource.$part.awarded"}=$pcr;
                   6136:                     $grades{"resource.$part.solved"}=$award;
                   6137:                     $points{$part}=1;
                   6138:                 } else {
                   6139:                     $error_msg = "<br />" .
                   6140:                         &mt("Some point values were assigned"
                   6141:                             ." for problems with a weight "
                   6142:                             ."of zero. These values were "
                   6143:                             ."ignored.");
                   6144:                 }
1.244     albertel 6145: 	    } else {
                   6146: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   6147: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   6148: 		my $store_key=$dest;
1.798     raeburn  6149:                 if ($passback) {
                   6150:                     if ($store_key=~/stores_(.*)_(awarded|solved)/) {
                   6151:                         my ($part,$key) = ($1,$2);
                   6152:                         unless ((ref($weights{$symb}) eq 'HASH') && (exists($weights{$symb}{$part}))) {
                   6153:                             $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6154:                                                                           $symb,$domain,$username);
                   6155:                         }
                   6156:                         if ($key eq 'awarded') {
                   6157:                             $awardeds{$symb}{$part} = $entries{$fields{$dest}};
                   6158:                         } elsif ($key eq 'solved') {
                   6159:                             if ($entries{$fields{$dest}} =~ /^excused/) {
                   6160:                                 $excuseds{$symb}{$part} = 1;
                   6161:                             }
                   6162:                         }
                   6163:                     }
                   6164:                 }
1.244     albertel 6165: 		$store_key=~s/^stores/resource/;
                   6166: 		$store_key=~s/_/\./g;
                   6167: 		$grades{$store_key}=$entries{$fields{$dest}};
                   6168: 	    }
1.41      ng       6169: 	}
1.766     raeburn  6170: 	if (! %grades) {
1.508     www      6171:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   6172:         } else {
                   6173: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   6174: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 6175: 					   $env{'request.course.id'},
                   6176: 					   $domain,$username);
1.508     www      6177: 	   if ($result eq 'ok') {
1.627     www      6178: # Successfully stored
1.508     www      6179: 	      $request->print('.');
1.627     www      6180: # Remove from grading queue
1.798     raeburn  6181:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,$cnum,
1.801   ! raeburn  6182: 						     $domain,$username);
1.627     www      6183:               $countdone++;
1.798     raeburn  6184:               if ($passback) {
                   6185:                   my @parts_in_upload;
                   6186:                   if (ref($weights{$symb}) eq 'HASH') {
                   6187:                       @parts_in_upload = sort(keys(%{$weights{$symb}}));
                   6188:                   }
                   6189:                   my @diffs = &Apache::loncommon::compare_arrays(\@parts_in_upload,\@parts);
                   6190:                   if (@diffs > 0) {
                   6191:                       my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$username);
                   6192:                       foreach my $part (@parts) {
                   6193:                           next if (grep(/^\Q$part\E$/,@parts_in_upload));
                   6194:                           $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6195:                                                                         $symb,$domain,$username);
                   6196:                           if ($record{"resource.$part.solved"} =~/^excused/) {
                   6197:                               $excuseds{$symb}{$part} = 1;
                   6198:                           } else {
                   6199:                               $excuseds{$symb}{$part} = '';
                   6200:                           }
                   6201:                           $awardeds{$symb}{$part} = $record{"resource.$part.awarded"};
                   6202:                       }
                   6203:                   }
                   6204:                   &process_passbacks('csvupload',[$symb],$cdom,$cnum,$domain,$username,\%weights,
                   6205:                                      \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   6206:               }
1.627     www      6207:            } else {
1.508     www      6208: 	      $request->print("<p><span class=\"LC_error\">".
                   6209:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   6210:                                   "$username:$domain",$result)."</span></p>");
                   6211: 	   }
                   6212: 	   $request->rflush();
                   6213:         }
1.41      ng       6214:     }
1.570     www      6215:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  6216:     if (@warnings) {
                   6217:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   6218:         $request->print(join(', ',@warnings));
                   6219:     }
1.41      ng       6220:     if (@skipped) {
1.571     www      6221: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   6222:         $request->print(join(', ',@skipped));
1.106     albertel 6223:     }
                   6224:     if (@notallowed) {
1.571     www      6225: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   6226: 	$request->print(join(', ',@notallowed));
1.41      ng       6227:     }
1.106     albertel 6228:     $request->print("<br />\n");
1.345     bowersj2 6229:     return $error_msg;
1.26      albertel 6230: }
1.44      ng       6231: #------------- end of section for handling csv file upload ---------
                   6232: #
                   6233: #-------------------------------------------------------------------
                   6234: #
1.122     ng       6235: #-------------- Next few routines handle grading by page/sequence
1.72      ng       6236: #
                   6237: #--- Select a page/sequence and a student to grade
1.68      ng       6238: sub pickStudentPage {
1.608     www      6239:     my ($request,$symb) = @_;
1.68      ng       6240: 
1.539     riegler  6241:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  6242:     &js_escape(\$alertmsg);
1.597     wenzelju 6243:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       6244: 
                   6245: function checkPickOne(formname) {
1.76      ng       6246:     if (radioSelection(formname.student) == null) {
1.539     riegler  6247: 	alert("$alertmsg");
1.68      ng       6248: 	return;
                   6249:     }
1.125     ng       6250:     ptr = pullDownSelection(formname.selectpage);
                   6251:     formname.page.value = formname["page"+ptr].value;
                   6252:     formname.title.value = formname["title"+ptr].value;
1.68      ng       6253:     formname.submit();
                   6254: }
                   6255: 
                   6256: LISTJAVASCRIPT
1.118     ng       6257:     &commonJSfunctions($request);
1.608     www      6258: 
1.257     albertel 6259:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6260:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6261:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  6262:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       6263: 
1.398     albertel 6264:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 6265: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       6266: 
1.80      ng       6267:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  6268:     my $map_error;
                   6269:     my ($titles,$symbx) = &getSymbMap($map_error);
                   6270:     if ($map_error) {
                   6271:         $request->print(&navmap_errormsg());
                   6272:         return; 
                   6273:     }
1.137     albertel 6274:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   6275: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   6276: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   6277: 
                   6278:     # Collection of hidden fields
1.70      ng       6279:     my $ctr=0;
1.68      ng       6280:     foreach (@$titles) {
1.700     bisitz   6281:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   6282:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   6283:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   6284:         $ctr++;
1.68      ng       6285:     }
1.700     bisitz   6286:     $result.='<input type="hidden" name="page" />'."\n".
                   6287:         '<input type="hidden" name="title" />'."\n";
                   6288: 
                   6289:     $result.=&build_section_inputs();
                   6290:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   6291:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   6292: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   6293: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 6294: 
1.700     bisitz   6295:     # Show grading options
                   6296:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   6297:     my $select = '<select name="selectpage">'."\n";
1.70      ng       6298:     $ctr=0;
                   6299:     foreach (@$titles) {
                   6300: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   6301: 	$select.='<option value="'.$ctr.'"'.
                   6302: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   6303: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       6304: 	$ctr++;
                   6305:     }
1.700     bisitz   6306:     $select.= '</select>';
1.68      ng       6307: 
1.700     bisitz   6308:     $result.=
                   6309:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   6310:        .$select
                   6311:        .&Apache::lonhtmlcommon::row_closure();
                   6312: 
                   6313:     $result.=
                   6314:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   6315:        .'<label><input type="radio" name="vProb" value="no"'
                   6316:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   6317:        .'<label><input type="radio" name="vProb" value="yes" />'
                   6318:            .&mt('yes').'</label>'."\n"
                   6319:        .&Apache::lonhtmlcommon::row_closure();
                   6320: 
                   6321:     $result.=
                   6322:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   6323:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   6324:            .&mt('none').' </label>'."\n"
                   6325:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   6326:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   6327:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   6328:            .&mt('all submissions with details').' </label>'
                   6329:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 6330:     
1.700     bisitz   6331:     $result.=
                   6332:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   6333:        .'<input type="text" name="CODE" value="" />'
                   6334:        .&Apache::lonhtmlcommon::row_closure(1)
                   6335:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 6336: 
1.700     bisitz   6337:     # Show list of students to select for grading
                   6338:     $result.='<br /><input type="button" '.
1.589     bisitz   6339:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       6340: 
1.68      ng       6341:     $request->print($result);
                   6342: 
1.485     albertel 6343:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 6344: 	&Apache::loncommon::start_data_table().
                   6345: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6346: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6347: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 6348: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6349: 	'<th>'.&nameUserString('header').'</th>'.
                   6350: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       6351:  
1.761     raeburn  6352:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       6353:     my $ptr = 1;
1.294     albertel 6354:     foreach my $student (sort 
                   6355: 			 {
                   6356: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   6357: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   6358: 			     }
                   6359: 			     return $a cmp $b;
                   6360: 			 } (keys(%$fullname))) {
1.68      ng       6361: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 6362: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   6363:                                   : '</td>');
1.126     ng       6364: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 6365: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   6366: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 6367: 	$studentTable.=
                   6368: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   6369:                          : '');
1.68      ng       6370: 	$ptr++;
                   6371:     }
1.484     albertel 6372:     if ($ptr%2 == 0) {
                   6373: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   6374: 	    &Apache::loncommon::end_data_table_row();
                   6375:     }
                   6376:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       6377:     $studentTable.='<input type="button" '.
1.589     bisitz   6378:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       6379: 
                   6380:     $request->print($studentTable);
                   6381: 
                   6382:     return '';
                   6383: }
                   6384: 
                   6385: sub getSymbMap {
1.582     raeburn  6386:     my ($map_error) = @_;
1.132     bowersj2 6387:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6388:     unless (ref($navmap)) {
                   6389:         if (ref($map_error)) {
                   6390:             $$map_error = 'navmap';
                   6391:         }
                   6392:         return;
                   6393:     }
1.68      ng       6394:     my %symbx = ();
                   6395:     my @titles = ();
1.117     bowersj2 6396:     my $minder = 0;
                   6397: 
                   6398:     # Gather every sequence that has problems.
1.240     albertel 6399:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   6400: 					       1,0,1);
1.117     bowersj2 6401:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  6402: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 6403: 	    my $title = $minder.'.'.
                   6404: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   6405: 	    push(@titles, $title); # minder in case two titles are identical
                   6406: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 6407: 	    $minder++;
1.241     albertel 6408: 	}
1.68      ng       6409:     }
                   6410:     return \@titles,\%symbx;
                   6411: }
                   6412: 
1.72      ng       6413: #
                   6414: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       6415: sub displayPage {
1.608     www      6416:     my ($request,$symb) = @_;
1.257     albertel 6417:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6418:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6419:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6420:     my $pageTitle = $env{'form.page'};
1.103     albertel 6421:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6422:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6423:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 6424: 
                   6425:     #need to make sure we have the correct data for later EXT calls, 
                   6426:     #thus invalidate the cache
                   6427:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 6428:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   6429:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 6430:     &Apache::lonnet::clear_EXT_cache_status();
                   6431: 
1.103     albertel 6432:     if (!&canview($usec)) {
1.712     bisitz   6433:         $request->print(
                   6434:             '<span class="LC_warning">'.
                   6435:             &mt('Unable to view requested student. ([_1])',
                   6436:                     $env{'form.student'}).
                   6437:             '</span>');
                   6438:         return;
1.103     albertel 6439:     }
1.398     albertel 6440:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 6441:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       6442: 	'</h3>'."\n";
1.500     albertel 6443:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     6444:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 6445: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 6446:     } else {
                   6447: 	delete($env{'form.CODE'});
                   6448:     }
1.71      ng       6449:     &sub_page_js($request);
                   6450:     $request->print($result);
                   6451: 
1.132     bowersj2 6452:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6453:     unless (ref($navmap)) {
                   6454:         $request->print(&navmap_errormsg());
                   6455:         return;
                   6456:     }
1.257     albertel 6457:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       6458:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6459:     if (!$map) {
1.485     albertel 6460: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 6461: 	return; 
                   6462:     }
1.68      ng       6463:     my $iterator = $navmap->getIterator($map->map_start(),
                   6464: 					$map->map_finish());
                   6465: 
1.71      ng       6466:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       6467: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 6468: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   6469: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       6470: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 6471: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 6472: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      6473: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       6474: 
1.382     albertel 6475:     if (defined($env{'form.CODE'})) {
                   6476: 	$studentTable.=
                   6477: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   6478:     }
1.381     albertel 6479:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 6480: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       6481: 
1.594     bisitz   6482:     $studentTable.='&nbsp;<span class="LC_info">'.
                   6483:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   6484:         '</span>'."\n".
1.484     albertel 6485: 	&Apache::loncommon::start_data_table().
                   6486: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   6487: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 6488: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 6489: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6490: 
1.329     albertel 6491:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 6492:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       6493:     $iterator->next(); # skip the first BEGIN_MAP
                   6494:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 6495:     while ($depth > 0) {
1.68      ng       6496:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6497:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       6498: 
1.745     raeburn  6499:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 6500: 	    my $parts = $curRes->parts();
1.68      ng       6501:             my $title = $curRes->compTitle();
1.71      ng       6502: 	    my $symbx = $curRes->symb();
1.746     raeburn  6503:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 6504: 	    $studentTable.=
                   6505: 		&Apache::loncommon::start_data_table_row().
                   6506: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6507: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  6508: 		                        : '<br />('.&mt('[_1]parts',
                   6509: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 6510: 		 ).
                   6511: 		 '</td>';
1.71      ng       6512: 	    $studentTable.='<td valign="top">';
1.382     albertel 6513: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  6514:             if ($is_tool) {
                   6515:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   6516:             } else {
1.745     raeburn  6517: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   6518: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   6519: 					         undef,'both',\%form);
                   6520: 	        } else {
                   6521: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   6522: 		    $companswer =~ s|<form(.*?)>||g;
                   6523: 		    $companswer =~ s|</form>||g;
                   6524: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   6525: #		        $companswer =~ s/$1/ /ms;
                   6526: #		        $request->print('match='.$1."<br />\n");
                   6527: #		    }
                   6528: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   6529: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   6530: 		}
1.71      ng       6531: 	    }
                   6532: 
1.257     albertel 6533: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       6534: 
1.257     albertel 6535: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       6536: 		if ($record{'version'} eq '') {
1.745     raeburn  6537:                     my $msg = &mt('No recorded submission for this problem.');
                   6538:                     if ($is_tool) {
                   6539:                         $msg = &mt('No recorded transactions for this external tool');
                   6540:                     }
                   6541: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       6542: 		} else {
1.116     ng       6543: 		    my %responseType = ();
                   6544: 		    foreach my $partid (@{$parts}) {
1.147     albertel 6545: 			my @responseIds =$curRes->responseIds($partid);
                   6546: 			my @responseType =$curRes->responseType($partid);
                   6547: 			my %responseIds;
                   6548: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   6549: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   6550: 			}
                   6551: 			$responseType{$partid} = \%responseIds;
1.116     ng       6552: 		    }
1.148     albertel 6553: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       6554: 		}
1.257     albertel 6555: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   6556: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  6557:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       6558: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 6559: 									$env{'request.course.id'},
1.726     raeburn  6560: 									'','.submission',undef,
                   6561:                                                                         $usec,$identifier);
1.71      ng       6562:  
                   6563: 	    }
1.103     albertel 6564: 	    if (&canmodify($usec)) {
1.585     bisitz   6565:             $studentTable.=&gradeBox_start();
1.103     albertel 6566: 		foreach my $partid (@{$parts}) {
                   6567: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   6568: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   6569: 		    $question++;
                   6570: 		}
1.585     bisitz   6571:             $studentTable.=&gradeBox_end();
1.196     albertel 6572: 		$prob++;
1.71      ng       6573: 	    }
                   6574: 	    $studentTable.='</td></tr>';
1.68      ng       6575: 
1.103     albertel 6576: 	}
1.68      ng       6577:         $curRes = $iterator->next();
                   6578:     }
1.780     raeburn  6579:     my $disabled;
                   6580:     unless (&canmodify($usec)) {
                   6581:         $disabled = ' disabled="disabled"';
                   6582:     }
1.68      ng       6583: 
1.589     bisitz   6584:     $studentTable.=
                   6585:         '</table>'."\n".
1.780     raeburn  6586:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   6587:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   6588:         '</form>'."\n";
1.71      ng       6589:     $request->print($studentTable);
                   6590: 
                   6591:     return '';
1.119     ng       6592: }
                   6593: 
                   6594: sub displaySubByDates {
1.148     albertel 6595:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 6596:     my $isCODE=0;
1.335     albertel 6597:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  6598:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 6599:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 6600:     my $studentTable=&Apache::loncommon::start_data_table().
                   6601: 	&Apache::loncommon::start_data_table_header_row().
                   6602: 	'<th>'.&mt('Date/Time').'</th>'.
                   6603: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  6604:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  6605: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 6606: 	'<th>'.&mt('Status').'</th>'.
                   6607: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       6608:     my ($version);
                   6609:     my %mark;
1.148     albertel 6610:     my %orders;
1.119     ng       6611:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 6612:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  6613:         if ($is_tool) {
                   6614:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   6615:         } else {
                   6616:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   6617:         }
1.147     albertel 6618:     }
1.335     albertel 6619: 
                   6620:     my $interaction;
1.525     raeburn  6621:     my $no_increment = 1;
1.735     raeburn  6622:     my (%lastrndseed,%lasttype);
1.119     ng       6623:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 6624: 	my $timestamp = 
                   6625: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 6626: 	if (exists($$record{$version.':resource.0.version'})) {
                   6627: 	    $interaction = $$record{$version.':resource.0.version'};
                   6628: 	}
1.671     raeburn  6629:         if ($isTask && $env{'form.previousversion'}) {
                   6630:             next unless ($interaction == $env{'form.previousversion'});
                   6631:         }
1.335     albertel 6632: 	my $where = ($isTask ? "$version:resource.$interaction"
                   6633: 		             : "$version:resource");
1.467     albertel 6634: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   6635: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 6636: 	if ($isCODE) {
                   6637: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   6638: 	}
1.671     raeburn  6639:         if ($isTask) {
                   6640:             $studentTable.='<td>'.$interaction.'</td>';
                   6641:         }
1.119     ng       6642: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   6643: 	my @displaySub = ();
                   6644: 	foreach my $partid (@{$parts}) {
1.640     raeburn  6645:             my ($hidden,$type);
                   6646:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   6647:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  6648:                 $hidden = 1;
                   6649:             }
1.749     raeburn  6650:             my @matchKey;
                   6651:             if ($isTask) {
1.769     raeburn  6652:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  6653:             } elsif ($is_tool) {
1.769     raeburn  6654:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  6655:             } else {
1.769     raeburn  6656:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  6657:             }
1.122     ng       6658: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 6659: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 6660: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 6661: 		if (exists($$record{$version.':'.$matchKey}) &&
                   6662: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  6663:                     if ($is_tool) {
                   6664:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  6665:                     } else {
1.749     raeburn  6666: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   6667: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   6668:                         $displaySub[0].='<span class="LC_nobreak">';
                   6669:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   6670:                                        .' <span class="LC_internal_info">'
                   6671:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   6672:                                        .'</span>'
                   6673:                                        .' <b>';
                   6674:                         if ($hidden) {
                   6675:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   6676:                         } else {
                   6677:                             my ($trial,$rndseed,$newvariation);
                   6678:                             if ($type eq 'randomizetry') {
                   6679:                                 $trial = $$record{"$where.$partid.tries"};
                   6680:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   6681:                             }
                   6682: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   6683: 			        $displaySub[0].=&mt('Trial not counted');
                   6684: 		            } else {
                   6685: 			        $displaySub[0].=&mt('Trial: [_1]',
                   6686: 					        $$record{"$where.$partid.tries"});
                   6687:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   6688:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   6689:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   6690:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   6691:                                     }
1.640     raeburn  6692:                                 }
1.749     raeburn  6693:                                 $lastrndseed{$partid} = $rndseed;
                   6694:                                 $lasttype{$partid} = $type;
                   6695: 		            }
                   6696: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 6697:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  6698: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   6699: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   6700: 			        $orders{$partid}->{$responseId}=
                   6701: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   6702:                                                $no_increment,$type,$trial,$rndseed);
                   6703: 		            }
                   6704: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   6705: 		            $displaySub[0].='&nbsp; '.
                   6706: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   6707:                         }
1.596     raeburn  6708:                     }
1.147     albertel 6709: 		}
                   6710: 	    }
1.335     albertel 6711: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 6712: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   6713: 				    $$record{"$where.$partid.checkedin"},
                   6714: 				    $$record{"$where.$partid.checkedin.slot"}).
                   6715: 					'<br />';
1.335     albertel 6716: 	    }
                   6717: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 6718: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 6719: 		    lc($$record{"$where.$partid.award"}).' '.
                   6720: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 6721: 		    '<br />';
1.749     raeburn  6722: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   6723: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   6724: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   6725: 		}
1.147     albertel 6726: 	    }
1.335     albertel 6727: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  6728: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   6729: 		unless ($is_tool) {
                   6730: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6731: 		}
1.335     albertel 6732: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   6733: 		$displaySub[2].=
1.749     raeburn  6734: 		    $$record{"$version:resource.$partid.regrader"};
                   6735:                 unless ($is_tool) {
                   6736: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6737:                 }
1.147     albertel 6738: 	    }
                   6739: 	}
                   6740: 	# needed because old essay regrader has not parts info
                   6741: 	if (exists $$record{"$version:resource.regrader"}) {
                   6742: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   6743: 	}
                   6744: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   6745: 	if ($displaySub[2]) {
1.467     albertel 6746: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 6747: 	}
1.467     albertel 6748: 	$studentTable.='&nbsp;</td>'.
                   6749: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       6750:     }
1.467     albertel 6751:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       6752:     return $studentTable;
1.71      ng       6753: }
                   6754: 
                   6755: sub updateGradeByPage {
1.608     www      6756:     my ($request,$symb) = @_;
1.71      ng       6757: 
1.257     albertel 6758:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6759:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6760:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6761:     my $pageTitle = $env{'form.page'};
1.103     albertel 6762:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6763:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6764:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 6765:     if (!&canmodify($usec)) {
1.526     raeburn  6766: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 6767: 	return;
                   6768:     }
1.398     albertel 6769:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  6770:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       6771: 	'</h3>'."\n";
1.70      ng       6772: 
1.68      ng       6773:     $request->print($result);
                   6774: 
1.582     raeburn  6775: 
1.132     bowersj2 6776:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6777:     unless (ref($navmap)) {
                   6778:         $request->print(&navmap_errormsg());
                   6779:         return;
                   6780:     }
1.257     albertel 6781:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       6782:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6783:     if (!$map) {
1.527     raeburn  6784: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 6785: 	return; 
                   6786:     }
1.71      ng       6787:     my $iterator = $navmap->getIterator($map->map_start(),
                   6788: 					$map->map_finish());
1.70      ng       6789: 
1.484     albertel 6790:     my $studentTable=
                   6791: 	&Apache::loncommon::start_data_table().
                   6792: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6793: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   6794: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   6795: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   6796: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 6797: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6798: 
                   6799:     $iterator->next(); # skip the first BEGIN_MAP
                   6800:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  6801:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.798     raeburn  6802:     my (@updates,%weights,%excuseds,%awardeds,@symbs_in_map);
1.101     albertel 6803:     while ($depth > 0) {
1.71      ng       6804:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6805:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       6806: 
1.385     albertel 6807:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 6808: 	    my $parts = $curRes->parts();
1.71      ng       6809:             my $title = $curRes->compTitle();
                   6810: 	    my $symbx = $curRes->symb();
1.798     raeburn  6811:             push(@symbs_in_map,$symbx);
1.484     albertel 6812: 	    $studentTable.=
                   6813: 		&Apache::loncommon::start_data_table_row().
                   6814: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6815: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  6816:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  6817: 		.')').'</td>';
1.71      ng       6818: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   6819: 
                   6820: 	    my %newrecord=();
                   6821: 	    my @displayPts=();
1.269     raeburn  6822:             my %aggregate = ();
                   6823:             my $aggregateflag = 0;
1.787     raeburn  6824:             my %queueable;
1.726     raeburn  6825:             if ($env{'form.HIDE'.$prob}) {
                   6826:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  6827:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  6828:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.798     raeburn  6829:                 if ($numchgs) {
                   6830:                     push(@updates,$symbx);
                   6831:                 }
1.726     raeburn  6832:                 $hideflag += $numchgs;
                   6833:             }
1.71      ng       6834: 	    foreach my $partid (@{$parts}) {
1.257     albertel 6835: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   6836: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.787     raeburn  6837:                 my @types = $curRes->responseType($partid);
1.786     raeburn  6838:                 if (grep(/^essay$/,@types)) {
                   6839:                     $queueable{$partid} = 1;
                   6840:                 } else {
1.787     raeburn  6841:                     my @ids = $curRes->responseIds($partid);
1.786     raeburn  6842:                     for (my $i=0; $i < scalar(@ids); $i++) {
1.787     raeburn  6843:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
1.786     raeburn  6844:                                                           '.handgrade',$symb);
                   6845:                         if (lc($hndgrd) eq 'yes') {
                   6846:                             $queueable{$partid} = 1;
                   6847:                             last;
                   6848:                         }
                   6849:                     }
                   6850:                 }
1.257     albertel 6851: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   6852: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.798     raeburn  6853:                 $weights{$symbx}{$partid} = $wgt;
                   6854:                 $excuseds{$symbx}{$partid} = '';
1.71      ng       6855: 		my $partial = $newpts/$wgt;
                   6856: 		my $score;
                   6857: 		if ($partial > 0) {
                   6858: 		    $score = 'correct_by_override';
1.125     ng       6859: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       6860: 		    $score = 'incorrect_by_override';
                   6861: 		}
1.257     albertel 6862: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       6863: 		if ($dropMenu eq 'excused') {
1.71      ng       6864: 		    $partial = '';
                   6865: 		    $score = 'excused';
1.798     raeburn  6866:                     $excuseds{$symbx}{$partid} = 1;
1.125     ng       6867: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 6868: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       6869: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   6870: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   6871: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   6872: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 6873: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       6874: 		    $changeflag++;
                   6875: 		    $newpts = '';
1.269     raeburn  6876:                     
                   6877:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   6878:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   6879:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   6880:                     if ($aggtries > 0) {
                   6881:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   6882:                         $aggregateflag = 1;
                   6883:                     }
1.71      ng       6884: 		}
1.324     albertel 6885: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 6886: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  6887: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       6888: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 6889: 		    '&nbsp;<br />';
1.526     raeburn  6890: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       6891: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 6892: 		    '&nbsp;<br />';
1.71      ng       6893: 		$question++;
1.798     raeburn  6894:                 if (($newpts eq '') || ($partial eq '')) {
                   6895:                     $awardeds{$symbx}{$partid} = 0;
                   6896:                 } else {
                   6897:                     $awardeds{$symbx}{$partid} = $partial;
                   6898:                 }
1.380     albertel 6899: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       6900: 
1.71      ng       6901: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       6902: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 6903: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       6904: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       6905: 
                   6906: 		$changeflag++;
                   6907: 	    }
                   6908: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 6909: 		my %record = 
                   6910: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   6911: 					     $udom,$uname);
                   6912: 
                   6913: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   6914: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   6915: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   6916: 		    $newrecord{'resource.CODE'} = '';
                   6917: 		}
1.257     albertel 6918: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       6919: 					$udom,$uname);
1.382     albertel 6920: 		%record = &Apache::lonnet::restore($symbx,
                   6921: 						   $env{'request.course.id'},
                   6922: 						   $udom,$uname);
1.380     albertel 6923: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.786     raeburn  6924: 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       6925: 	    }
1.380     albertel 6926: 	    
1.269     raeburn  6927:             if ($aggregateflag) {
                   6928:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   6929:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   6930:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   6931:             }
1.125     ng       6932: 
1.71      ng       6933: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   6934: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 6935: 		&Apache::loncommon::end_data_table_row();
1.68      ng       6936: 
1.196     albertel 6937: 	    $prob++;
1.798     raeburn  6938:             if ($changeflag) {
                   6939:                 push(@updates,$symbx);
                   6940:             }
1.68      ng       6941: 	}
1.71      ng       6942:         $curRes = $iterator->next();
1.68      ng       6943:     }
1.98      albertel 6944: 
1.484     albertel 6945:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  6946:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   6947: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  6948: 		  $changeflag).'<br />');
                   6949:     my $hidemsg=($hideflag == 0 ? '' :
                   6950:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   6951:                      $hideflag).'<br />');
                   6952:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       6953: 
1.798     raeburn  6954:     if (@updates) {
                   6955:         my (@allsymbs,$mapsymb,@recurseup,%parentmapsymbs,%possmappb,%possrespb);
                   6956:         @allsymbs = @updates;
                   6957:         if (ref($map)) {
                   6958:             $mapsymb = $map->symb();
                   6959:             push(@allsymbs,$mapsymb);
                   6960:             @recurseup = $navmap->recurseup_maps($map->src,1);
                   6961:         }
                   6962:         if (@recurseup) {
                   6963:             push(@allsymbs,@recurseup);
                   6964:             map { $parentmapsymbs{$_} = 1; } @recurseup;
                   6965:         }
                   6966:         my %passback = &Apache::lonnet::get('nohist_linkprot_passback',\@allsymbs,$cdom,$cnum);
                   6967:         my (%uniqsymbs,$use_symbs_in_map);
                   6968:         if (keys(%passback)) {
                   6969:             foreach my $possible (keys(%passback)) {
                   6970:                 if (ref($passback{$possible}) eq 'HASH') {
                   6971:                     if ($possible eq $mapsymb) {
                   6972:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   6973:                             $possmappb{$launcher} = 1;
                   6974:                         }
                   6975:                         $use_symbs_in_map = 1;
                   6976:                     } elsif (exists($parentmapsymbs{$possible})) {
                   6977:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   6978:                             my ($linkuri,$linkprotector,$scope) = split(/\0/,$launcher);
                   6979:                             if ($scope eq 'rec') {
                   6980:                                 $possmappb{$launcher} = 1;
                   6981:                                 $use_symbs_in_map = 1;
                   6982:                             }
                   6983:                         }
                   6984:                     } elsif (grep(/^\Q$possible$\E$/,@updates)) {
                   6985:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   6986:                             $possrespb{$launcher} = 1;
                   6987:                         }
                   6988:                         $uniqsymbs{$possible} = 1;
                   6989:                     }
                   6990:                 }
                   6991:             }
                   6992:         }
                   6993:         if ($use_symbs_in_map) {
                   6994:             map { $uniqsymbs{$_} = 1; } @symbs_in_map;
                   6995:         }
                   6996:         my @posslaunchers;
                   6997:         if (keys(%possmappb)) {
                   6998:             push(@posslaunchers,keys(%possmappb));
                   6999:         }
                   7000:         if (keys(%possrespb)) {
                   7001:             push(@posslaunchers,keys(%possrespb));
                   7002:         }
                   7003:         if (@posslaunchers) {
                   7004:             my (%pbsave,%skip_passback,%needpb);
                   7005:             my %pbids = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@posslaunchers,$udom,$uname);
                   7006:             foreach my $key (keys(%pbids)) {
                   7007:                 if (ref($pbids{$key}) eq 'ARRAY') {
                   7008:                     $needpb{$key} = 1;
                   7009:                 }
                   7010:             }
                   7011:             my @symbs = keys(%uniqsymbs);
                   7012:             &process_passbacks('updatebypage',\@symbs,$cdom,$cnum,$udom,$uname,\%weights,
                   7013:                                \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave,\%pbids);
1.801   ! raeburn  7014:             if (@Apache::grades::ltipassback) {
1.798     raeburn  7015:                 unless ($registered_cleanup) {
                   7016:                     my $handlers = $request->get_handlers('PerlCleanupHandler');
                   7017:                     $request->set_handlers('PerlCleanupHandler' =>
1.801   ! raeburn  7018:                                            [\&Apache::grades::make_passback,@{$handlers}]);
        !          7019:                     $registered_cleanup=1;
1.798     raeburn  7020:                 }
                   7021:             }
                   7022:         }
                   7023:     }
1.70      ng       7024:     return '';
                   7025: }
                   7026: 
1.801   ! raeburn  7027: sub make_passback {
        !          7028:     if (@Apache::grades::ltipassback) {
        !          7029:         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
        !          7030:         my $ip = &Apache::lonnet::get_host_ip($lonhost);
        !          7031:         foreach my $item (@Apache::grades::ltipassback) {
        !          7032:             &Apache::lonhomework::run_passback($item,$lonhost,$ip);
        !          7033:         }
        !          7034:         undef(@Apache::grades::ltipassback);
        !          7035:     }
        !          7036: }
        !          7037: 
1.72      ng       7038: #-------- end of section for handling grading by page/sequence ---------
                   7039: #
                   7040: #-------------------------------------------------------------------
                   7041: 
1.581     www      7042: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 7043: #
                   7044: #------ start of section for handling grading by page/sequence ---------
                   7045: 
1.423     albertel 7046: =pod
                   7047: 
                   7048: =head1 Bubble sheet grading routines
                   7049: 
1.424     albertel 7050:   For this documentation:
                   7051: 
                   7052:    'scanline' refers to the full line of characters
                   7053:    from the file that we are parsing that represents one entire sheet
                   7054: 
                   7055:    'bubble line' refers to the data
1.659     raeburn  7056:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 7057: 
                   7058: 
1.659     raeburn  7059: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 7060: into a course. When a user wants to grade, they select a
1.659     raeburn  7061: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 7062: one of the predefined configurations for what each scanline looks
                   7063: like.
                   7064: 
                   7065: Next each scanline is checked for any errors of either 'missing
1.435     foxr     7066: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 7067: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   7068: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  7069: invalid student/employee ID
1.424     albertel 7070: 
                   7071: If the CODE option is used that determines the randomization of the
1.556     weissno  7072: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 7073: username:domain.
                   7074: 
                   7075: During the validation phase the instructor can choose to skip scanlines. 
                   7076: 
1.659     raeburn  7077: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 7078: 
                   7079:   scantron_original_filename (unmodified original file)
                   7080:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   7081:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   7082: 
                   7083: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  7084: correction information that isn't representable in the bubblesheet
1.424     albertel 7085: file (see &scantron_getfile() for more information)
                   7086: 
                   7087: After all scanlines are either valid, marked as valid or skipped, then
                   7088: foreach line foreach problem in the picked sequence, an ssi request is
                   7089: made that simulates a user submitting their selected letter(s) against
                   7090: the homework problem.
1.423     albertel 7091: 
                   7092: =over 4
                   7093: 
                   7094: 
                   7095: 
                   7096: =item defaultFormData
                   7097: 
                   7098:   Returns html hidden inputs used to hold context/default values.
                   7099: 
                   7100:  Arguments:
                   7101:   $symb - $symb of the current resource 
                   7102: 
                   7103: =cut
1.422     foxr     7104: 
1.81      albertel 7105: sub defaultFormData {
1.324     albertel 7106:     my ($symb)=@_;
1.766     raeburn  7107:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 7108: }
                   7109: 
1.447     foxr     7110: 
1.423     albertel 7111: =pod 
                   7112: 
                   7113: =item getSequenceDropDown
                   7114: 
                   7115:    Return html dropdown of possible sequences to grade
                   7116:  
                   7117:  Arguments:
1.582     raeburn  7118:    $symb - $symb of the current resource
                   7119:    $map_error - ref to scalar which will container error if
                   7120:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 7121: 
                   7122: =cut
1.422     foxr     7123: 
1.75      albertel 7124: sub getSequenceDropDown {
1.582     raeburn  7125:     my ($symb,$map_error)=@_;
1.75      albertel 7126:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  7127:     my ($titles,$symbx) = &getSymbMap($map_error);
                   7128:     if (ref($map_error)) {
                   7129:         return if ($$map_error);
                   7130:     }
1.137     albertel 7131:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 7132:     my $ctr=0;
                   7133:     foreach (@$titles) {
                   7134: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   7135: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 7136: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 7137: 	    '>'.$showtitle.'</option>'."\n";
                   7138: 	$ctr++;
                   7139:     }
                   7140:     $result.= '</select>';
                   7141:     return $result;
                   7142: }
                   7143: 
1.495     albertel 7144: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  7145:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 7146: 
                   7147: my %first_bubble_line;             # First bubble line no. for each bubble.
                   7148: 
1.509     raeburn  7149: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   7150:                                    # matchresponse or rankresponse, where 
                   7151:                                    # an individual response can have multiple 
                   7152:                                    # lines
1.503     raeburn  7153: 
                   7154: my %responsetype_per_response;     # responsetype for each response
                   7155: 
1.691     raeburn  7156: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   7157:                                    # numbered response. Needed when randomorder
                   7158:                                    # or randompick are in use. Key is ID, value 
                   7159:                                    # is response number.
                   7160: 
1.495     albertel 7161: # Save and restore the bubble lines array to the form env.
                   7162: 
                   7163: 
                   7164: sub save_bubble_lines {
                   7165:     foreach my $line (keys(%bubble_lines_per_response)) {
                   7166: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   7167: 	$env{"form.scantron.first_bubble_line.$line"} =
                   7168: 	    $first_bubble_line{$line};
1.503     raeburn  7169:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   7170:             $subdivided_bubble_lines{$line};
                   7171:         $env{"form.scantron.responsetype.$line"} =
                   7172:             $responsetype_per_response{$line};
1.495     albertel 7173:     }
1.691     raeburn  7174:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   7175:         my $line = $masterseq_id_responsenum{$resid};
                   7176:         $env{"form.scantron.residpart.$line"} = $resid;
                   7177:     }
1.495     albertel 7178: }
                   7179: 
                   7180: 
                   7181: sub restore_bubble_lines {
                   7182:     my $line = 0;
                   7183:     %bubble_lines_per_response = ();
1.691     raeburn  7184:     %masterseq_id_responsenum = ();
1.495     albertel 7185:     while ($env{"form.scantron.bubblelines.$line"}) {
                   7186: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   7187: 	$bubble_lines_per_response{$line} = $value;
                   7188: 	$first_bubble_line{$line}  =
                   7189: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  7190:         $subdivided_bubble_lines{$line} =
                   7191:             $env{"form.scantron.sub_bubblelines.$line"};
                   7192:         $responsetype_per_response{$line} =
                   7193:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  7194:         my $id = $env{"form.scantron.residpart.$line"};
                   7195:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 7196: 	$line++;
                   7197:     }
                   7198: }
                   7199: 
1.423     albertel 7200: =pod 
                   7201: 
                   7202: =item scantron_filenames
                   7203: 
                   7204:    Returns a list of the scantron files in the current course 
                   7205: 
                   7206: =cut
1.422     foxr     7207: 
1.202     albertel 7208: sub scantron_filenames {
1.257     albertel 7209:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7210:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  7211:     my $getpropath = 1;
1.662     raeburn  7212:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   7213:                                                         $cname,$getpropath);
1.202     albertel 7214:     my @possiblenames;
1.662     raeburn  7215:     if (ref($dirlist) eq 'ARRAY') {
                   7216:         foreach my $filename (sort(@{$dirlist})) {
                   7217: 	    ($filename)=split(/&/,$filename);
                   7218: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   7219: 	    $filename=~s/^scantron_orig_//;
                   7220: 	    push(@possiblenames,$filename);
                   7221:         }
1.202     albertel 7222:     }
                   7223:     return @possiblenames;
                   7224: }
                   7225: 
1.423     albertel 7226: =pod 
                   7227: 
                   7228: =item scantron_uploads
                   7229: 
                   7230:    Returns  html drop-down list of scantron files in current course.
                   7231: 
                   7232:  Arguments:
                   7233:    $file2grade - filename to set as selected in the dropdown
                   7234: 
                   7235: =cut
1.422     foxr     7236: 
1.202     albertel 7237: sub scantron_uploads {
1.209     ng       7238:     my ($file2grade) = @_;
1.202     albertel 7239:     my $result=	'<select name="scantron_selectfile">';
                   7240:     $result.="<option></option>";
                   7241:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 7242: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 7243:     }
                   7244:     $result.="</select>";
                   7245:     return $result;
                   7246: }
                   7247: 
1.423     albertel 7248: =pod 
                   7249: 
                   7250: =item scantron_scantab
                   7251: 
                   7252:   Returns html drop down of the scantron formats in the scantronformat.tab
                   7253:   file.
                   7254: 
                   7255: =cut
1.422     foxr     7256: 
1.82      albertel 7257: sub scantron_scantab {
                   7258:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 7259:     $result.='<option></option>'."\n";
1.754     raeburn  7260:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  7261:     if (@lines > 0) {
                   7262:         foreach my $line (@lines) {
                   7263:             next if (($line =~ /^\#/) || ($line eq ''));
                   7264: 	    my ($name,$descrip)=split(/:/,$line);
                   7265: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   7266:         }
1.82      albertel 7267:     }
                   7268:     $result.='</select>'."\n";
1.518     raeburn  7269:     return $result;
                   7270: }
                   7271: 
1.423     albertel 7272: =pod 
                   7273: 
                   7274: =item scantron_CODElist
                   7275: 
                   7276:   Returns html drop down of the saved CODE lists from current course,
                   7277:   generated from earlier printings.
                   7278: 
                   7279: =cut
1.422     foxr     7280: 
1.186     albertel 7281: sub scantron_CODElist {
1.257     albertel 7282:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7283:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 7284:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   7285:     my $namechoice='<option></option>';
1.225     albertel 7286:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 7287: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 7288: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 7289: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   7290:     }
                   7291:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   7292:     return $namechoice;
                   7293: }
                   7294: 
1.423     albertel 7295: =pod 
                   7296: 
                   7297: =item scantron_CODEunique
                   7298: 
                   7299:   Returns the html for "Each CODE to be used once" radio.
                   7300: 
                   7301: =cut
1.422     foxr     7302: 
1.186     albertel 7303: sub scantron_CODEunique {
1.532     bisitz   7304:     my $result='<span class="LC_nobreak">
1.272     albertel 7305:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7306:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 7307:                 </span>
1.532     bisitz   7308:                 <span class="LC_nobreak">
1.272     albertel 7309:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7310:                         value="no" />'.&mt('No').' </label>
1.381     albertel 7311:                 </span>';
1.186     albertel 7312:     return $result;
                   7313: }
1.423     albertel 7314: 
                   7315: =pod 
                   7316: 
                   7317: =item scantron_selectphase
                   7318: 
1.659     raeburn  7319:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 7320:   Allows for - starting a grading run.
1.424     albertel 7321:              - downloading existing scan data (original, corrected
1.423     albertel 7322:                                                 or skipped info)
                   7323: 
                   7324:              - uploading new scan data
                   7325: 
                   7326:  Arguments:
                   7327:   $r          - The Apache request object
                   7328:   $file2grade - name of the file that contain the scanned data to score
                   7329: 
                   7330: =cut
1.186     albertel 7331: 
1.75      albertel 7332: sub scantron_selectphase {
1.608     www      7333:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 7334:     if (!$symb) {return '';}
1.582     raeburn  7335:     my $map_error;
                   7336:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   7337:     if ($map_error) {
                   7338:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   7339:         return;
                   7340:     }
1.324     albertel 7341:     my $default_form_data=&defaultFormData($symb);
1.209     ng       7342:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 7343:     my $format_selector=&scantron_scantab();
1.186     albertel 7344:     my $CODE_selector=&scantron_CODElist();
                   7345:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 7346:     my $result;
1.422     foxr     7347: 
1.513     foxr     7348:     $ssi_error = 0;
                   7349: 
1.770     raeburn  7350:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 7351: 
                   7352: 	# Chunk of form to prompt for a scantron file upload.
                   7353: 
                   7354:         $r->print('
1.754     raeburn  7355:     <br />');
1.606     wenzelju 7356:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7357:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  7358:     my $csec= $env{'request.course.sec'};
1.736     damieng  7359:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   7360:     &js_escape(\$alertmsg);
1.754     raeburn  7361:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 7362:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   7363:     function checkUpload(formname) {
                   7364: 	if (formname.upfile.value == "") {
1.736     damieng  7365: 	    alert("'.$alertmsg.'");
1.606     wenzelju 7366: 	    return false;
                   7367: 	}
                   7368: 	formname.submit();
1.756     raeburn  7369:     }'."\n".$formatjs));
1.606     wenzelju 7370:     $r->print('
                   7371:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7372:                 '.$default_form_data.'
                   7373:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  7374:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 7375:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   7376:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  7377:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7378:               '.&Apache::loncommon::start_data_table_header_row().'
                   7379:                 <th>
                   7380:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   7381:                 </th>
                   7382:               '.&Apache::loncommon::end_data_table_header_row().'
                   7383:               '.&Apache::loncommon::start_data_table_row().'
                   7384:             <td>
                   7385:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   7386:     if ($formatoptions) {
                   7387:         $r->print('</td>
                   7388:                  '.&Apache::loncommon::end_data_table_row().'
                   7389:                  '.&Apache::loncommon::start_data_table_row().'
                   7390:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   7391:                  </td>
                   7392:                  '.&Apache::loncommon::end_data_table_row().'
                   7393:                  '.&Apache::loncommon::start_data_table_row().'
                   7394:                  <td>'
                   7395:         );
                   7396:     } else {
                   7397:         $r->print(' <br />');
                   7398:     }
                   7399:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   7400:               </td>
                   7401:              '.&Apache::loncommon::end_data_table_row().'
                   7402:              '.&Apache::loncommon::end_data_table().'
                   7403:              </form>'
                   7404:     );
1.606     wenzelju 7405: 
                   7406:     }
                   7407: 
1.422     foxr     7408:     # Chunk of form to prompt for a file to grade and how:
                   7409: 
1.489     albertel 7410:     $result.= '
                   7411:     <br />
                   7412:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   7413:     <input type="hidden" name="command" value="scantron_warning" />
                   7414:     '.$default_form_data.'
                   7415:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7416:        '.&Apache::loncommon::start_data_table_header_row().'
                   7417:             <th colspan="2">
1.492     albertel 7418:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 7419:             </th>
                   7420:        '.&Apache::loncommon::end_data_table_header_row().'
                   7421:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7422:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 7423:        '.&Apache::loncommon::end_data_table_row().'
                   7424:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      7425:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 7426:        '.&Apache::loncommon::end_data_table_row().'
                   7427:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      7428:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 7429:        '.&Apache::loncommon::end_data_table_row().'
                   7430:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7431:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 7432:        '.&Apache::loncommon::end_data_table_row().'
                   7433:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7434:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 7435:        '.&Apache::loncommon::end_data_table_row().'
                   7436:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7437: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 7438:             <td>
1.492     albertel 7439: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   7440:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   7441:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 7442: 	    </td>
1.489     albertel 7443:        '.&Apache::loncommon::end_data_table_row().'
                   7444:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 7445:             <td colspan="2">
1.572     www      7446:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 7447:             </td>
1.489     albertel 7448:        '.&Apache::loncommon::end_data_table_row().'
                   7449:     '.&Apache::loncommon::end_data_table().'
                   7450:     </form>
                   7451: ';
1.162     albertel 7452:    
                   7453:     $r->print($result);
                   7454: 
1.422     foxr     7455:     # Chunk of the form that prompts to view a scoring office file,
                   7456:     # corrected file, skipped records in a file.
                   7457: 
1.489     albertel 7458:     $r->print('
                   7459:    <br />
                   7460:    <form action="/adm/grades" name="scantron_download">
                   7461:      '.$default_form_data.'
                   7462:      <input type="hidden" name="command" value="scantron_download" />
                   7463:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7464:        '.&Apache::loncommon::start_data_table_header_row().'
                   7465:               <th>
1.492     albertel 7466:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 7467:               </th>
                   7468:        '.&Apache::loncommon::end_data_table_header_row().'
                   7469:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7470:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 7471:                 <br />
1.492     albertel 7472:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 7473:        '.&Apache::loncommon::end_data_table_row().'
                   7474:      '.&Apache::loncommon::end_data_table().'
                   7475:    </form>
                   7476:    <br />
                   7477: ');
1.162     albertel 7478: 
1.457     banghart 7479:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  7480: 
1.694     bisitz   7481:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  7482:              $default_form_data."\n".
                   7483:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   7484:              &Apache::loncommon::start_data_table_header_row()."\n".
                   7485:              '<th colspan="2">
1.572     www      7486:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  7487:              '</th>'."\n".
                   7488:               &Apache::loncommon::end_data_table_header_row()."\n".
                   7489:               &Apache::loncommon::start_data_table_row()."\n".
                   7490:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   7491:               '<td> '.$sequence_selector.' </td>'.
                   7492:               &Apache::loncommon::end_data_table_row()."\n".
                   7493:               &Apache::loncommon::start_data_table_row()."\n".
                   7494:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   7495:               '<td> '.$file_selector.' </td>'."\n".
                   7496:               &Apache::loncommon::end_data_table_row()."\n".
                   7497:               &Apache::loncommon::start_data_table_row()."\n".
                   7498:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   7499:               '<td> '.$format_selector.' </td>'."\n".
                   7500:               &Apache::loncommon::end_data_table_row()."\n".
                   7501:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  7502:               '<td> '.&mt('Options').' </td>'."\n".
                   7503:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   7504:               &Apache::loncommon::end_data_table_row()."\n".
                   7505:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  7506:               '<td colspan="2">'."\n".
                   7507:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      7508:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  7509:               '</td>'."\n".
                   7510:               &Apache::loncommon::end_data_table_row()."\n".
                   7511:               &Apache::loncommon::end_data_table()."\n".
                   7512:               '</form><br />');
                   7513:     return;
1.75      albertel 7514: }
                   7515: 
1.423     albertel 7516: =pod 
                   7517: 
                   7518: =item username_to_idmap
                   7519: 
1.556     weissno  7520:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  7521:     student username:domain. If a single ID occurs for more than one student,
                   7522:     the status of the student is checked, and if Active, the value in the hash
                   7523:     will be set to the Active student.
1.423     albertel 7524: 
                   7525:   Arguments:
                   7526: 
                   7527:     $classlist - reference to the class list hash. This is a hash
                   7528:                  keyed by student name:domain  whose elements are references
1.424     albertel 7529:                  to arrays containing various chunks of information
1.423     albertel 7530:                  about the student. (See loncoursedata for more info).
                   7531: 
                   7532:   Returns
                   7533:     %idmap - the constructed hash
                   7534: 
                   7535: =cut
                   7536: 
1.82      albertel 7537: sub username_to_idmap {
                   7538:     my ($classlist)= @_;
                   7539:     my %idmap;
                   7540:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  7541:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   7542:         unless ($id eq '') {
                   7543:             if (!exists($idmap{$id})) {
                   7544:                 $idmap{$id} = $student;
                   7545:             } else {
                   7546:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   7547:                 if ($status eq 'Active') {
                   7548:                     $idmap{$id} = $student;
                   7549:                 }
                   7550:             }
                   7551:         }
1.82      albertel 7552:     }
                   7553:     return %idmap;
                   7554: }
1.423     albertel 7555: 
                   7556: =pod
                   7557: 
1.424     albertel 7558: =item scantron_fixup_scanline
1.423     albertel 7559: 
                   7560:    Process a requested correction to a scanline.
                   7561: 
                   7562:   Arguments:
1.754     raeburn  7563:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 7564:     $scan_data         - hash of correction information 
                   7565:                           (see &scantron_getfile())
                   7566:     $line              - existing scanline
                   7567:     $whichline         - line number of the passed in scanline
                   7568:     $field             - type of change to process 
                   7569:                          (either 
1.573     bisitz   7570:                           'ID'     -> correct the student/employee ID
1.423     albertel 7571:                           'CODE'   -> correct the CODE
                   7572:                           'answer' -> fixup the submitted answers)
                   7573:     
                   7574:    $args               - hash of additional info,
                   7575:                           - 'ID' 
                   7576:                                'newid' -> studentID to use in replacement
1.424     albertel 7577:                                           of existing one
1.423     albertel 7578:                           - 'CODE' 
                   7579:                                'CODE_ignore_dup' - set to true if duplicates
                   7580:                                                    should be ignored.
                   7581: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 7582:                                         if the existing unfound code should
1.423     albertel 7583:                                         be used as is
                   7584:                           - 'answer'
                   7585:                                'response' - new answer or 'none' if blank
                   7586:                                'question' - the bubble line to change
1.503     raeburn  7587:                                'questionnum' - the question identifier,
                   7588:                                                may include subquestion. 
1.423     albertel 7589: 
                   7590:   Returns:
                   7591:     $line - the modified scanline
                   7592: 
                   7593:   Side effects: 
                   7594:     $scan_data - may be updated
                   7595: 
                   7596: =cut
                   7597: 
1.82      albertel 7598: 
1.157     albertel 7599: sub scantron_fixup_scanline {
                   7600:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   7601:     if ($field eq 'ID') {
                   7602: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 7603: 	    return ($line,1,'New value too large');
1.157     albertel 7604: 	}
                   7605: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   7606: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   7607: 				     $args->{'newid'});
                   7608: 	}
                   7609: 	substr($line,$$scantron_config{'IDstart'}-1,
                   7610: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   7611: 	if ($args->{'newid'}=~/^\s*$/) {
                   7612: 	    &scan_data($scan_data,"$whichline.user",
                   7613: 		       $args->{'username'}.':'.$args->{'domain'});
                   7614: 	}
1.186     albertel 7615:     } elsif ($field eq 'CODE') {
1.192     albertel 7616: 	if ($args->{'CODE_ignore_dup'}) {
                   7617: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   7618: 	}
                   7619: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   7620: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 7621: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   7622: 		return ($line,1,'New CODE value too large');
                   7623: 	    }
                   7624: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   7625: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   7626: 	    }
                   7627: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   7628: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 7629: 	}
1.157     albertel 7630:     } elsif ($field eq 'answer') {
1.497     foxr     7631: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 7632: 	my $off=$scantron_config->{'Qoff'};
                   7633: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     7634: 	my $answer=${off}x$length;
                   7635: 	if ($args->{'response'} eq 'none') {
                   7636: 	    &scan_data($scan_data,
1.503     raeburn  7637: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     7638: 	} else {
                   7639: 	    if ($on eq 'letter') {
                   7640: 		my @alphabet=('A'..'Z');
                   7641: 		$answer=$alphabet[$args->{'response'}];
                   7642: 	    } elsif ($on eq 'number') {
                   7643: 		$answer=$args->{'response'}+1;
                   7644: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 7645: 	    } else {
1.497     foxr     7646: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 7647: 	    }
1.497     foxr     7648: 	    &scan_data($scan_data,
1.503     raeburn  7649: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 7650: 	}
1.497     foxr     7651: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   7652: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 7653:     }
                   7654:     return $line;
                   7655: }
1.423     albertel 7656: 
                   7657: =pod
                   7658: 
                   7659: =item scan_data
                   7660: 
                   7661:     Edit or look up  an item in the scan_data hash.
                   7662: 
                   7663:   Arguments:
                   7664:     $scan_data  - The hash (see scantron_getfile)
                   7665:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 7666:                   scantronfilename_key).
1.423     albertel 7667:     $data        - New value of the hash entry.
                   7668:     $delete      - If true, the entry is removed from the hash.
                   7669: 
                   7670:   Returns:
                   7671:     The new value of the hash table field (undefined if deleted).
                   7672: 
                   7673: =cut
                   7674: 
                   7675: 
1.157     albertel 7676: sub scan_data {
                   7677:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 7678:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 7679:     if (defined($value)) {
                   7680: 	$scan_data->{$filename.'_'.$key} = $value;
                   7681:     }
                   7682:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   7683:     return $scan_data->{$filename.'_'.$key};
                   7684: }
1.423     albertel 7685: 
1.495     albertel 7686: # ----- These first few routines are general use routines.----
                   7687: 
                   7688: # Return the number of occurences of a pattern in a string.
                   7689: 
                   7690: sub occurence_count {
                   7691:     my ($string, $pattern) = @_;
                   7692: 
                   7693:     my @matches = ($string =~ /$pattern/g);
                   7694: 
                   7695:     return scalar(@matches);
                   7696: }
                   7697: 
                   7698: 
                   7699: # Take a string known to have digits and convert all the
                   7700: # digits into letters in the range J,A..I.
                   7701: 
                   7702: sub digits_to_letters {
                   7703:     my ($input) = @_;
                   7704: 
                   7705:     my @alphabet = ('J', 'A'..'I');
                   7706: 
                   7707:     my @input    = split(//, $input);
                   7708:     my $output ='';
                   7709:     for (my $i = 0; $i < scalar(@input); $i++) {
                   7710: 	if ($input[$i] =~ /\d/) {
                   7711: 	    $output .= $alphabet[$input[$i]];
                   7712: 	} else {
                   7713: 	    $output .= $input[$i];
                   7714: 	}
                   7715:     }
                   7716:     return $output;
                   7717: }
                   7718: 
1.423     albertel 7719: =pod 
                   7720: 
                   7721: =item scantron_parse_scanline
                   7722: 
1.711     bisitz   7723:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 7724: 
                   7725:  Arguments:
1.711     bisitz   7726:     line             - The text of the bubblesheet file line to process
1.423     albertel 7727:     whichline        - Line number
1.711     bisitz   7728:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 7729:     scan_data        - Hash of extra information about the scanline
                   7730:                        (see scantron_getfile for more information)
                   7731:     just_header      - True if should not process question answers but only
                   7732:                        the stuff to the left of the answers.
1.691     raeburn  7733:     randomorder      - True if randomorder in use
                   7734:     randompick       - True if randompick in use
                   7735:     sequence         - Exam folder URL
                   7736:     master_seq       - Ref to array containing symbs in exam folder
                   7737:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   7738:                        (corresponding values are resource objects)
                   7739:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   7740:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   7741:                        are refs to an array of resource objects, ordered
                   7742:                        according to order used for CODE, when randomorder
                   7743:                        and or randompick are in use.
                   7744:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   7745:                        for current line to question number used for same question
                   7746:                         in "Master Sequence" (as seen by Course Coordinator).
                   7747:     startline        - Ref to hash where key is question number (0 is first)
                   7748:                        and value is number of first bubble line for current 
                   7749:                        student or code-based randompick and/or randomorder.
                   7750:     totalref         - Ref of scalar used to score total number of bubble
                   7751:                        lines needed for responses in a scan line (used when
                   7752:                        randompick in use. 
                   7753:     
1.423     albertel 7754:  Returns:
                   7755:    Hash containing the result of parsing the scanline
                   7756: 
                   7757:    Keys are all proceeded by the string 'scantron.'
                   7758: 
                   7759:        CODE    - the CODE in use for this scanline
                   7760:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   7761:                  by the operator
                   7762:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   7763:                             CODEs were selected, but the usage has been
                   7764:                             forced by the operator
1.556     weissno  7765:        ID  - student/employee ID
1.423     albertel 7766:        PaperID - if used, the ID number printed on the sheet when the 
                   7767:                  paper was scanned
                   7768:        FirstName - first name from the sheet
                   7769:        LastName  - last name from the sheet
                   7770: 
                   7771:      if just_header was not true these key may also exist
                   7772: 
1.447     foxr     7773:        missingerror - a list of bubble ranges that are considered to be answers
                   7774:                       to a single question that don't have any bubbles filled in.
                   7775:                       Of the form questionnumber:firstbubblenumber:count.
                   7776:        doubleerror  - a list of bubble ranges that are considered to be answers
                   7777:                       to a single question that have more than one bubble filled in.
                   7778:                       Of the form questionnumber::firstbubblenumber:count
                   7779:    
                   7780:                 In the above, count is the number of bubble responses in the
                   7781:                 input line needed to represent the possible answers to the question.
                   7782:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   7783:                 per line would have count = 2.
                   7784: 
1.423     albertel 7785:        maxquest     - the number of the last bubble line that was parsed
                   7786: 
                   7787:        (<number> starts at 1)
                   7788:        <number>.answer - zero or more letters representing the selected
                   7789:                          letters from the scanline for the bubble line 
                   7790:                          <number>.
                   7791:                          if blank there was either no bubble or there where
                   7792:                          multiple bubbles, (consult the keys missingerror and
                   7793:                          doubleerror if this is an error condition)
                   7794: 
                   7795: =cut
                   7796: 
1.82      albertel 7797: sub scantron_parse_scanline {
1.691     raeburn  7798:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   7799:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   7800:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     7801: 
1.82      albertel 7802:     my %record;
1.691     raeburn  7803:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 7804:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   7805: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   7806: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   7807: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   7808: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 7809: 	    $record{'scantron.CODE'}=substr($data,
                   7810: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 7811: 					    $$scantron_config{'CODElength'});
1.191     albertel 7812: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   7813: 		$record{'scantron.useCODE'}=1;
                   7814: 	    }
1.192     albertel 7815: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   7816: 		$record{'scantron.CODE_ignore_dup'}=1;
                   7817: 	    }
1.82      albertel 7818: 	} else {
                   7819: 	    #FIXME interpret first N questions
                   7820: 	}
                   7821:     }
1.83      albertel 7822:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   7823: 				  $$scantron_config{'IDlength'});
1.157     albertel 7824:     $record{'scantron.PaperID'}=
                   7825: 	substr($data,$$scantron_config{'PaperID'}-1,
                   7826: 	       $$scantron_config{'PaperIDlength'});
                   7827:     $record{'scantron.FirstName'}=
                   7828: 	substr($data,$$scantron_config{'FirstName'}-1,
                   7829: 	       $$scantron_config{'FirstNamelength'});
                   7830:     $record{'scantron.LastName'}=
                   7831: 	substr($data,$$scantron_config{'LastName'}-1,
                   7832: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 7833:     if ($just_header) { return \%record; }
1.194     albertel 7834: 
1.82      albertel 7835:     my @alphabet=('A'..'Z');
                   7836:     my $questnum=0;
1.447     foxr     7837:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   7838: 
1.691     raeburn  7839:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   7840:     if ($randompick || $randomorder) {
                   7841:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   7842:                                          $master_seq,$symb_to_resource,
                   7843:                                          $partids_by_symb,$orderedforcode,
                   7844:                                          $respnumlookup,$startline);
                   7845:         if ($total) {
                   7846:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   7847:         }
                   7848:         if (ref($totalref)) {
                   7849:             $$totalref = $total;
                   7850:         }
                   7851:     }
                   7852:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     7853:     chomp($questions);		# Get rid of any trailing \n.
                   7854:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   7855:     while (length($questions)) {
1.691     raeburn  7856:         my $answers_needed;
                   7857:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7858:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   7859:         } else {
                   7860: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   7861:         }
1.503     raeburn  7862:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   7863:                              || 1;
                   7864:         $questnum++;
                   7865:         my $quest_id = $questnum;
                   7866:         my $currentquest = substr($questions,0,$answer_length);
                   7867:         $questions       = substr($questions,$answer_length);
                   7868:         if (length($currentquest) < $answer_length) { next; }
                   7869: 
1.691     raeburn  7870:         my $subdivided;
                   7871:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7872:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   7873:         } else {
                   7874:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   7875:         }
                   7876:         if ($subdivided =~ /,/) {
1.503     raeburn  7877:             my $subquestnum = 1;
                   7878:             my $subquestions = $currentquest;
1.691     raeburn  7879:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  7880:             foreach my $subans (@subanswers_needed) {
                   7881:                 my $subans_length =
                   7882:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   7883:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   7884:                 $subquestions   = substr($subquestions,$subans_length);
                   7885:                 $quest_id = "$questnum.$subquestnum";
                   7886:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   7887:                     ($$scantron_config{'Qon'} eq 'number')) {
                   7888:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   7889:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  7890:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7891:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7892:                 } else {
                   7893:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  7894:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   7895:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7896:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7897:                 }
                   7898:                 $subquestnum ++;
                   7899:             }
                   7900:         } else {
                   7901:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   7902:                 ($$scantron_config{'Qon'} eq 'number')) {
                   7903:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   7904:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7905:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7906:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7907:             } else {
                   7908:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   7909:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7910:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7911:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7912:             }
                   7913:         }
                   7914:     }
                   7915:     $record{'scantron.maxquest'}=$questnum;
                   7916:     return \%record;
                   7917: }
1.447     foxr     7918: 
1.691     raeburn  7919: sub get_master_seq {
1.788     raeburn  7920:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
1.691     raeburn  7921:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   7922:                    (ref($symb_to_resource) eq 'HASH'));
1.788     raeburn  7923:     if ($need_symb_in_map) {
                   7924:         return unless (ref($symb_for_examcode) eq 'HASH');
                   7925:     }
1.691     raeburn  7926:     my $resource_error;
                   7927:     foreach my $resource (@{$resources}) {
                   7928:         my $ressymb;
                   7929:         if (ref($resource)) {
                   7930:             $ressymb = $resource->symb();
                   7931:             push(@{$master_seq},$ressymb);
                   7932:             $symb_to_resource->{$ressymb} = $resource;
1.788     raeburn  7933:             if ($need_symb_in_map) {
                   7934:                 unless ($resource->is_map()) {
                   7935:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   7936:                     unless (exists($symb_for_examcode->{$map})) {
                   7937:                         $symb_for_examcode->{$map} = $ressymb;
                   7938:                     }
                   7939:                 }
                   7940:             }
1.691     raeburn  7941:         } else {
                   7942:             $resource_error = 1;
                   7943:             last;
                   7944:         }
                   7945:     }
                   7946:     return $resource_error;
                   7947: }
                   7948: 
                   7949: sub get_respnum_lookups {
                   7950:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   7951:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   7952:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   7953:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   7954:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   7955:                    (ref($startline) eq 'HASH'));
                   7956:     my ($user,$scancode);
                   7957:     if ((exists($record->{'scantron.CODE'})) &&
                   7958:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   7959:         $scancode = $record->{'scantron.CODE'};
                   7960:     } else {
                   7961:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   7962:     }
                   7963:     my @mapresources =
                   7964:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   7965:                      $orderedforcode);
                   7966:     my $total = 0;
                   7967:     my $count = 0;
                   7968:     foreach my $resource (@mapresources) {
                   7969:         my $id = $resource->id();
                   7970:         my $symb = $resource->symb();
                   7971:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   7972:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   7973:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   7974:                 if ($respnum ne '') {
                   7975:                     $respnumlookup->{$count} = $respnum;
                   7976:                     $startline->{$count} = $total;
                   7977:                     $total += $bubble_lines_per_response{$respnum};
                   7978:                     $count ++;
                   7979:                 }
                   7980:             }
                   7981:         }
                   7982:     }
                   7983:     return $total;
                   7984: }
                   7985: 
1.503     raeburn  7986: sub scantron_validator_lettnum {
                   7987:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  7988:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   7989:         $randompick,$respnumlookup) = @_;
1.503     raeburn  7990: 
                   7991:     # Qon 'letter' implies for each slot in currquest we have:
                   7992:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   7993:     #    about anything else (esp. a value of Qoff) for missing
                   7994:     #    bubbles.
                   7995:     #
                   7996:     # Qon 'number' implies each slot gives a digit that indexes the
                   7997:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   7998:     #    and * or ? for double bubbles on a single line.
                   7999:     #
1.447     foxr     8000: 
1.503     raeburn  8001:     my $matchon;
                   8002:     if ($$scantron_config{'Qon'} eq 'letter') {
                   8003:         $matchon = '[A-Z]';
                   8004:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   8005:         $matchon = '\d';
                   8006:     }
                   8007:     my $occurrences = 0;
1.691     raeburn  8008:     my $responsenum = $questnum-1;
                   8009:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   8010:        $responsenum = $respnumlookup->{$questnum-1} 
                   8011:     }
                   8012:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8013:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8014:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8015:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8016:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8017:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8018:         my @singlelines = split('',$currquest);
                   8019:         foreach my $entry (@singlelines) {
                   8020:             $occurrences = &occurence_count($entry,$matchon);
                   8021:             if ($occurrences > 1) {
                   8022:                 last;
                   8023:             }
1.691     raeburn  8024:         }
1.503     raeburn  8025:     } else {
                   8026:         $occurrences = &occurence_count($currquest,$matchon); 
                   8027:     }
                   8028:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   8029:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8030:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8031:             my $bubble = substr($currquest,$ans,1);
                   8032:             if ($bubble =~ /$matchon/ ) {
                   8033:                 if ($$scantron_config{'Qon'} eq 'number') {
                   8034:                     if ($bubble == 0) {
                   8035:                         $bubble = 10; 
                   8036:                     }
                   8037:                     $record->{"scantron.$ansnum.answer"} = 
                   8038:                         $alphabet->[$bubble-1];
                   8039:                 } else {
                   8040:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   8041:                 }
                   8042:             } else {
                   8043:                 $record->{"scantron.$ansnum.answer"}='';
                   8044:             }
                   8045:             $ansnum++;
                   8046:         }
                   8047:     } elsif (!defined($currquest)
                   8048:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   8049:             || (&occurence_count($currquest,$matchon) == 0)) {
                   8050:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8051:             $record->{"scantron.$ansnum.answer"}='';
                   8052:             $ansnum++;
                   8053:         }
                   8054:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8055:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   8056:         }
                   8057:     } else {
                   8058:         if ($$scantron_config{'Qon'} eq 'number') {
                   8059:             $currquest = &digits_to_letters($currquest);            
                   8060:         }
                   8061:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8062:             my $bubble = substr($currquest,$ans,1);
                   8063:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   8064:             $ansnum++;
                   8065:         }
                   8066:     }
                   8067:     return $ansnum;
                   8068: }
1.447     foxr     8069: 
1.503     raeburn  8070: sub scantron_validator_positional {
                   8071:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  8072:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   8073:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     8074: 
1.503     raeburn  8075:     # Otherwise there's a positional notation;
                   8076:     # each bubble line requires Qlength items, and there are filled in
                   8077:     # bubbles for each case where there 'Qon' characters.
                   8078:     #
1.447     foxr     8079: 
1.503     raeburn  8080:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     8081: 
1.503     raeburn  8082:     # If the split only gives us one element.. the full length of the
                   8083:     # answer string, no bubbles are filled in:
1.447     foxr     8084: 
1.507     raeburn  8085:     if ($answers_needed eq '') {
                   8086:         return;
                   8087:     }
                   8088: 
1.503     raeburn  8089:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   8090:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8091:             $record->{"scantron.$ansnum.answer"}='';
                   8092:             $ansnum++;
                   8093:         }
                   8094:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8095:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   8096:         }
                   8097:     } elsif (scalar(@array) == 2) {
                   8098:         my $location = length($array[0]);
                   8099:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   8100:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   8101:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8102:             if ($ans eq $line_num) {
                   8103:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   8104:             } else {
                   8105:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   8106:             }
                   8107:             $ansnum++;
                   8108:          }
                   8109:     } else {
                   8110:         #  If there's more than one instance of a bubble character
                   8111:         #  That's a double bubble; with positional notation we can
                   8112:         #  record all the bubbles filled in as well as the
                   8113:         #  fact this response consists of multiple bubbles.
                   8114:         #
1.691     raeburn  8115:         my $responsenum = $questnum-1;
                   8116:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   8117:             $responsenum = $respnumlookup->{$questnum-1}
                   8118:         }
                   8119:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8120:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8121:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8122:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8123:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8124:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8125:             my $doubleerror = 0;
                   8126:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   8127:                    (!$doubleerror)) {
                   8128:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   8129:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   8130:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   8131:                if (length(@currarray) > 2) {
                   8132:                    $doubleerror = 1;
                   8133:                } 
                   8134:             }
                   8135:             if ($doubleerror) {
                   8136:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8137:             }
                   8138:         } else {
                   8139:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8140:         }
                   8141:         my $item = $ansnum;
                   8142:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8143:             $record->{"scantron.$item.answer"} = '';
                   8144:             $item ++;
                   8145:         }
1.447     foxr     8146: 
1.503     raeburn  8147:         my @ans=@array;
                   8148:         my $i=0;
                   8149:         my $increment = 0;
                   8150:         while ($#ans) {
                   8151:             $i+=length($ans[0]) + $increment;
                   8152:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   8153:             my $bubble = $i%$$scantron_config{'Qlength'};
                   8154:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   8155:             shift(@ans);
                   8156:             $increment = 1;
                   8157:         }
                   8158:         $ansnum += $answers_needed;
1.82      albertel 8159:     }
1.503     raeburn  8160:     return $ansnum;
1.82      albertel 8161: }
                   8162: 
1.423     albertel 8163: =pod
                   8164: 
                   8165: =item scantron_add_delay
                   8166: 
                   8167:    Adds an error message that occurred during the grading phase to a
                   8168:    queue of messages to be shown after grading pass is complete
                   8169: 
                   8170:  Arguments:
1.424     albertel 8171:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 8172:    $scanline    - the scanline that caused the error
                   8173:    $errormesage - the error message
                   8174:    $errorcode   - a numeric code for the error
                   8175: 
                   8176:  Side Effects:
1.424     albertel 8177:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 8178: 
                   8179: =cut
                   8180: 
1.82      albertel 8181: sub scantron_add_delay {
1.140     albertel 8182:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   8183:     push(@$delayqueue,
                   8184: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   8185: 	  'ecode' => $errorcode }
                   8186: 	 );
1.82      albertel 8187: }
                   8188: 
1.423     albertel 8189: =pod
                   8190: 
                   8191: =item scantron_find_student
                   8192: 
1.424     albertel 8193:    Finds the username for the current scanline
                   8194: 
                   8195:   Arguments:
                   8196:    $scantron_record - hash result from scantron_parse_scanline
                   8197:    $scan_data       - hash of correction information 
                   8198:                       (see &scantron_getfile() form more information)
                   8199:    $idmap           - hash from &username_to_idmap()
                   8200:    $line            - number of current scanline
                   8201:  
                   8202:   Returns:
                   8203:    Either 'username:domain' or undef if unknown
                   8204: 
1.423     albertel 8205: =cut
                   8206: 
1.82      albertel 8207: sub scantron_find_student {
1.157     albertel 8208:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 8209:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 8210:     if ($scanID =~ /^\s*$/) {
                   8211:  	return &scan_data($scan_data,"$line.user");
                   8212:     }
1.83      albertel 8213:     foreach my $id (keys(%$idmap)) {
1.157     albertel 8214:  	if (lc($id) eq lc($scanID)) {
                   8215:  	    return $$idmap{$id};
                   8216:  	}
1.83      albertel 8217:     }
                   8218:     return undef;
                   8219: }
                   8220: 
1.423     albertel 8221: =pod
                   8222: 
                   8223: =item scantron_filter
                   8224: 
1.424     albertel 8225:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   8226:    hidden resources was selected
                   8227: 
1.423     albertel 8228: =cut
                   8229: 
1.83      albertel 8230: sub scantron_filter {
                   8231:     my ($curres)=@_;
1.331     albertel 8232: 
                   8233:     if (ref($curres) && $curres->is_problem()) {
                   8234: 	# if the user has asked to not have either hidden
                   8235: 	# or 'randomout' controlled resources to be graded
                   8236: 	# don't include them
                   8237: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   8238: 	    && $curres->randomout) {
                   8239: 	    return 0;
                   8240: 	}
1.83      albertel 8241: 	return 1;
                   8242:     }
                   8243:     return 0;
1.82      albertel 8244: }
                   8245: 
1.423     albertel 8246: =pod
                   8247: 
                   8248: =item scantron_process_corrections
                   8249: 
1.424     albertel 8250:    Gets correction information out of submitted form data and corrects
                   8251:    the scanline
                   8252: 
1.423     albertel 8253: =cut
                   8254: 
1.157     albertel 8255: sub scantron_process_corrections {
                   8256:     my ($r) = @_;
1.754     raeburn  8257:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8258:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8259:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 8260:     my $which=$env{'form.scantron_line'};
1.200     albertel 8261:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 8262:     my ($skip,$err,$errmsg);
1.257     albertel 8263:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 8264: 	$skip=1;
1.257     albertel 8265:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   8266: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   8267: 	    $env{'form.scantron_domain'};
1.157     albertel 8268: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   8269: 	($line,$err,$errmsg)=
                   8270: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   8271: 				     'ID',{'newid'=>$newid,
1.257     albertel 8272: 				    'username'=>$env{'form.scantron_username'},
                   8273: 				    'domain'=>$env{'form.scantron_domain'}});
                   8274:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   8275: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 8276: 	my $newCODE;
1.192     albertel 8277: 	my %args;
1.190     albertel 8278: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 8279: 	    $newCODE='use_unfound';
1.190     albertel 8280: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 8281: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 8282: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 8283: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 8284: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 8285: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 8286: 	}
1.257     albertel 8287: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 8288: 	    $args{'CODE_ignore_dup'}=1;
                   8289: 	}
                   8290: 	$args{'CODE'}=$newCODE;
1.186     albertel 8291: 	($line,$err,$errmsg)=
                   8292: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 8293: 				     'CODE',\%args);
1.257     albertel 8294:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   8295: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 8296: 	    ($line,$err,$errmsg)=
                   8297: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   8298: 					 $which,'answer',
                   8299: 					 { 'question'=>$question,
1.503     raeburn  8300: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   8301:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 8302: 	    if ($err) { last; }
                   8303: 	}
                   8304:     }
                   8305:     if ($err) {
1.703     bisitz   8306:         $r->print(
                   8307:             '<p class="LC_error">'
                   8308:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   8309:                 $errmsg)
1.704     raeburn  8310:            .'</p>');
1.157     albertel 8311:     } else {
1.200     albertel 8312: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 8313: 	&scantron_putfile($scanlines,$scan_data);
                   8314:     }
                   8315: }
                   8316: 
1.423     albertel 8317: =pod
                   8318: 
                   8319: =item reset_skipping_status
                   8320: 
1.424     albertel 8321:    Forgets the current set of remember skipped scanlines (and thus
                   8322:    reverts back to considering all lines in the
                   8323:    scantron_skipped_<filename> file)
                   8324: 
1.423     albertel 8325: =cut
                   8326: 
1.200     albertel 8327: sub reset_skipping_status {
                   8328:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8329:     &scan_data($scan_data,'remember_skipping',undef,1);
                   8330:     &scantron_putfile(undef,$scan_data);
                   8331: }
                   8332: 
1.423     albertel 8333: =pod
                   8334: 
                   8335: =item start_skipping
                   8336: 
1.424     albertel 8337:    Marks a scanline to be skipped. 
                   8338: 
1.423     albertel 8339: =cut
                   8340: 
1.376     albertel 8341: sub start_skipping {
1.200     albertel 8342:     my ($scan_data,$i)=@_;
                   8343:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8344:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   8345: 	$remembered{$i}=2;
                   8346:     } else {
                   8347: 	$remembered{$i}=1;
                   8348:     }
1.200     albertel 8349:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   8350: }
                   8351: 
1.423     albertel 8352: =pod
                   8353: 
                   8354: =item should_be_skipped
                   8355: 
1.424     albertel 8356:    Checks whether a scanline should be skipped.
                   8357: 
1.423     albertel 8358: =cut
                   8359: 
1.200     albertel 8360: sub should_be_skipped {
1.376     albertel 8361:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 8362:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 8363: 	# not redoing old skips
1.376     albertel 8364: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 8365: 	return 0;
                   8366:     }
                   8367:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8368: 
                   8369:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   8370: 	return 0;
                   8371:     }
1.200     albertel 8372:     return 1;
                   8373: }
                   8374: 
1.423     albertel 8375: =pod
                   8376: 
                   8377: =item remember_current_skipped
                   8378: 
1.424     albertel 8379:    Discovers what scanlines are in the scantron_skipped_<filename>
                   8380:    file and remembers them into scan_data for later use.
                   8381: 
1.423     albertel 8382: =cut
                   8383: 
1.200     albertel 8384: sub remember_current_skipped {
                   8385:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8386:     my %to_remember;
                   8387:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8388: 	if ($scanlines->{'skipped'}[$i]) {
                   8389: 	    $to_remember{$i}=1;
                   8390: 	}
                   8391:     }
1.376     albertel 8392: 
1.200     albertel 8393:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   8394:     &scantron_putfile(undef,$scan_data);
                   8395: }
                   8396: 
1.423     albertel 8397: =pod
                   8398: 
                   8399: =item check_for_error
                   8400: 
1.424     albertel 8401:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  8402:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 8403:     something went wrong.
                   8404: 
1.423     albertel 8405: =cut
                   8406: 
1.200     albertel 8407: sub check_for_error {
                   8408:     my ($r,$result)=@_;
                   8409:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 8410: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 8411:     }
                   8412: }
1.157     albertel 8413: 
1.423     albertel 8414: =pod
                   8415: 
                   8416: =item scantron_warning_screen
                   8417: 
1.424     albertel 8418:    Interstitial screen to make sure the operator has selected the
                   8419:    correct options before we start the validation phase.
                   8420: 
1.423     albertel 8421: =cut
                   8422: 
1.203     albertel 8423: sub scantron_warning_screen {
1.650     raeburn  8424:     my ($button_text,$symb)=@_;
1.257     albertel 8425:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  8426:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 8427:     my $CODElist;
1.284     albertel 8428:     if ($scantron_config{'CODElocation'} &&
                   8429: 	$scantron_config{'CODEstart'} &&
                   8430: 	$scantron_config{'CODElength'}) {
                   8431: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   8432: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 8433: 	$CODElist=
1.492     albertel 8434: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 8435: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 8436:     }
1.663     raeburn  8437:     my $lastbubblepoints;
                   8438:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8439:         $lastbubblepoints =
                   8440:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   8441:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   8442:     }
1.770     raeburn  8443:     return '
1.203     albertel 8444: <p>
1.492     albertel 8445: <span class="LC_warning">
1.705     raeburn  8446: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 8447: </p>
                   8448: <table>
1.492     albertel 8449: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   8450: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  8451: '.$CODElist.$lastbubblepoints.'
1.203     albertel 8452: </table>
1.680     raeburn  8453: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  8454: '.&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  8455: ';
1.203     albertel 8456: }
                   8457: 
1.423     albertel 8458: =pod
                   8459: 
                   8460: =item scantron_do_warning
                   8461: 
1.424     albertel 8462:    Check if the operator has picked something for all required
                   8463:    fields. Error out if something is missing.
                   8464: 
1.423     albertel 8465: =cut
                   8466: 
1.203     albertel 8467: sub scantron_do_warning {
1.608     www      8468:     my ($r,$symb)=@_;
1.203     albertel 8469:     if (!$symb) {return '';}
1.324     albertel 8470:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 8471:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 8472:     if ( $env{'form.selectpage'} eq '' ||
                   8473: 	 $env{'form.scantron_selectfile'} eq '' ||
                   8474: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  8475: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 8476: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 8477: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 8478: 	} 
1.257     albertel 8479: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  8480: 	    $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  8481: 	}
1.257     albertel 8482: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  8483: 	    $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  8484: 	}
1.237     albertel 8485:     } else {
1.650     raeburn  8486: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  8487:         my ($checksec,@possibles) = &gradable_sections();
                   8488:         my $gradesections;
                   8489:         if ($checksec) {
                   8490:             my $file=$env{'form.scantron_selectfile'};
                   8491:             if (&valid_file($file)) {
                   8492:                 my %bysec = &scantron_get_sections();
                   8493:                 my $table;
                   8494:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   8495:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   8496:                     $table = &Apache::loncommon::start_data_table()."\n".
                   8497:                              &Apache::loncommon::start_data_table_header_row().
                   8498:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   8499:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   8500:                     if ($bysec{'none'}) {
                   8501:                         $table .= &Apache::loncommon::start_data_table_row().
                   8502:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   8503:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8504:                     }
                   8505:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   8506:                         next if ($sec eq 'none');
                   8507:                         $table .= &Apache::loncommon::start_data_table_row().
                   8508:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   8509:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8510:                     }
                   8511:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   8512:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   8513:                                       '<p>'.$table.'</p>';
                   8514:                     if (@possibles) {
                   8515:                         $gradesections .= '<p>'.
                   8516:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   8517:                                               scalar(@possibles)).'<br />'.
                   8518:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   8519:                                               '<i>'.$checksec.'</i>').' ';
                   8520:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   8521:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   8522:                         }
                   8523:                         $gradesections .= '</p>';
                   8524:                     }
                   8525:                 }
                   8526:             } else {
                   8527:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   8528:             }
                   8529:         }
1.663     raeburn  8530:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 8531: 	$r->print('
1.770     raeburn  8532: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 8533: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 8534: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 8535: ');
1.237     albertel 8536:     }
1.614     www      8537:     $r->print("</form><br />");
1.203     albertel 8538:     return '';
                   8539: }
                   8540: 
1.423     albertel 8541: =pod
                   8542: 
                   8543: =item scantron_form_start
                   8544: 
1.424     albertel 8545:     html hidden input for remembering all selected grading options
                   8546: 
1.423     albertel 8547: =cut
                   8548: 
1.203     albertel 8549: sub scantron_form_start {
                   8550:     my ($max_bubble)=@_;
                   8551:     my $result= <<SCANTRONFORM;
                   8552: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 8553:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   8554:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   8555:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 8556:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 8557:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   8558:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   8559:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   8560:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 8561:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 8562: SCANTRONFORM
1.447     foxr     8563: 
                   8564:   my $line = 0;
                   8565:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   8566:        my $chunk =
                   8567: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     8568:        $chunk .=
                   8569: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  8570:        $chunk .= 
                   8571:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  8572:        $chunk .=
                   8573:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  8574:        $chunk .=
                   8575:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     8576:        $result .= $chunk;
                   8577:        $line++;
1.691     raeburn  8578:     }
1.203     albertel 8579:     return $result;
                   8580: }
                   8581: 
1.423     albertel 8582: =pod
                   8583: 
                   8584: =item scantron_validate_file
                   8585: 
1.659     raeburn  8586:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 8587: 
                   8588:     Also processes any necessary information resets that need to
                   8589:     occur before validation begins (ignore previous corrections,
                   8590:     restarting the skipped records processing)
                   8591: 
1.423     albertel 8592: =cut
                   8593: 
1.157     albertel 8594: sub scantron_validate_file {
1.608     www      8595:     my ($r,$symb) = @_;
1.157     albertel 8596:     if (!$symb) {return '';}
1.324     albertel 8597:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 8598:     
1.703     bisitz   8599:     # do the detection of only doing skipped records first before we delete
1.424     albertel 8600:     # them when doing the corrections reset
1.257     albertel 8601:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 8602: 	&reset_skipping_status();
                   8603:     }
1.257     albertel 8604:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 8605: 	&remember_current_skipped();
1.257     albertel 8606: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 8607:     }
                   8608: 
1.257     albertel 8609:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 8610: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   8611: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   8612: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 8613: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 8614:     }
1.200     albertel 8615: 
1.257     albertel 8616:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 8617: 	&scantron_process_corrections($r);
                   8618:     }
1.770     raeburn  8619: 
                   8620:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   8621:     my ($checksec,@gradable);
                   8622:     if ($env{'request.course.sec'}) {
                   8623:         ($checksec,my @possibles) = &gradable_sections();
                   8624:         if ($checksec) {
                   8625:             if (@possibles) {
                   8626:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   8627:                 if (@chosensecs) {
                   8628:                     foreach my $sec (@chosensecs) {
                   8629:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   8630:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   8631:                                 push(@gradable,$sec);
                   8632:                             }
                   8633:                         }
                   8634:                     }
                   8635:                 }
                   8636:             }
                   8637:             $r->print('<p><table>');
                   8638:             if (@gradable) {
                   8639:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   8640:                 $r->print(
                   8641:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   8642:             } else {
                   8643:                 $r->print(
                   8644:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   8645:             }
                   8646:             $r->print('</table></p>');
                   8647:         }
                   8648:     }
                   8649:     $r->rflush();
                   8650: 
1.157     albertel 8651:     #get the student pick code ready
                   8652:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  8653:     my $nav_error;
1.754     raeburn  8654:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8655:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8656:     if ($nav_error) {
                   8657:         $r->print(&navmap_errormsg());
                   8658:         return '';
                   8659:     }
1.203     albertel 8660:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  8661:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8662:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   8663:     }
1.157     albertel 8664:     $r->print($result);
                   8665:     
1.334     albertel 8666:     my @validate_phases=( 'sequence',
                   8667: 			  'ID',
1.157     albertel 8668: 			  'CODE',
                   8669: 			  'doublebubble',
                   8670: 			  'missingbubbles');
1.257     albertel 8671:     if (!$env{'form.validatepass'}) {
                   8672: 	$env{'form.validatepass'} = 0;
1.157     albertel 8673:     }
1.257     albertel 8674:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  8675:     my %skipbysec=();
1.448     foxr     8676: 
1.157     albertel 8677:     my $stop=0;
                   8678:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  8679: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 8680: 	$r->rflush();
1.691     raeburn  8681:      
1.157     albertel 8682: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   8683: 	{
                   8684: 	    no strict 'refs';
1.770     raeburn  8685:             my @extras=();
                   8686:             if ($validate_phases[$currentphase] eq 'ID') {
                   8687:                 @extras = (\%skipbysec,$checksec,@gradable);
                   8688:             }
                   8689: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 8690: 	}
                   8691:     }
                   8692:     if (!$stop) {
1.650     raeburn  8693: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  8694:         my $secinfo;
                   8695:         if (keys(%skipbysec) > 0) {
                   8696:             my $seclist = '<ul>';
                   8697:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   8698:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   8699:             }
                   8700:             $seclist .= '</ul>';
                   8701:             $secinfo = '<p class="LC_info">'.
                   8702:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   8703:                            $seclist).
                   8704:                        '</p>';
                   8705:         }
1.542     raeburn  8706: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  8707:                   $secinfo.$warning.
1.542     raeburn  8708:                   &mt('Perform verification for each student after storage of submissions?').
                   8709:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   8710:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   8711:                   ('&nbsp;'x3).'<label>'.
                   8712:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   8713:                   '</label></span><br />'.
                   8714:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  8715:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  8716:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   8717:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 8718:     } else {
                   8719: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   8720: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   8721:     }
                   8722:     if ($stop) {
1.334     albertel 8723: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  8724: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 8725: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 8726: 
1.650     raeburn  8727: 	    $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 8728: 	} else {
1.503     raeburn  8729:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  8730: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  8731:             } else {
1.539     riegler  8732:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  8733:             }
1.492     albertel 8734: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   8735: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   8736: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 8737: 	}
1.157     albertel 8738:     }
1.614     www      8739:     $r->print(" </form><br />");
1.157     albertel 8740:     return '';
                   8741: }
                   8742: 
1.423     albertel 8743: 
                   8744: =pod
                   8745: 
                   8746: =item scantron_remove_file
                   8747: 
1.659     raeburn  8748:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 8749:    scantron_original_<filename> is never removed
                   8750: 
                   8751: 
1.423     albertel 8752: =cut
                   8753: 
1.200     albertel 8754: sub scantron_remove_file {
1.192     albertel 8755:     my ($which)=@_;
1.257     albertel 8756:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8757:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8758:     my $file='scantron_';
1.200     albertel 8759:     if ($which eq 'corrected' || $which eq 'skipped') {
                   8760: 	$file.=$which.'_';
1.192     albertel 8761:     } else {
                   8762: 	return 'refused';
                   8763:     }
1.257     albertel 8764:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 8765:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   8766: }
                   8767: 
1.423     albertel 8768: 
                   8769: =pod
                   8770: 
                   8771: =item scantron_remove_scan_data
                   8772: 
1.659     raeburn  8773:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 8774:    data file.  (In the case that both the are doing skipped records we need
                   8775:    to remember the old skipped lines for the time being so that element
                   8776:    persists for a while.)
                   8777: 
1.423     albertel 8778: =cut
                   8779: 
1.200     albertel 8780: sub scantron_remove_scan_data {
1.257     albertel 8781:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8782:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8783:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   8784:     my @todelete;
1.257     albertel 8785:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 8786:     foreach my $key (@keys) {
                   8787: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 8788: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 8789: 		$key=~/remember_skipping/) {
                   8790: 		next;
                   8791: 	    }
1.192     albertel 8792: 	    push(@todelete,$key);
                   8793: 	}
                   8794:     }
1.200     albertel 8795:     my $result;
1.192     albertel 8796:     if (@todelete) {
1.491     albertel 8797: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   8798: 				       \@todelete,$cdom,$cname);
                   8799:     } else {
                   8800: 	$result = 'ok';
1.192     albertel 8801:     }
                   8802:     return $result;
                   8803: }
                   8804: 
1.423     albertel 8805: 
                   8806: =pod
                   8807: 
                   8808: =item scantron_getfile
                   8809: 
1.659     raeburn  8810:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 8811:     the scan_data hash
                   8812:   
                   8813:   Arguments:
                   8814:     None
                   8815: 
                   8816:   Returns:
                   8817:     2 hash references
                   8818: 
                   8819:      - first one has 
                   8820:          orig      -
                   8821:          corrected -
                   8822:          skipped   -  each of which points to an array ref of the specified
                   8823:                       file broken up into individual lines
                   8824:          count     - number of scanlines
                   8825:  
                   8826:      - second is the scan_data hash possible keys are
1.425     albertel 8827:        ($number refers to scanline numbered $number and thus the key affects
                   8828:         only that scanline
                   8829:         $bubline refers to the specific bubble line element and the aspects
                   8830:         refers to that specific bubble line element)
                   8831: 
                   8832:        $number.user - username:domain to use
                   8833:        $number.CODE_ignore_dup 
                   8834:                     - ignore the duplicate CODE error 
                   8835:        $number.useCODE
                   8836:                     - use the CODE in the scanline as is
                   8837:        $number.no_bubble.$bubline
                   8838:                     - it is valid that there is no bubbled in bubble
                   8839:                       at $number $bubline
                   8840:        remember_skipping
                   8841:                     - a frozen hash containing keys of $number and values
                   8842:                       of either 
                   8843:                         1 - we are on a 'do skipped records pass' and plan
                   8844:                             on processing this line
                   8845:                         2 - we are on a 'do skipped records pass' and this
                   8846:                             scanline has been marked to skip yet again
1.424     albertel 8847: 
1.423     albertel 8848: =cut
                   8849: 
1.157     albertel 8850: sub scantron_getfile {
1.200     albertel 8851:     #FIXME really would prefer a scantron directory
1.257     albertel 8852:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8853:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 8854:     my $lines;
                   8855:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8856: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 8857:     my %scanlines;
                   8858:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   8859:     my $temp=$scanlines{'orig'};
                   8860:     $scanlines{'count'}=$#$temp;
                   8861: 
                   8862:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8863: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 8864:     if ($lines eq '-1') {
                   8865: 	$scanlines{'corrected'}=[];
                   8866:     } else {
                   8867: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   8868:     }
                   8869:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8870: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 8871:     if ($lines eq '-1') {
                   8872: 	$scanlines{'skipped'}=[];
                   8873:     } else {
                   8874: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   8875:     }
1.175     albertel 8876:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 8877:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   8878:     my %scan_data = @tmp;
                   8879:     return (\%scanlines,\%scan_data);
                   8880: }
                   8881: 
1.423     albertel 8882: =pod
                   8883: 
                   8884: =item lonnet_putfile
                   8885: 
1.424     albertel 8886:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   8887: 
                   8888:  Arguments:
                   8889:    $contents - data to store
                   8890:    $filename - filename to store $contents into
                   8891: 
                   8892:  Returns:
                   8893:    result value from &Apache::lonnet::finishuserfileupload
                   8894: 
1.423     albertel 8895: =cut
                   8896: 
1.157     albertel 8897: sub lonnet_putfile {
                   8898:     my ($contents,$filename)=@_;
1.257     albertel 8899:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8900:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8901:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 8902:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 8903: 
                   8904: }
                   8905: 
1.423     albertel 8906: =pod
                   8907: 
                   8908: =item scantron_putfile
                   8909: 
1.659     raeburn  8910:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 8911:     scan_data hash. (Does not modify the original version only the
                   8912:     corrected and skipped versions.
                   8913: 
                   8914:  Arguments:
                   8915:     $scanlines - hash ref that looks like the first return value from
                   8916:                  &scantron_getfile()
                   8917:     $scan_data - hash ref that looks like the second return value from
                   8918:                  &scantron_getfile()
                   8919: 
1.423     albertel 8920: =cut
                   8921: 
1.157     albertel 8922: sub scantron_putfile {
                   8923:     my ($scanlines,$scan_data) = @_;
1.200     albertel 8924:     #FIXME really would prefer a scantron directory
1.257     albertel 8925:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8926:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 8927:     if ($scanlines) {
                   8928: 	my $prefix='scantron_';
1.157     albertel 8929: # no need to update orig, shouldn't change
                   8930: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 8931: #		    $env{'form.scantron_selectfile'});
1.200     albertel 8932: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   8933: 			$prefix.'corrected_'.
1.257     albertel 8934: 			$env{'form.scantron_selectfile'});
1.200     albertel 8935: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   8936: 			$prefix.'skipped_'.
1.257     albertel 8937: 			$env{'form.scantron_selectfile'});
1.200     albertel 8938:     }
1.175     albertel 8939:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 8940: }
                   8941: 
1.423     albertel 8942: =pod
                   8943: 
                   8944: =item scantron_get_line
                   8945: 
1.424     albertel 8946:    Returns the correct version of the scanline
                   8947: 
                   8948:  Arguments:
                   8949:     $scanlines - hash ref that looks like the first return value from
                   8950:                  &scantron_getfile()
                   8951:     $scan_data - hash ref that looks like the second return value from
                   8952:                  &scantron_getfile()
                   8953:     $i         - number of the requested line (starts at 0)
                   8954: 
                   8955:  Returns:
                   8956:    A scanline, (either the original or the corrected one if it
                   8957:    exists), or undef if the requested scanline should be
                   8958:    skipped. (Either because it's an skipped scanline, or it's an
                   8959:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   8960:    pass.
                   8961: 
1.423     albertel 8962: =cut
                   8963: 
1.157     albertel 8964: sub scantron_get_line {
1.200     albertel 8965:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 8966:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   8967:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 8968:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   8969:     return $scanlines->{'orig'}[$i]; 
                   8970: }
                   8971: 
1.423     albertel 8972: =pod
                   8973: 
                   8974: =item scantron_todo_count
                   8975: 
1.424     albertel 8976:     Counts the number of scanlines that need processing.
                   8977: 
                   8978:  Arguments:
                   8979:     $scanlines - hash ref that looks like the first return value from
                   8980:                  &scantron_getfile()
                   8981:     $scan_data - hash ref that looks like the second return value from
                   8982:                  &scantron_getfile()
                   8983: 
                   8984:  Returns:
                   8985:     $count - number of scanlines to process
                   8986: 
1.423     albertel 8987: =cut
                   8988: 
1.200     albertel 8989: sub get_todo_count {
                   8990:     my ($scanlines,$scan_data)=@_;
                   8991:     my $count=0;
                   8992:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8993: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   8994: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8995: 	$count++;
                   8996:     }
                   8997:     return $count;
                   8998: }
                   8999: 
1.423     albertel 9000: =pod
                   9001: 
                   9002: =item scantron_put_line
                   9003: 
1.659     raeburn  9004:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 9005:     data file.
                   9006: 
                   9007:  Arguments:
                   9008:     $scanlines - hash ref that looks like the first return value from
                   9009:                  &scantron_getfile()
                   9010:     $scan_data - hash ref that looks like the second return value from
                   9011:                  &scantron_getfile()
                   9012:     $i         - line number to update
                   9013:     $newline   - contents of the updated scanline
                   9014:     $skip      - if true make the line for skipping and update the
                   9015:                  'skipped' file
                   9016: 
1.423     albertel 9017: =cut
                   9018: 
1.157     albertel 9019: sub scantron_put_line {
1.200     albertel 9020:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 9021:     if ($skip) {
                   9022: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 9023: 	&start_skipping($scan_data,$i);
1.157     albertel 9024: 	return;
                   9025:     }
                   9026:     $scanlines->{'corrected'}[$i]=$newline;
                   9027: }
                   9028: 
1.423     albertel 9029: =pod
                   9030: 
                   9031: =item scantron_clear_skip
                   9032: 
1.424     albertel 9033:    Remove a line from the 'skipped' file
                   9034: 
                   9035:  Arguments:
                   9036:     $scanlines - hash ref that looks like the first return value from
                   9037:                  &scantron_getfile()
                   9038:     $scan_data - hash ref that looks like the second return value from
                   9039:                  &scantron_getfile()
                   9040:     $i         - line number to update
                   9041: 
1.423     albertel 9042: =cut
                   9043: 
1.376     albertel 9044: sub scantron_clear_skip {
                   9045:     my ($scanlines,$scan_data,$i)=@_;
                   9046:     if (exists($scanlines->{'skipped'}[$i])) {
                   9047: 	undef($scanlines->{'skipped'}[$i]);
                   9048: 	return 1;
                   9049:     }
                   9050:     return 0;
                   9051: }
                   9052: 
1.423     albertel 9053: =pod
                   9054: 
                   9055: =item scantron_filter_not_exam
                   9056: 
1.424     albertel 9057:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   9058:    filter out resources that are not marked as 'exam' mode
                   9059: 
1.423     albertel 9060: =cut
                   9061: 
1.334     albertel 9062: sub scantron_filter_not_exam {
                   9063:     my ($curres)=@_;
                   9064:     
                   9065:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   9066: 	# if the user has asked to not have either hidden
                   9067: 	# or 'randomout' controlled resources to be graded
                   9068: 	# don't include them
                   9069: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   9070: 	    && $curres->randomout) {
                   9071: 	    return 0;
                   9072: 	}
                   9073: 	return 1;
                   9074:     }
                   9075:     return 0;
                   9076: }
                   9077: 
1.423     albertel 9078: =pod
                   9079: 
                   9080: =item scantron_validate_sequence
                   9081: 
1.424     albertel 9082:     Validates the selected sequence, checking for resource that are
                   9083:     not set to exam mode.
                   9084: 
1.423     albertel 9085: =cut
                   9086: 
1.334     albertel 9087: sub scantron_validate_sequence {
                   9088:     my ($r,$currentphase) = @_;
                   9089: 
                   9090:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9091:     unless (ref($navmap)) {
                   9092:         $r->print(&navmap_errormsg());
                   9093:         return (1,$currentphase);
                   9094:     }
1.334     albertel 9095:     my (undef,undef,$sequence)=
                   9096: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9097: 
                   9098:     my $map=$navmap->getResourceByUrl($sequence);
                   9099: 
                   9100:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   9101:                                     value="ignore" />');
                   9102:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   9103: 	my @resources=
                   9104: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   9105: 	if (@resources) {
1.675     bisitz   9106: 	    $r->print(
                   9107:                 '<p class="LC_warning">'
                   9108:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   9109:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   9110:                    .' work correctly.')
                   9111:                .'</p>'
                   9112:             );
1.334     albertel 9113: 	    return (1,$currentphase);
                   9114: 	}
                   9115:     }
                   9116: 
                   9117:     return (0,$currentphase+1);
                   9118: }
                   9119: 
1.423     albertel 9120: 
                   9121: 
1.157     albertel 9122: sub scantron_validate_ID {
1.770     raeburn  9123:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 9124:     
                   9125:     #get student info
                   9126:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9127:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  9128:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 9129: 
                   9130:     #get scantron line setup
1.754     raeburn  9131:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9132:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  9133: 
                   9134:     my $nav_error;
1.649     raeburn  9135:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  9136:     if ($nav_error) {
                   9137:         $r->print(&navmap_errormsg());
                   9138:         return(1,$currentphase);
                   9139:     }
1.157     albertel 9140: 
                   9141:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  9142:     my $unsavedskips = 0;
1.157     albertel 9143:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9144: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9145: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9146: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9147: 						 $scan_data);
                   9148: 	my $id=$$scan_record{'scantron.ID'};
                   9149: 	my $found;
                   9150: 	foreach my $checkid (keys(%idmap)) {
                   9151: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   9152: 	}
                   9153: 	if ($found) {
                   9154: 	    my $username=$idmap{$found};
1.770     raeburn  9155:             if ($checksec) {
                   9156:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   9157:                     my $stusec = $classlist->{$username}->[$secidx];
                   9158:                     if ($stusec ne $checksec) {
                   9159:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9160:                             my $skip=1;
                   9161:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9162:                             if (ref($skipbysec) eq 'HASH') {
                   9163:                                 if ($stusec eq '') {
                   9164:                                     $skipbysec->{'none'} ++;
                   9165:                                 } else {
                   9166:                                     $skipbysec->{$stusec} ++;
                   9167:                                 }
                   9168:                             }
                   9169:                             $unsavedskips ++;
                   9170:                             next;
                   9171:                         }
                   9172:                     }
                   9173:                 }
                   9174:             }
1.157     albertel 9175: 	    if ($found{'ids'}{$found}) {
                   9176: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9177: 					 $line,'duplicateID',$found);
1.770     raeburn  9178:                 if ($unsavedskips) {
                   9179:                     &scantron_putfile($scanlines,$scan_data);
                   9180:                     $unsavedskips = 0;
                   9181:                 }
1.194     albertel 9182: 		return(1,$currentphase);
1.157     albertel 9183: 	    } elsif ($found{'usernames'}{$username}) {
                   9184: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9185: 					 $line,'duplicateID',$username);
1.770     raeburn  9186:                 if ($unsavedskips) {
                   9187:                     &scantron_putfile($scanlines,$scan_data);
                   9188:                     $unsavedskips = 0;
                   9189:                 }
1.194     albertel 9190: 		return(1,$currentphase);
1.157     albertel 9191: 	    }
1.186     albertel 9192: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 9193: 	    $found{'ids'}{$found}++;
                   9194: 	    $found{'usernames'}{$username}++;
                   9195: 	} else {
                   9196: 	    if ($id =~ /^\s*$/) {
1.158     albertel 9197: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  9198:                 if (($checksec && $username ne '')) {
                   9199:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   9200:                         my $stusec = $classlist->{$username}->[$secidx];
                   9201:                         if ($stusec ne $checksec) {
                   9202:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9203:                                 my $skip=1;
                   9204:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9205:                                 if (ref($skipbysec) eq 'HASH') {
                   9206:                                     if ($stusec eq '') {
                   9207:                                         $skipbysec->{'none'} ++;
                   9208:                                     } else {
                   9209:                                         $skipbysec->{$stusec} ++;
                   9210:                                     }
                   9211:                                 }
                   9212:                                 $unsavedskips ++;
                   9213:                                 next;
                   9214:                             }
                   9215:                         }
                   9216:                     }
                   9217: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 9218: 		    &scantron_get_correction($r,$i,$scan_record,
                   9219: 					     \%scantron_config,
                   9220: 					     $line,'duplicateID',$username);
1.770     raeburn  9221:                     if ($unsavedskips) {
                   9222:                         &scantron_putfile($scanlines,$scan_data);
                   9223:                         $unsavedskips = 0;
                   9224:                     }
1.194     albertel 9225: 		    return(1,$currentphase);
1.157     albertel 9226: 		} elsif (!defined($username)) {
                   9227: 		    &scantron_get_correction($r,$i,$scan_record,
                   9228: 					     \%scantron_config,
                   9229: 					     $line,'incorrectID');
1.770     raeburn  9230:                     if ($unsavedskips) {
                   9231:                         &scantron_putfile($scanlines,$scan_data);
                   9232:                         $unsavedskips = 0;
                   9233:                     }
1.194     albertel 9234: 		    return(1,$currentphase);
1.157     albertel 9235: 		}
                   9236: 		$found{'usernames'}{$username}++;
                   9237: 	    } else {
                   9238: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9239: 					 $line,'incorrectID');
1.770     raeburn  9240:                 if ($unsavedskips) {
                   9241:                     &scantron_putfile($scanlines,$scan_data);
                   9242:                     $unsavedskips = 0;
                   9243:                 }
1.194     albertel 9244: 		return(1,$currentphase);
1.157     albertel 9245: 	    }
                   9246: 	}
                   9247:     }
1.770     raeburn  9248:     if ($unsavedskips) {
                   9249:         &scantron_putfile($scanlines,$scan_data);
                   9250:         $unsavedskips = 0;
                   9251:     }
1.157     albertel 9252:     return (0,$currentphase+1);
                   9253: }
                   9254: 
1.770     raeburn  9255: sub scantron_get_sections {
                   9256:     my %bysec;
                   9257:     if ($env{'form.scantron_format'} ne '') {
                   9258:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   9259:         my ($scanlines,$scan_data)=&scantron_getfile();
                   9260:         my $classlist=&Apache::loncoursedata::get_classlist();
                   9261:         my %idmap=&username_to_idmap($classlist);
                   9262:         foreach my $key (keys(%idmap)) {
                   9263:             my $lckey = lc($key);
                   9264:             $idmap{$lckey} = $idmap{$key};
                   9265:         }
                   9266:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   9267:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   9268:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   9269:             if ($line=~/^[\s\cz]*$/) { next; }
                   9270:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9271:                                                      $scan_data);
                   9272:             my $id=lc($$scan_record{'scantron.ID'});
                   9273:             if (exists($idmap{$id})) {
                   9274:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9275:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9276:                     if ($stusec eq '') {
                   9277:                         $bysec{'none'} ++;
                   9278:                     } else {
                   9279:                         $bysec{$stusec} ++;
                   9280:                     }
                   9281:                 }
                   9282:             }
                   9283:         }
                   9284:     }
                   9285:     return %bysec;
                   9286: }
1.423     albertel 9287: 
1.157     albertel 9288: sub scantron_get_correction {
1.691     raeburn  9289:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   9290:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 9291: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 9292: #to show both the current line and the previous one and allow skipping
                   9293: #the previous one or the current one
                   9294: 
1.333     albertel 9295:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   9296:         $r->print(
                   9297:             '<p class="LC_warning">'
                   9298:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   9299:                 "<b>$error</b>",
                   9300:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   9301:            ."</p> \n");
1.157     albertel 9302:     } else {
1.658     bisitz   9303:         $r->print(
                   9304:             '<p class="LC_warning">'
                   9305:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   9306:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   9307:            ."</p> \n");
                   9308:     }
                   9309:     my $message =
                   9310:         '<p>'
                   9311:        .&mt('The ID on the form is [_1]',
                   9312:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   9313:        .'<br />'
1.665     raeburn  9314:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   9315:             $$scan_record{'scantron.LastName'},
                   9316:             $$scan_record{'scantron.FirstName'})
                   9317:        .'</p>';
1.242     albertel 9318: 
1.157     albertel 9319:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   9320:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  9321:                            # Array populated for doublebubble or
                   9322:     my @lines_to_correct;  # missingbubble errors to build javascript
                   9323:                            # to validate radio button checking   
                   9324: 
1.157     albertel 9325:     if ($error =~ /ID$/) {
1.186     albertel 9326: 	if ($error eq 'incorrectID') {
1.658     bisitz   9327:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 9328: 		      "</p>\n");
1.157     albertel 9329: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   9330:             $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 9331: 	}
1.242     albertel 9332: 	$r->print($message);
1.492     albertel 9333: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 9334: 	$r->print("\n<ul><li> ");
                   9335: 	#FIXME it would be nice if this sent back the user ID and
                   9336: 	#could do partial userID matches
                   9337: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   9338: 				       'scantron_username','scantron_domain'));
                   9339: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   9340: 	$r->print("\n:\n".
1.257     albertel 9341: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 9342: 
                   9343: 	$r->print('</li>');
1.186     albertel 9344:     } elsif ($error =~ /CODE$/) {
                   9345: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   9346: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 9347: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   9348: 	    $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 9349: 	}
1.658     bisitz   9350: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   9351: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   9352:                  ."</p>\n");
1.242     albertel 9353: 	$r->print($message);
1.658     bisitz   9354: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 9355: 	$r->print("\n<br /> ");
1.194     albertel 9356: 	my $i=0;
1.273     albertel 9357: 	if ($error eq 'incorrectCODE' 
                   9358: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 9359: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 9360: 	    if ($closest > 0) {
                   9361: 		foreach my $testcode (@{$closest}) {
                   9362: 		    my $checked='';
1.569     bisitz   9363: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9364: 		    $r->print("
                   9365:    <label>
1.569     bisitz   9366:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 9367:        ".&mt("Use the similar CODE [_1] instead.",
                   9368: 	    "<b><tt>".$testcode."</tt></b>")."
                   9369:     </label>
                   9370:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 9371: 		    $r->print("\n<br />");
                   9372: 		    $i++;
                   9373: 		}
1.194     albertel 9374: 	    }
                   9375: 	}
1.273     albertel 9376: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   9377: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9378: 	    $r->print("
                   9379:     <label>
1.569     bisitz   9380:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  9381:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 9382: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   9383:     </label>");
1.273     albertel 9384: 	    $r->print("\n<br />");
                   9385: 	}
1.194     albertel 9386: 
1.597     wenzelju 9387: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 9388: function change_radio(field) {
1.190     albertel 9389:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 9390:     var i;
                   9391:     for (i=0;i<slct.length;i++) {
                   9392:         if (slct[i].value==field) { slct[i].checked=true; }
                   9393:     }
                   9394: }
                   9395: ENDSCRIPT
1.187     albertel 9396: 	my $href="/adm/pickcode?".
1.359     www      9397: 	   "form=".&escape("scantronupload").
                   9398: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   9399: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   9400: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   9401: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 9402: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 9403: 	    $r->print("
                   9404:     <label>
                   9405:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   9406:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   9407: 	     "<a target='_blank' href='$href'>","</a>")."
                   9408:     </label> 
1.558     bisitz   9409:     ".&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 9410: 	    $r->print("\n<br />");
                   9411: 	}
1.492     albertel 9412: 	$r->print("
                   9413:     <label>
                   9414:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   9415:        ".&mt("Use [_1] as the CODE.",
                   9416: 	     "</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 9417: 	$r->print("\n<br /><br />");
1.157     albertel 9418:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   9419: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     9420: 
                   9421: 	# The form field scantron_questions is acutally a list of line numbers.
                   9422: 	# represented by this form so:
                   9423: 
1.691     raeburn  9424: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9425:                                                 $respnumlookup,$startline);
1.497     foxr     9426: 
1.157     albertel 9427: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9428: 		  $line_list.'" />');
1.242     albertel 9429: 	$r->print($message);
1.492     albertel 9430: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 9431: 	foreach my $question (@{$arg}) {
1.503     raeburn  9432: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9433:                                                    $scan_record, $error,
                   9434:                                                    $randomorder,$randompick,
                   9435:                                                    $respnumlookup,$startline);
1.524     raeburn  9436:             push(@lines_to_correct,@linenums);
1.157     albertel 9437: 	}
1.503     raeburn  9438:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9439:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   9440: 	$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 9441: 	$r->print($message);
1.492     albertel 9442: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  9443: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     9444: 
1.503     raeburn  9445: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     9446: 	# a list of question numbers. Therefore:
                   9447: 	#
1.691     raeburn  9448: 
                   9449: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9450:                                                 $respnumlookup,$startline);
1.497     foxr     9451: 
1.157     albertel 9452: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9453: 		  $line_list.'" />');
1.157     albertel 9454: 	foreach my $question (@{$arg}) {
1.503     raeburn  9455: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9456:                                                    $scan_record, $error,
                   9457:                                                    $randomorder,$randompick,
                   9458:                                                    $respnumlookup,$startline);
1.524     raeburn  9459:             push(@lines_to_correct,@linenums);
1.157     albertel 9460: 	}
1.503     raeburn  9461:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9462:     } else {
                   9463: 	$r->print("\n<ul>");
                   9464:     }
                   9465:     $r->print("\n</li></ul>");
1.497     foxr     9466: }
                   9467: 
1.503     raeburn  9468: sub verify_bubbles_checked {
                   9469:     my (@ansnums) = @_;
                   9470:     my $ansnumstr = join('","',@ansnums);
                   9471:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  9472:     &js_escape(\$warning);
1.767     raeburn  9473:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  9474: function verify_bubble_radio(form) {
                   9475:     var ansnumArray = new Array ("$ansnumstr");
                   9476:     var need_bubble_count = 0;
                   9477:     for (var i=0; i<ansnumArray.length; i++) {
                   9478:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   9479:             var bubble_picked = 0; 
                   9480:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   9481:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   9482:                     bubble_picked = 1;
                   9483:                 }
                   9484:             }
                   9485:             if (bubble_picked == 0) {
                   9486:                 need_bubble_count ++;
                   9487:             }
                   9488:         }
                   9489:     }
                   9490:     if (need_bubble_count) {
                   9491:         alert("$warning");
                   9492:         return;
                   9493:     }
                   9494:     form.submit(); 
                   9495: }
                   9496: ENDSCRIPT
                   9497:     return $output;
                   9498: }
                   9499: 
1.497     foxr     9500: =pod
                   9501: 
                   9502: =item  questions_to_line_list
1.157     albertel 9503: 
1.497     foxr     9504: Converts a list of questions into a string of comma separated
                   9505: line numbers in the answer sheet used by the questions.  This is
                   9506: used to fill in the scantron_questions form field.
                   9507: 
                   9508:   Arguments:
                   9509:      questions    - Reference to an array of questions.
1.691     raeburn  9510:      randomorder  - True if randomorder in use.
                   9511:      randompick   - True if randompick in use.
                   9512:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9513:                      for current line to question number used for same question
                   9514:                      in "Master Seqence" (as seen by Course Coordinator).
                   9515:      startline    - Reference to hash where key is question number (0 is first)
                   9516:                     and key is number of first bubble line for current student
                   9517:                     or code-based randompick and/or randomorder.
1.693     raeburn  9518: 
1.497     foxr     9519: =cut
                   9520: 
                   9521: 
                   9522: sub questions_to_line_list {
1.691     raeburn  9523:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     9524:     my @lines;
                   9525: 
1.503     raeburn  9526:     foreach my $item (@{$questions}) {
                   9527:         my $question = $item;
                   9528:         my ($first,$count,$last);
                   9529:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   9530:             $question = $1;
                   9531:             my $subquestion = $2;
1.691     raeburn  9532:             my $responsenum = $question-1;
                   9533:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9534:                 $responsenum = $respnumlookup->{$question-1};
                   9535:                 if (ref($startline) eq 'HASH') {
                   9536:                     $first = $startline->{$question-1} + 1;
                   9537:                 }
                   9538:             } else {
                   9539:                 $first = $first_bubble_line{$responsenum} + 1;
                   9540:             }
                   9541:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9542:             my $subcount = 1;
                   9543:             while ($subcount<$subquestion) {
                   9544:                 $first += $subans[$subcount-1];
                   9545:                 $subcount ++;
                   9546:             }
                   9547:             $count = $subans[$subquestion-1];
                   9548:         } else {
1.691     raeburn  9549:             my $responsenum = $question-1;
                   9550:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9551:                 $responsenum = $respnumlookup->{$question-1};
                   9552:                 if (ref($startline) eq 'HASH') {
                   9553:                     $first = $startline->{$question-1} + 1;
                   9554:                 }
                   9555:             } else {
                   9556:                 $first = $first_bubble_line{$responsenum} + 1;
                   9557:             }
                   9558: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9559:         }
1.506     raeburn  9560:         $last = $first+$count-1;
1.503     raeburn  9561:         push(@lines, ($first..$last));
1.497     foxr     9562:     }
                   9563:     return join(',', @lines);
                   9564: }
                   9565: 
                   9566: =pod 
                   9567: 
                   9568: =item prompt_for_corrections
                   9569: 
                   9570: Prompts for a potentially multiline correction to the
                   9571: user's bubbling (factors out common code from scantron_get_correction
                   9572: for multi and missing bubble cases).
                   9573: 
                   9574:  Arguments:
                   9575:    $r           - Apache request object.
                   9576:    $question    - The question number to prompt for.
                   9577:    $scan_config - The scantron file configuration hash.
                   9578:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  9579:    $error       - Type of error
1.691     raeburn  9580:    $randomorder - True if randomorder in use.
                   9581:    $randompick  - True if randompick in use.
                   9582:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9583:                     for current line to question number used for same question
                   9584:                     in "Master Seqence" (as seen by Course Coordinator).
                   9585:    $startline   - Reference to hash where key is question number (0 is first)
                   9586:                   and value is number of first bubble line for current student
                   9587:                   or code-based randompick and/or randomorder.
                   9588: 
1.497     foxr     9589: 
                   9590:  Implicit inputs:
                   9591:    %bubble_lines_per_response   - Starting line numbers for each question.
                   9592:                                   Numbered from 0 (but question numbers are from
                   9593:                                   1.
                   9594:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  9595:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   9596:                                   type problems render as separate sub-questions, 
1.503     raeburn  9597:                                   in exam mode. This hash contains a 
                   9598:                                   comma-separated list of the lines per 
                   9599:                                   sub-question.
1.510     raeburn  9600:    %responsetype_per_response   - essayresponse, formularesponse,
                   9601:                                   stringresponse, imageresponse, reactionresponse,
                   9602:                                   and organicresponse type problem parts can have
1.503     raeburn  9603:                                   multiple lines per response if the weight
                   9604:                                   assigned exceeds 10.  In this case, only
                   9605:                                   one bubble per line is permitted, but more 
                   9606:                                   than one line might contain bubbles, e.g.
                   9607:                                   bubbling of: line 1 - J, line 2 - J, 
                   9608:                                   line 3 - B would assign 22 points.  
1.497     foxr     9609: 
                   9610: =cut
                   9611: 
                   9612: sub prompt_for_corrections {
1.691     raeburn  9613:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   9614:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  9615:     my ($current_line,$lines);
                   9616:     my @linenums;
                   9617:     my $questionnum = $question;
1.691     raeburn  9618:     my ($first,$responsenum);
1.503     raeburn  9619:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   9620:         $question = $1;
                   9621:         my $subquestion = $2;
1.691     raeburn  9622:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9623:             $responsenum = $respnumlookup->{$question-1};
                   9624:             if (ref($startline) eq 'HASH') {
                   9625:                 $first = $startline->{$question-1};
                   9626:             }
                   9627:         } else {
                   9628:             $responsenum = $question-1;
1.714     raeburn  9629:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  9630:         }
                   9631:         $current_line = $first + 1 ;
                   9632:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9633:         my $subcount = 1;
                   9634:         while ($subcount<$subquestion) {
                   9635:             $current_line += $subans[$subcount-1];
                   9636:             $subcount ++;
                   9637:         }
                   9638:         $lines = $subans[$subquestion-1];
                   9639:     } else {
1.691     raeburn  9640:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9641:             $responsenum = $respnumlookup->{$question-1};
                   9642:             if (ref($startline) eq 'HASH') { 
                   9643:                 $first = $startline->{$question-1};
                   9644:             }
                   9645:         } else {
                   9646:             $responsenum = $question-1;
                   9647:             $first = $first_bubble_line{$responsenum};
                   9648:         }
                   9649:         $current_line = $first + 1;
                   9650:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9651:     }
1.497     foxr     9652:     if ($lines > 1) {
1.503     raeburn  9653:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  9654:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   9655:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   9656:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   9657:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   9658:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   9659:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   9660:             $r->print(
                   9661:                 &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)
                   9662:                .'<br /><br />'
                   9663:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   9664:                .'<br />'
                   9665:                .&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.')
                   9666:                .'<br />'
                   9667:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   9668:                .'<br /><br />'
                   9669:             );
1.503     raeburn  9670:         } else {
                   9671:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   9672:         }
1.497     foxr     9673:     }
                   9674:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  9675:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  9676: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  9677: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  9678:         push(@linenums,$current_line);
1.497     foxr     9679: 	$current_line++;
                   9680:     }
                   9681:     if ($lines > 1) {
                   9682: 	$r->print("<hr /><br />");
                   9683:     }
1.503     raeburn  9684:     return @linenums;
1.157     albertel 9685: }
1.423     albertel 9686: 
                   9687: =pod
                   9688: 
                   9689: =item scantron_bubble_selector
                   9690:   
                   9691:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 9692:    possibly showing the existing the selected bubbles if known
1.423     albertel 9693: 
                   9694:  Arguments:
                   9695:     $r           - Apache request object
1.754     raeburn  9696:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     9697:     $line        - Number of the line being displayed.
1.503     raeburn  9698:     $questionnum - Question number (may include subquestion)
                   9699:     $error       - Type of error.
1.497     foxr     9700:     @selected    - Array of bubbles picked on this line.
1.423     albertel 9701: 
                   9702: =cut
                   9703: 
1.157     albertel 9704: sub scantron_bubble_selector {
1.503     raeburn  9705:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 9706:     my $max=$$scan_config{'Qlength'};
1.274     albertel 9707: 
                   9708:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  9709:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   9710:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   9711:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   9712:             $max=$$scan_config{'BubblesPerRow'};
                   9713:             if (($scmode eq 'number') && ($max > 10)) {
                   9714:                 $max = 10;
                   9715:             } elsif (($scmode eq 'letter') && $max > 26) {
                   9716:                 $max = 26;
                   9717:             }
                   9718:         } else {
                   9719:             $max = 10;
                   9720:         }
                   9721:     }
1.274     albertel 9722: 
1.157     albertel 9723:     my @alphabet=('A'..'Z');
1.503     raeburn  9724:     $r->print(&Apache::loncommon::start_data_table().
                   9725:               &Apache::loncommon::start_data_table_row());
                   9726:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     9727:     for (my $i=0;$i<$max+1;$i++) {
                   9728: 	$r->print("\n".'<td align="center">');
                   9729: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   9730: 	else { $r->print('&nbsp;'); }
                   9731: 	$r->print('</td>');
                   9732:     }
1.503     raeburn  9733:     $r->print(&Apache::loncommon::end_data_table_row().
                   9734:               &Apache::loncommon::start_data_table_row());
1.497     foxr     9735:     for (my $i=0;$i<$max;$i++) {
                   9736: 	$r->print("\n".
                   9737: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   9738: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   9739:     }
1.503     raeburn  9740:     my $nobub_checked = ' ';
                   9741:     if ($error eq 'missingbubble') {
                   9742:         $nobub_checked = ' checked = "checked" ';
                   9743:     }
                   9744:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   9745: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   9746:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   9747:               $line.'" value="'.$questionnum.'" /></td>');
                   9748:     $r->print(&Apache::loncommon::end_data_table_row().
                   9749:               &Apache::loncommon::end_data_table());
1.157     albertel 9750: }
                   9751: 
1.423     albertel 9752: =pod
                   9753: 
                   9754: =item num_matches
                   9755: 
1.424     albertel 9756:    Counts the number of characters that are the same between the two arguments.
                   9757: 
                   9758:  Arguments:
                   9759:    $orig - CODE from the scanline
                   9760:    $code - CODE to match against
                   9761: 
                   9762:  Returns:
                   9763:    $count - integer count of the number of same characters between the
                   9764:             two arguments
                   9765: 
1.423     albertel 9766: =cut
                   9767: 
1.194     albertel 9768: sub num_matches {
                   9769:     my ($orig,$code) = @_;
                   9770:     my @code=split(//,$code);
                   9771:     my @orig=split(//,$orig);
                   9772:     my $same=0;
                   9773:     for (my $i=0;$i<scalar(@code);$i++) {
                   9774: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   9775:     }
                   9776:     return $same;
                   9777: }
                   9778: 
1.423     albertel 9779: =pod
                   9780: 
                   9781: =item scantron_get_closely_matching_CODEs
                   9782: 
1.424     albertel 9783:    Cycles through all CODEs and finds the set that has the greatest
                   9784:    number of same characters as the provided CODE
                   9785: 
                   9786:  Arguments:
                   9787:    $allcodes - hash ref returned by &get_codes()
                   9788:    $CODE     - CODE from the current scanline
                   9789: 
                   9790:  Returns:
                   9791:    2 element list
                   9792:     - first elements is number of how closely matching the best fit is 
                   9793:       (5 means best set has 5 matching characters)
                   9794:     - second element is an arrary ref containing the set of valid CODEs
                   9795:       that best fit the passed in CODE
                   9796: 
1.423     albertel 9797: =cut
                   9798: 
1.194     albertel 9799: sub scantron_get_closely_matching_CODEs {
                   9800:     my ($allcodes,$CODE)=@_;
                   9801:     my @CODEs;
                   9802:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   9803: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   9804:     }
                   9805: 
                   9806:     return ($#CODEs,$CODEs[-1]);
                   9807: }
                   9808: 
1.423     albertel 9809: =pod
                   9810: 
                   9811: =item get_codes
                   9812: 
1.424     albertel 9813:    Builds a hash which has keys of all of the valid CODEs from the selected
                   9814:    set of remembered CODEs.
                   9815: 
                   9816:  Arguments:
                   9817:   $old_name - name of the set of remembered CODEs
                   9818:   $cdom     - domain of the course
                   9819:   $cnum     - internal course name
                   9820: 
                   9821:  Returns:
                   9822:   %allcodes - keys are the valid CODEs, values are all 1
                   9823: 
1.423     albertel 9824: =cut
                   9825: 
1.194     albertel 9826: sub get_codes {
1.280     foxr     9827:     my ($old_name, $cdom, $cnum) = @_;
                   9828:     if (!$old_name) {
                   9829: 	$old_name=$env{'form.scantron_CODElist'};
                   9830:     }
                   9831:     if (!$cdom) {
                   9832: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9833:     }
                   9834:     if (!$cnum) {
                   9835: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   9836:     }
1.278     albertel 9837:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   9838: 				    $cdom,$cnum);
                   9839:     my %allcodes;
                   9840:     if ($result{"type\0$old_name"} eq 'number') {
                   9841: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   9842:     } else {
                   9843: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   9844:     }
1.194     albertel 9845:     return %allcodes;
                   9846: }
                   9847: 
1.423     albertel 9848: =pod
                   9849: 
                   9850: =item scantron_validate_CODE
                   9851: 
1.424     albertel 9852:    Validates all scanlines in the selected file to not have any
                   9853:    invalid or underspecified CODEs and that none of the codes are
                   9854:    duplicated if this was requested.
                   9855: 
1.423     albertel 9856: =cut
                   9857: 
1.157     albertel 9858: sub scantron_validate_CODE {
                   9859:     my ($r,$currentphase) = @_;
1.754     raeburn  9860:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 9861:     if ($scantron_config{'CODElocation'} &&
                   9862: 	$scantron_config{'CODEstart'} &&
                   9863: 	$scantron_config{'CODElength'}) {
1.257     albertel 9864: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 9865: 	    &FIXME_blow_up()
                   9866: 	}
                   9867:     } else {
                   9868: 	return (0,$currentphase+1);
                   9869:     }
                   9870:     
                   9871:     my %usedCODEs;
                   9872: 
1.194     albertel 9873:     my %allcodes=&get_codes();
1.186     albertel 9874: 
1.582     raeburn  9875:     my $nav_error;
1.649     raeburn  9876:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  9877:     if ($nav_error) {
                   9878:         $r->print(&navmap_errormsg());
                   9879:         return(1,$currentphase);
                   9880:     }
1.447     foxr     9881: 
1.186     albertel 9882:     my ($scanlines,$scan_data)=&scantron_getfile();
                   9883:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9884: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 9885: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9886: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9887: 						 $scan_data);
                   9888: 	my $CODE=$$scan_record{'scantron.CODE'};
                   9889: 	my $error=0;
1.224     albertel 9890: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   9891: 	    &scantron_get_correction($r,$i,$scan_record,
                   9892: 				     \%scantron_config,
                   9893: 				     $line,'incorrectCODE',\%allcodes);
                   9894: 	    return(1,$currentphase);
                   9895: 	}
1.221     albertel 9896: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   9897: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 9898: 	    &scantron_get_correction($r,$i,$scan_record,
                   9899: 				     \%scantron_config,
1.194     albertel 9900: 				     $line,'incorrectCODE',\%allcodes);
                   9901: 	    return(1,$currentphase);
1.186     albertel 9902: 	}
1.214     albertel 9903: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 9904: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 9905: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 9906: 	    &scantron_get_correction($r,$i,$scan_record,
                   9907: 				     \%scantron_config,
1.194     albertel 9908: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   9909: 	    return(1,$currentphase);
1.186     albertel 9910: 	}
1.524     raeburn  9911: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 9912:     }
1.157     albertel 9913:     return (0,$currentphase+1);
                   9914: }
                   9915: 
1.423     albertel 9916: =pod
                   9917: 
                   9918: =item scantron_validate_doublebubble
                   9919: 
1.424     albertel 9920:    Validates all scanlines in the selected file to not have any
                   9921:    bubble lines with multiple bubbles marked.
                   9922: 
1.423     albertel 9923: =cut
                   9924: 
1.157     albertel 9925: sub scantron_validate_doublebubble {
                   9926:     my ($r,$currentphase) = @_;
                   9927:     #get student info
                   9928:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9929:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  9930:     my (undef,undef,$sequence)=
                   9931:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 9932: 
                   9933:     #get scantron line setup
1.754     raeburn  9934:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9935:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  9936: 
                   9937:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9938:     unless (ref($navmap)) {
                   9939:         $r->print(&navmap_errormsg());
                   9940:         return(1,$currentphase);
                   9941:     }
                   9942:     my $map=$navmap->getResourceByUrl($sequence);
                   9943:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9944:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9945:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   9946:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9947: 
1.583     raeburn  9948:     my $nav_error;
1.691     raeburn  9949:     if (ref($map)) {
                   9950:         $randomorder = $map->randomorder();
                   9951:         $randompick = $map->randompick();
1.788     raeburn  9952:         unless ($randomorder || $randompick) {
                   9953:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9954:                 if ($res->randomorder()) {
                   9955:                     $randomorder = 1;
                   9956:                 }
                   9957:                 if ($res->randompick()) {
                   9958:                     $randompick = 1;
                   9959:                 }
                   9960:                 last if ($randomorder || $randompick);
                   9961:             }
                   9962:         }
1.691     raeburn  9963:         if ($randomorder || $randompick) {
                   9964:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9965:             if ($nav_error) {
                   9966:                 $r->print(&navmap_errormsg());
                   9967:                 return(1,$currentphase);
                   9968:             }
                   9969:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9970:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   9971:         }
                   9972:     } else {
                   9973:         $r->print(&navmap_errormsg());
                   9974:         return(1,$currentphase);
                   9975:     }
                   9976: 
1.649     raeburn  9977:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  9978:     if ($nav_error) {
                   9979:         $r->print(&navmap_errormsg());
                   9980:         return(1,$currentphase);
                   9981:     }
1.447     foxr     9982: 
1.157     albertel 9983:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9984: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9985: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9986: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9987: 						 $scan_data,undef,\%idmap,$randomorder,
                   9988:                                                  $randompick,$sequence,\@master_seq,
                   9989:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9990:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 9991: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   9992: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   9993: 				 'doublebubble',
1.691     raeburn  9994: 				 $$scan_record{'scantron.doubleerror'},
                   9995:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 9996:     	return (1,$currentphase);
                   9997:     }
                   9998:     return (0,$currentphase+1);
                   9999: }
                   10000: 
1.423     albertel 10001: 
1.503     raeburn  10002: sub scantron_get_maxbubble {
1.649     raeburn  10003:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 10004:     if (defined($env{'form.scantron_maxbubble'}) &&
                   10005: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     10006: 	&restore_bubble_lines();
1.257     albertel 10007: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 10008:     }
1.330     albertel 10009: 
1.447     foxr     10010:     my (undef, undef, $sequence) =
1.257     albertel 10011: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 10012: 
1.447     foxr     10013:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10014:     unless (ref($navmap)) {
                   10015:         if (ref($nav_error)) {
                   10016:             $$nav_error = 1;
                   10017:         }
1.591     raeburn  10018:         return;
1.582     raeburn  10019:     }
1.191     albertel 10020:     my $map=$navmap->getResourceByUrl($sequence);
                   10021:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  10022:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 10023: 
                   10024:     &Apache::lonxml::clear_problem_counter();
                   10025: 
1.557     raeburn  10026:     my $uname       = $env{'user.name'};
                   10027:     my $udom        = $env{'user.domain'};
1.435     foxr     10028:     my $cid         = $env{'request.course.id'};
                   10029:     my $total_lines = 0;
                   10030:     %bubble_lines_per_response = ();
1.447     foxr     10031:     %first_bubble_line         = ();
1.503     raeburn  10032:     %subdivided_bubble_lines   = ();
                   10033:     %responsetype_per_response = ();
1.691     raeburn  10034:     %masterseq_id_responsenum  = ();
1.554     raeburn  10035: 
1.447     foxr     10036:     my $response_number = 0;
                   10037:     my $bubble_line     = 0;
1.191     albertel 10038:     foreach my $resource (@resources) {
1.691     raeburn  10039:         my $resid = $resource->id(); 
1.672     raeburn  10040:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   10041:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  10042:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   10043: 	    foreach my $part_id (@{$parts}) {
                   10044:                 my $lines;
                   10045: 
                   10046: 	        # TODO - make this a persistent hash not an array.
                   10047: 
                   10048:                 # optionresponse, matchresponse and rankresponse type items 
                   10049:                 # render as separate sub-questions in exam mode.
                   10050:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   10051:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   10052:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   10053:                     my ($numbub,$numshown);
                   10054:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   10055:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   10056:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   10057:                         }
                   10058:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   10059:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   10060:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   10061:                         }
                   10062:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   10063:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   10064:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   10065:                         }
                   10066:                     }
                   10067:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   10068:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   10069:                     }
1.649     raeburn  10070:                     my $bubbles_per_row =
                   10071:                         &bubblesheet_bubbles_per_row($scantron_config);
                   10072:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   10073:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  10074:                         $inner_bubble_lines++;
                   10075:                     }
                   10076:                     for (my $i=0; $i<$numshown; $i++) {
                   10077:                         $subdivided_bubble_lines{$response_number} .= 
                   10078:                             $inner_bubble_lines.',';
                   10079:                     }
                   10080:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   10081:                     $lines = $numshown * $inner_bubble_lines;
                   10082:                 } else {
                   10083:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  10084:                 }
1.542     raeburn  10085: 
                   10086:                 $first_bubble_line{$response_number} = $bubble_line;
                   10087: 	        $bubble_lines_per_response{$response_number} = $lines;
                   10088:                 $responsetype_per_response{$response_number} = 
                   10089:                     $analysis->{$part_id.'.type'};
1.691     raeburn  10090:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  10091: 	        $response_number++;
                   10092: 
                   10093: 	        $bubble_line +=  $lines;
                   10094: 	        $total_lines +=  $lines;
                   10095: 	    }
                   10096:         }
                   10097:     }
1.552     raeburn  10098:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  10099: 
                   10100:     &save_bubble_lines();
                   10101:     $env{'form.scantron_maxbubble'} =
                   10102: 	$total_lines;
                   10103:     return $env{'form.scantron_maxbubble'};
                   10104: }
1.523     raeburn  10105: 
1.649     raeburn  10106: sub bubblesheet_bubbles_per_row {
                   10107:     my ($scantron_config) = @_;
                   10108:     my $bubbles_per_row;
                   10109:     if (ref($scantron_config) eq 'HASH') {
                   10110:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   10111:     }
                   10112:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   10113:         $bubbles_per_row = 10;
                   10114:     }
                   10115:     return $bubbles_per_row;
                   10116: }
                   10117: 
1.157     albertel 10118: sub scantron_validate_missingbubbles {
                   10119:     my ($r,$currentphase) = @_;
                   10120:     #get student info
                   10121:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10122:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  10123:     my (undef,undef,$sequence)=
                   10124:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 10125: 
                   10126:     #get scantron line setup
1.754     raeburn  10127:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 10128:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  10129: 
                   10130:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10131:     unless (ref($navmap)) {
                   10132:         $r->print(&navmap_errormsg());
                   10133:         return(1,$currentphase);
                   10134:     }
                   10135: 
                   10136:     my $map=$navmap->getResourceByUrl($sequence);
                   10137:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10138:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10139:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   10140:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10141: 
1.582     raeburn  10142:     my $nav_error;
1.691     raeburn  10143:     if (ref($map)) {
                   10144:         $randomorder = $map->randomorder();
                   10145:         $randompick = $map->randompick();
1.788     raeburn  10146:         unless ($randomorder || $randompick) {
                   10147:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10148:                 if ($res->randomorder()) {
                   10149:                     $randomorder = 1;
                   10150:                 }
                   10151:                 if ($res->randompick()) {
                   10152:                     $randompick = 1;
                   10153:                 }
                   10154:                 last if ($randomorder || $randompick);
                   10155:             }
                   10156:         }
1.691     raeburn  10157:         if ($randomorder || $randompick) {
                   10158:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10159:             if ($nav_error) {
                   10160:                 $r->print(&navmap_errormsg());
                   10161:                 return(1,$currentphase);
                   10162:             }
                   10163:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10164:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   10165:         }
                   10166:     } else {
                   10167:         $r->print(&navmap_errormsg());
                   10168:         return(1,$currentphase);
                   10169:     }
                   10170: 
                   10171: 
1.649     raeburn  10172:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  10173:     if ($nav_error) {
1.691     raeburn  10174:         $r->print(&navmap_errormsg());
1.693     raeburn  10175:         return(1,$currentphase);
1.582     raeburn  10176:     }
1.691     raeburn  10177: 
1.157     albertel 10178:     if (!$max_bubble) { $max_bubble=2**31; }
                   10179:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 10180: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10181: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  10182: 	my $scan_record =
                   10183:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   10184: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   10185:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   10186:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 10187: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   10188: 	my @to_correct;
1.470     foxr     10189: 	
                   10190: 	# Probably here's where the error is...
                   10191: 
1.157     albertel 10192: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  10193:             my $lastbubble;
                   10194:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   10195:                my $question = $1;
                   10196:                my $subquestion = $2;
1.691     raeburn  10197:                my ($first,$responsenum);
                   10198:                if ($randomorder || $randompick) {
                   10199:                    $responsenum = $respnumlookup{$question-1};
                   10200:                    $first = $startline{$question-1};
                   10201:                } else {
                   10202:                    $responsenum = $question-1; 
                   10203:                    $first = $first_bubble_line{$responsenum};
                   10204:                }
                   10205:                if (!defined($first)) { next; }
                   10206:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  10207:                my $subcount = 1;
                   10208:                while ($subcount<$subquestion) {
                   10209:                    $first += $subans[$subcount-1];
                   10210:                    $subcount ++;
                   10211:                }
                   10212:                my $count = $subans[$subquestion-1];
                   10213:                $lastbubble = $first + $count;
                   10214:             } else {
1.691     raeburn  10215:                my ($first,$responsenum);
                   10216:                if ($randomorder || $randompick) {
                   10217:                    $responsenum = $respnumlookup{$missing-1};
                   10218:                    $first = $startline{$missing-1};
                   10219:                } else {
                   10220:                    $responsenum = $missing-1;
                   10221:                    $first = $first_bubble_line{$responsenum};
                   10222:                }
                   10223:                if (!defined($first)) { next; }
                   10224:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  10225:             }
                   10226:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 10227: 	    push(@to_correct,$missing);
                   10228: 	}
                   10229: 	if (@to_correct) {
                   10230: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  10231: 				     $line,'missingbubble',\@to_correct,
                   10232:                                      $randomorder,$randompick,\%respnumlookup,
                   10233:                                      \%startline);
1.157     albertel 10234: 	    return (1,$currentphase);
                   10235: 	}
                   10236: 
                   10237:     }
                   10238:     return (0,$currentphase+1);
                   10239: }
                   10240: 
1.663     raeburn  10241: sub hand_bubble_option {
                   10242:     my (undef, undef, $sequence) =
                   10243:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10244:     return if ($sequence eq '');
                   10245:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10246:     unless (ref($navmap)) {
                   10247:         return;
                   10248:     }
                   10249:     my $needs_hand_bubbles;
                   10250:     my $map=$navmap->getResourceByUrl($sequence);
                   10251:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10252:     foreach my $res (@resources) {
                   10253:         if (ref($res)) {
                   10254:             if ($res->is_problem()) {
                   10255:                 my $partlist = $res->parts();
                   10256:                 foreach my $part (@{ $partlist }) {
                   10257:                     my @types = $res->responseType($part);
                   10258:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   10259:                         $needs_hand_bubbles = 1;
                   10260:                         last;
                   10261:                     }
                   10262:                 }
                   10263:             }
                   10264:         }
                   10265:     }
                   10266:     if ($needs_hand_bubbles) {
1.754     raeburn  10267:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  10268:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10269:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   10270:                &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 />').
                   10271:                '<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  10272:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  10273:     }
                   10274:     return;
                   10275: }
1.423     albertel 10276: 
1.82      albertel 10277: sub scantron_process_students {
1.608     www      10278:     my ($r,$symb) = @_;
1.513     foxr     10279: 
1.257     albertel 10280:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     10281:     if (!$symb) {
                   10282: 	return '';
                   10283:     }
1.324     albertel 10284:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 10285: 
1.754     raeburn  10286:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  10287:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 10288:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 10289:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10290:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 10291:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10292:     unless (ref($navmap)) {
                   10293:         $r->print(&navmap_errormsg());
                   10294:         return '';
1.691     raeburn  10295:     }
1.83      albertel 10296:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10297:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.788     raeburn  10298:         %grader_randomlists_by_symb,%symb_for_examcode);
1.677     raeburn  10299:     if (ref($map)) {
                   10300:         $randomorder = $map->randomorder();
1.689     raeburn  10301:         $randompick = $map->randompick();
1.788     raeburn  10302:         unless ($randomorder || $randompick) {
                   10303:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10304:                 if ($res->randomorder()) {
                   10305:                     $randomorder = 1;
                   10306:                 }
                   10307:                 if ($res->randompick()) {
                   10308:                     $randompick = 1;
                   10309:                 }
                   10310:                 last if ($randomorder || $randompick);
                   10311:             }
                   10312:         }
1.691     raeburn  10313:     } else {
                   10314:         $r->print(&navmap_errormsg());
                   10315:         return '';
1.677     raeburn  10316:     }
1.691     raeburn  10317:     my $nav_error;
1.83      albertel 10318:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10319:     if ($randomorder || $randompick) {
1.788     raeburn  10320:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
1.691     raeburn  10321:         if ($nav_error) {
                   10322:             $r->print(&navmap_errormsg());
                   10323:             return '';
                   10324:         }
                   10325:     }
1.557     raeburn  10326:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  10327:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  10328: 
1.554     raeburn  10329:     my ($uname,$udom);
1.82      albertel 10330:     my $result= <<SCANTRONFORM;
1.81      albertel 10331: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   10332:   <input type="hidden" name="command" value="scantron_configphase" />
                   10333:   $default_form_data
                   10334: SCANTRONFORM
1.82      albertel 10335:     $r->print($result);
                   10336: 
1.770     raeburn  10337:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 10338:     my @delayqueue;
1.542     raeburn  10339:     my (%completedstudents,%scandata);
1.770     raeburn  10340: 
1.520     www      10341:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 10342:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10343:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   10344:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  10345:     $r->print('<br />');
1.140     albertel 10346:     my $start=&Time::HiRes::time();
1.158     albertel 10347:     my $i=-1;
1.542     raeburn  10348:     my $started;
1.447     foxr     10349: 
1.649     raeburn  10350:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10351:     if ($nav_error) {
                   10352:         $r->print(&navmap_errormsg());
                   10353:         return '';
                   10354:     }
                   10355: 
1.513     foxr     10356:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   10357:     # the user and return.
                   10358: 
                   10359:     if ($ssi_error) {
                   10360: 	$r->print("</form>");
                   10361: 	&ssi_print_error($r);
1.520     www      10362:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     10363: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   10364:     }
1.447     foxr     10365: 
1.755     raeburn  10366:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  10367:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  10368:     my %orderedforcode;
1.542     raeburn  10369: 
1.157     albertel 10370:     while ($i<$scanlines->{'count'}) {
                   10371:  	($uname,$udom)=('','');
                   10372:  	$i++;
1.200     albertel 10373:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10374:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 10375: 	if ($started) {
1.667     www      10376: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 10377: 	}
                   10378: 	$started=1;
1.691     raeburn  10379:         my %respnumlookup = ();
                   10380:         my %startline = ();
                   10381:         my $total;
1.157     albertel 10382:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  10383:                                                  $scan_data,undef,\%idmap,$randomorder,
                   10384:                                                  $randompick,$sequence,\@master_seq,
                   10385:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   10386:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   10387:                                                  \$total);
1.157     albertel 10388:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10389:  					      \%idmap,$i)) {
                   10390:   	    &scantron_add_delay(\@delayqueue,$line,
                   10391:  				'Unable to find a student that matches',1);
                   10392:  	    next;
                   10393:   	}
                   10394:  	if (exists $completedstudents{$uname}) {
                   10395:  	    &scantron_add_delay(\@delayqueue,$line,
                   10396:  				'Student '.$uname.' has multiple sheets',2);
                   10397:  	    next;
                   10398:  	}
1.677     raeburn  10399:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  10400:         if (($checksec ne '') && ($checksec ne $usec)) {
                   10401:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   10402:                 &scantron_add_delay(\@delayqueue,$line,
                   10403:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   10404:                 next;
                   10405:             }
                   10406:         }
1.677     raeburn  10407:         my $user = $uname.':'.$usec;
1.157     albertel 10408:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 10409: 
1.677     raeburn  10410:         my $scancode;
                   10411:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10412:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10413:             $scancode = $scan_record->{'scantron.CODE'};
                   10414:         } else {
                   10415:             $scancode = '';
                   10416:         }
                   10417: 
                   10418:         my @mapresources = @resources;
1.689     raeburn  10419:         if ($randomorder || $randompick) {
1.678     raeburn  10420:             @mapresources = 
1.691     raeburn  10421:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10422:                              \%orderedforcode);
1.677     raeburn  10423:         }
1.586     raeburn  10424:         my (%partids_by_symb,$res_error);
1.677     raeburn  10425:         foreach my $resource (@mapresources) {
1.586     raeburn  10426:             my $ressymb;
                   10427:             if (ref($resource)) {
                   10428:                 $ressymb = $resource->symb();
                   10429:             } else {
                   10430:                 $res_error = 1;
                   10431:                 last;
                   10432:             }
1.557     raeburn  10433:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10434:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10435:                 my $currcode;
                   10436:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10437:                     $currcode = $scancode;
                   10438:                 }
1.557     raeburn  10439:                 my ($analysis,$parts) =
1.672     raeburn  10440:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  10441:                                               $uname,$udom,undef,$bubbles_per_row,
                   10442:                                               $currcode);
1.557     raeburn  10443:                 $partids_by_symb{$ressymb} = $parts;
                   10444:             } else {
                   10445:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   10446:             }
1.554     raeburn  10447:         }
                   10448: 
1.586     raeburn  10449:         if ($res_error) {
                   10450:             &scantron_add_delay(\@delayqueue,$line,
                   10451:                                 'An error occurred while grading student '.$uname,2);
                   10452:             next;
                   10453:         }
                   10454: 
1.330     albertel 10455: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  10456:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 10457: 
                   10458: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   10459: 	    &scantron_putfile($scanlines,$scan_data);
                   10460: 	}
1.161     albertel 10461: 	
1.542     raeburn  10462:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10463:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  10464:                                    $bubbles_per_row,$randomorder,$randompick,
                   10465:                                    \%respnumlookup,\%startline) 
                   10466:             eq 'ssi_error') {
1.542     raeburn  10467:             $ssi_error = 0; # So end of handler error message does not trigger.
                   10468:             $r->print("</form>");
                   10469:             &ssi_print_error($r);
                   10470:             &Apache::lonnet::remove_lock($lock);
                   10471:             return '';      # Why return ''?  Beats me.
                   10472:         }
1.513     foxr     10473: 
1.692     raeburn  10474:         if (($scancode) && ($randomorder || $randompick)) {
1.788     raeburn  10475:             foreach my $key (keys(%symb_for_examcode)) {
                   10476:                 my $symb_in_map = $symb_for_examcode{$key};
                   10477:                 if ($symb_in_map ne '') {
                   10478:                     my $parmresult =
                   10479:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   10480:                                                                '0_examcode',2,$scancode,
                   10481:                                                                'string_examcode',$uname,
                   10482:                                                                $udom);
                   10483:                 }
                   10484:             }
1.692     raeburn  10485:         }
1.140     albertel 10486: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  10487:         if ($env{'form.verifyrecord'}) {
                   10488:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  10489:             if ($randompick) {
                   10490:                 if ($total) {
                   10491:                     $lastpos = $total*$scantron_config{'Qlength'};
                   10492:                 }
                   10493:             }
                   10494: 
1.542     raeburn  10495:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10496:             chomp($studentdata);
                   10497:             $studentdata =~ s/\r$//;
                   10498:             my $studentrecord = '';
                   10499:             my $counter = -1;
1.677     raeburn  10500:             foreach my $resource (@mapresources) {
1.554     raeburn  10501:                 my $ressymb = $resource->symb();
1.542     raeburn  10502:                 ($counter,my $recording) =
                   10503:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10504:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10505:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   10506:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  10507:                 $studentrecord .= $recording;
                   10508:             }
                   10509:             if ($studentrecord ne $studentdata) {
1.554     raeburn  10510:                 &Apache::lonxml::clear_problem_counter();
                   10511:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10512:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  10513:                                            $bubbles_per_row,$randomorder,$randompick,
                   10514:                                            \%respnumlookup,\%startline) 
                   10515:                     eq 'ssi_error') {
1.554     raeburn  10516:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   10517:                     $r->print("</form>");
                   10518:                     &ssi_print_error($r);
                   10519:                     &Apache::lonnet::remove_lock($lock);
                   10520:                     delete($completedstudents{$uname});
                   10521:                     return '';
                   10522:                 }
1.542     raeburn  10523:                 $counter = -1;
                   10524:                 $studentrecord = '';
1.677     raeburn  10525:                 foreach my $resource (@mapresources) {
1.554     raeburn  10526:                     my $ressymb = $resource->symb();
1.542     raeburn  10527:                     ($counter,my $recording) =
                   10528:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10529:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10530:                                                  \%scantron_config,\%lettdig,$numletts,
                   10531:                                                  $randomorder,$randompick,\%respnumlookup,
                   10532:                                                  \%startline);
1.542     raeburn  10533:                     $studentrecord .= $recording;
                   10534:                 }
                   10535:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   10536:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  10537:                     if ($scancode eq '') {
1.658     bisitz   10538:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  10539:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   10540:                     } else {
1.658     bisitz   10541:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  10542:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   10543:                     }
                   10544:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   10545:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   10546:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   10547:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   10548:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10549:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   10550:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  10551:                               &Apache::loncommon::end_data_table_row().
                   10552:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10553:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   10554:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  10555:                               &Apache::loncommon::end_data_table_row().
                   10556:                               &Apache::loncommon::end_data_table().'</p>');
                   10557:                 } else {
                   10558:                     $r->print('<br /><span class="LC_warning">'.
                   10559:                              &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 />'.
                   10560:                              &mt("As a consequence, this user's submission history records two tries.").
                   10561:                                  '</span><br />');
                   10562:                 }
                   10563:             }
                   10564:         }
1.543     raeburn  10565:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 10566:     } continue {
1.330     albertel 10567: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  10568: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 10569:     }
1.140     albertel 10570:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      10571:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 10572: #    my $lasttime = &Time::HiRes::time()-$start;
                   10573: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 10574: 
1.200     albertel 10575:     $r->print("</form>");
1.157     albertel 10576:     return '';
1.75      albertel 10577: }
1.157     albertel 10578: 
1.557     raeburn  10579: sub graders_resources_pass {
1.649     raeburn  10580:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   10581:         $bubbles_per_row) = @_;
1.557     raeburn  10582:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   10583:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   10584:         foreach my $resource (@{$resources}) {
                   10585:             my $ressymb = $resource->symb();
                   10586:             my ($analysis,$parts) =
                   10587:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  10588:                                           $env{'user.name'},$env{'user.domain'},
                   10589:                                           1,$bubbles_per_row);
1.557     raeburn  10590:             $grader_partids_by_symb->{$ressymb} = $parts;
                   10591:             if (ref($analysis) eq 'HASH') {
                   10592:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   10593:                     $grader_randomlists_by_symb->{$ressymb} =
                   10594:                         $analysis->{'parts_withrandomlist'};
                   10595:                 }
                   10596:             }
                   10597:         }
                   10598:     }
                   10599:     return;
                   10600: }
                   10601: 
1.678     raeburn  10602: =pod
                   10603: 
                   10604: =item users_order
                   10605: 
                   10606:   Returns array of resources in current map, ordered based on either CODE,
                   10607:   if this is a CODEd exam, or based on student's identity if this is a 
                   10608:   "NAMEd" exam.
                   10609: 
1.691     raeburn  10610:   Should be used when randomorder and/or randompick applied when the 
                   10611:   corresponding exam was printed, prior to students completing bubblesheets 
                   10612:   for the version of the exam the student received.
1.678     raeburn  10613: 
                   10614: =cut
                   10615: 
                   10616: sub users_order  {
1.691     raeburn  10617:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  10618:     my @mapresources;
1.691     raeburn  10619:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  10620:         return @mapresources;
1.691     raeburn  10621:     }
                   10622:     if ($scancode) {
                   10623:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   10624:             @mapresources = @{$orderedforcode->{$scancode}};
                   10625:         } else {
                   10626:             $env{'form.CODE'} = $scancode;
                   10627:             my $actual_seq =
                   10628:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10629:                                                                $master_seq,
                   10630:                                                                $user,$scancode,1);
                   10631:             if (ref($actual_seq) eq 'ARRAY') {
                   10632:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10633:                 if (ref($orderedforcode) eq 'HASH') {
                   10634:                     if (@mapresources > 0) { 
                   10635:                         $orderedforcode->{$scancode} = \@mapresources;
                   10636:                     }
                   10637:                 }
                   10638:             }
                   10639:             delete($env{'form.CODE'});
1.678     raeburn  10640:         }
                   10641:     } else {
                   10642:         my $actual_seq =
                   10643:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10644:                                                            $master_seq,
1.688     raeburn  10645:                                                            $user,undef,1);
1.678     raeburn  10646:         if (ref($actual_seq) eq 'ARRAY') {
                   10647:             @mapresources = 
                   10648:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10649:         }
1.691     raeburn  10650:     }
                   10651:     return @mapresources;
1.678     raeburn  10652: }
                   10653: 
1.542     raeburn  10654: sub grade_student_bubbles {
1.691     raeburn  10655:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   10656:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   10657:     my $uselookup = 0;
                   10658:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   10659:         (ref($startline) eq 'HASH')) {
                   10660:         $uselookup = 1;
                   10661:     }
                   10662: 
1.554     raeburn  10663:     if (ref($resources) eq 'ARRAY') {
                   10664:         my $count = 0;
                   10665:         foreach my $resource (@{$resources}) {
                   10666:             my $ressymb = $resource->symb();
                   10667:             my %form = ('submitted'      => 'scantron',
                   10668:                         'grade_target'   => 'grade',
                   10669:                         'grade_username' => $uname,
                   10670:                         'grade_domain'   => $udom,
                   10671:                         'grade_courseid' => $env{'request.course.id'},
                   10672:                         'grade_symb'     => $ressymb,
                   10673:                         'CODE'           => $scancode
                   10674:                        );
1.649     raeburn  10675:             if ($bubbles_per_row ne '') {
                   10676:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   10677:             }
1.663     raeburn  10678:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   10679:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   10680:             }
1.554     raeburn  10681:             if (ref($parts) eq 'HASH') {
                   10682:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   10683:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  10684:                         if ($uselookup) {
                   10685:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   10686:                         } else {
                   10687:                             $form{'scantron_questnum_start.'.$part} =
                   10688:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   10689:                         }
1.554     raeburn  10690:                         $count++;
                   10691:                     }
                   10692:                 }
                   10693:             }
                   10694:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   10695:             return 'ssi_error' if ($ssi_error);
                   10696:             last if (&Apache::loncommon::connection_aborted($r));
                   10697:         }
1.542     raeburn  10698:     }
                   10699:     return;
                   10700: }
                   10701: 
1.157     albertel 10702: sub scantron_upload_scantron_data {
1.767     raeburn  10703:     my ($r,$symb) = @_;
1.565     raeburn  10704:     my $dom = $env{'request.role.domain'};
1.754     raeburn  10705:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  10706:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   10707:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 10708:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 10709: 							  'domainid',
1.565     raeburn  10710: 							  'coursename',$dom);
                   10711:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   10712:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      10713:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  10714:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  10715:     &js_escape(\$nofile_alert);
1.579     raeburn  10716:     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  10717:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 10718:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 10719:     function checkUpload(formname) {
                   10720: 	if (formname.upfile.value == "") {
1.579     raeburn  10721: 	    alert("'.$nofile_alert.'");
1.157     albertel 10722: 	    return false;
                   10723: 	}
1.565     raeburn  10724:         if (formname.courseid.value == "") {
1.579     raeburn  10725:             alert("'.$nocourseid_alert.'");
1.565     raeburn  10726:             return false;
                   10727:         }
1.157     albertel 10728: 	formname.submit();
                   10729:     }
1.565     raeburn  10730: 
                   10731:     function ToSyllabus() {
                   10732:         var cdom = '."'$dom'".';
                   10733:         var cnum = document.rules.courseid.value;
                   10734:         if (cdom == "" || cdom == null) {
                   10735:             return;
                   10736:         }
                   10737:         if (cnum == "" || cnum == null) {
                   10738:            return;
                   10739:         }
                   10740:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   10741:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   10742:         return;
                   10743:     }
                   10744: 
1.754     raeburn  10745:     '.$formatjs.'
1.597     wenzelju 10746: '));
                   10747:     $r->print('
1.648     bisitz   10748: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  10749: 
1.492     albertel 10750: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  10751: '.$default_form_data.
                   10752:   &Apache::lonhtmlcommon::start_pick_box().
                   10753:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   10754:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   10755:   &Apache::lonhtmlcommon::row_closure().
                   10756:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   10757:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   10758:   &Apache::lonhtmlcommon::row_closure().
                   10759:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   10760:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  10761:   &Apache::lonhtmlcommon::row_closure());
                   10762:     if ($formatoptions) {
                   10763:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   10764:                   &Apache::lonhtmlcommon::row_closure());
                   10765:     }
                   10766:     $r->print(
1.565     raeburn  10767:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   10768:   '<input type="file" name="upfile" size="50" />'.
                   10769:   &Apache::lonhtmlcommon::row_closure(1).
                   10770:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   10771: 
1.492     albertel 10772: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   10773: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 10774: </form>
1.492     albertel 10775: ');
1.157     albertel 10776:     return '';
                   10777: }
                   10778: 
1.754     raeburn  10779: sub scantron_upload_dataformat {
                   10780:     my ($dom) = @_;
                   10781:     my ($formatoptions,$formattitle,$formatjs);
                   10782:     $formatjs = <<'END';
                   10783: function toggleScantab(form) {
                   10784:    return;
                   10785: }
                   10786: END
                   10787:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   10788:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10789:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10790:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   10791:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   10792:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  10793:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   10794:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   10795:                             my ($onclick,$formatextra,$singleline);
                   10796:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   10797:                             my $count = 0;
                   10798:                             foreach my $line (@lines) {
1.790     raeburn  10799:                                 next if (($line =~ /^\#/) || ($line eq ''));
1.756     raeburn  10800:                                 $singleline = $line;
                   10801:                                 $count ++;
                   10802:                             }
                   10803:                             if ($count > 1) {
                   10804:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  10805:                                                '<span class="LC_nobreak">'.
1.776     raeburn  10806:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  10807:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  10808:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   10809:                                 $formatjs = <<"END";
1.754     raeburn  10810: function toggleScantab(form) {
                   10811:     var divid = 'bubbletype';
                   10812:     if (document.getElementById(divid)) {
                   10813:         var radioname = 'fileformat';
                   10814:         var num = form.elements[radioname].length;
                   10815:         if (num) {
                   10816:             for (var i=0; i<num; i++) {
                   10817:                 if (form.elements[radioname][i].checked) {
                   10818:                     var chosen = form.elements[radioname][i].value;
                   10819:                     if (chosen == 'dat') {
                   10820:                         document.getElementById(divid).style.display = 'none';
                   10821:                     } else if (chosen == 'csv') {
1.757     raeburn  10822:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  10823:                     }
                   10824:                 }
                   10825:             }
                   10826:         }
                   10827:     }
                   10828:     return;
                   10829: }
                   10830: 
                   10831: END
1.756     raeburn  10832:                             } elsif ($count == 1) {
                   10833:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   10834:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   10835:                             }
                   10836:                             $formattitle = &mt('File format');
                   10837:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   10838:                                              &mt('Plain Text (no delimiters)').
                   10839:                                              '</label>'.('&nbsp;'x2).
                   10840:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   10841:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  10842:                         }
                   10843:                     }
                   10844:                 }
                   10845:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  10846:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10847:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  10848:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  10849:                         $formatoptions = &scantron_scantab();
                   10850:                     }
1.754     raeburn  10851:                 }
                   10852:             }
                   10853:         }
                   10854:     }
                   10855:     return ($formatoptions,$formattitle,$formatjs);
                   10856: }
1.423     albertel 10857: 
1.157     albertel 10858: sub scantron_upload_scantron_data_save {
1.767     raeburn  10859:     my ($r,$symb) = @_;
1.182     albertel 10860:     my $doanotherupload=
                   10861: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   10862: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 10863: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 10864: 	'</form>'."\n";
1.257     albertel 10865:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 10866: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  10867: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   10868:         !&Apache::lonnet::allowed('usc',
                   10869:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      10870: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      10871: 	unless ($symb) {
1.182     albertel 10872: 	    $r->print($doanotherupload);
                   10873: 	}
1.162     albertel 10874: 	return '';
                   10875:     }
1.257     albertel 10876:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  10877:     my $uploadedfile;
1.710     bisitz   10878:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 10879:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10880:         $r->print(
                   10881:             &Apache::lonhtmlcommon::confirm_success(
                   10882:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10883:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 10884:     } else {
1.754     raeburn  10885:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   10886:         my $parser;
                   10887:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10888:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10889:                 my $is_csv;
                   10890:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   10891:                 if (@possibles > 1) {
                   10892:                     if ($env{'form.fileformat'} eq 'csv') {
                   10893:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10894:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10895:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10896:                                     $is_csv = 1;
                   10897:                                 }
1.754     raeburn  10898:                             }
                   10899:                         }
                   10900:                     }
                   10901:                 } elsif (@possibles == 1) {
                   10902:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10903:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10904:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10905:                                 $is_csv = 1;
                   10906:                             }
1.754     raeburn  10907:                         }
                   10908:                     }
                   10909:                 }
                   10910:                 if ($is_csv) {
                   10911:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   10912:                 }
                   10913:             }
                   10914:         }
                   10915:         my $result =
                   10916:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  10917:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   10918:         if ($result =~ m{^/uploaded/}) {
                   10919:             $r->print(
                   10920:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   10921:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   10922:                         (length($env{'form.upfile'})-1),
                   10923:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  10924:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  10925:             if ($uploadedfile =~ /^scantron_orig_/) {
                   10926:                 my $logname = $uploadedfile;
                   10927:                 $logname =~ s/^scantron_orig_//;
                   10928:                 if ($logname ne '') {
                   10929:                     my $now = time;
                   10930:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   10931:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   10932:                 }
                   10933:             }
1.567     raeburn  10934:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  10935:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   10936:         } else {
                   10937:             $r->print(
                   10938:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   10939:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   10940:                           $result,
1.568     raeburn  10941: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 10942: 	}
                   10943:     }
1.174     albertel 10944:     if ($symb) {
1.612     www      10945: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 10946:     } else {
1.182     albertel 10947: 	$r->print($doanotherupload);
1.174     albertel 10948:     }
1.157     albertel 10949:     return '';
                   10950: }
                   10951: 
1.567     raeburn  10952: sub validate_uploaded_scantron_file {
1.770     raeburn  10953:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   10954: 
1.567     raeburn  10955:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   10956:     my @lines;
                   10957:     if ($scanlines ne '-1') {
                   10958:         @lines=split("\n",$scanlines,-1);
                   10959:     }
1.770     raeburn  10960:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   10961:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   10962:     if ($context eq 'download') {
                   10963:         $priv = 'mgr';
                   10964:     } else {
                   10965:         $priv = 'usc';
                   10966:     }
                   10967:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   10968:             (($env{'request.course.id'}) &&
                   10969:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   10970:         if ($env{'request.course.sec'} ne '') {
                   10971:             unless (&Apache::lonnet::allowed($priv,
                   10972:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   10973:                 unless ($context eq 'download') {
                   10974:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   10975:                 }
                   10976:                 return $output;
                   10977:             }
                   10978:             ($checksec,@possibles)=&gradable_sections();
                   10979:         }
                   10980:     }
1.567     raeburn  10981:     if (@lines) {
                   10982:         my (%counts,$max_match_format);
1.710     bisitz   10983:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  10984:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   10985:         my %idmap = &username_to_idmap($classlist);
                   10986:         foreach my $key (keys(%idmap)) {
                   10987:             my $lckey = lc($key);
                   10988:             $idmap{$lckey} = $idmap{$key};
                   10989:         }
                   10990:         my %unique_formats;
1.754     raeburn  10991:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  10992:         foreach my $line (@formatlines) {
1.790     raeburn  10993:             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  10994:             my @config = split(/:/,$line);
                   10995:             my $idstart = $config[5];
                   10996:             my $idlength = $config[6];
                   10997:             if (($idstart ne '') && ($idlength > 0)) {
                   10998:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   10999:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   11000:                 } else {
                   11001:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   11002:                 }
                   11003:             }
                   11004:         }
                   11005:         foreach my $key (keys(%unique_formats)) {
                   11006:             my ($idstart,$idlength) = split(':',$key);
                   11007:             %{$counts{$key}} = (
                   11008:                                'found'   => 0,
                   11009:                                'total'   => 0,
1.770     raeburn  11010:                                'totalanysec' => 0,
                   11011:                                'othersec' => 0,
1.567     raeburn  11012:                               );
                   11013:             foreach my $line (@lines) {
                   11014:                 next if ($line =~ /^#/);
                   11015:                 next if ($line =~ /^[\s\cz]*$/);
                   11016:                 my $id = substr($line,$idstart-1,$idlength);
                   11017:                 $id = lc($id);
                   11018:                 if (exists($idmap{$id})) {
1.770     raeburn  11019:                     if ($checksec ne '') {
                   11020:                         $counts{$key}{'totalanysec'} ++;
                   11021:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   11022:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   11023:                             if ($stusec ne $checksec) {
                   11024:                                 if (@possibles) {
                   11025:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   11026:                                         $counts{$key}{'othersec'} ++;
                   11027:                                         next;
                   11028:                                     }
                   11029:                                 } else {
                   11030:                                     $counts{$key}{'othersec'} ++;
                   11031:                                     next;
                   11032:                                 }
                   11033:                             }
                   11034:                         }
                   11035:                     }
1.567     raeburn  11036:                     $counts{$key}{'found'} ++;
                   11037:                 }
                   11038:                 $counts{$key}{'total'} ++;
                   11039:             }
                   11040:             if ($counts{$key}{'total'}) {
                   11041:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   11042:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   11043:                     $max_match_pct = $percent_match;
                   11044:                     $max_match_format = $key;
1.710     bisitz   11045:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  11046:                     $max_match_count = $counts{$key}{'total'};
                   11047:                 }
                   11048:             }
                   11049:         }
1.770     raeburn  11050:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  11051:             my $format_descs;
                   11052:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   11053:             for (my $i=0; $i<$numwithformat; $i++) {
                   11054:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   11055:                 if ($i<$numwithformat-2) {
                   11056:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   11057:                 } elsif ($i==$numwithformat-2) {
                   11058:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   11059:                 } elsif ($i==$numwithformat-1) {
                   11060:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   11061:                 }
                   11062:             }
                   11063:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   11064:             $output .= '<br />';
                   11065:             if ($found_match_count == $max_match_count) {
                   11066:                 # 100% matching entries
                   11067:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   11068:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   11069:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   11070:                 &mt('Comparison of student IDs in the uploaded file with'.
                   11071:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   11072:                     ' in the file (for the format defined for [_3]).',
                   11073:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   11074:             } else {
                   11075:                 # Not all entries matching? -> Show warning and additional info
                   11076:                 $output .=
                   11077:                     &Apache::lonhtmlcommon::confirm_success(
                   11078:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   11079:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   11080:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   11081:                     &mt('Comparison of student IDs in the uploaded file with'.
                   11082:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   11083:                         ' in the file (for the format defined for [_3]).',
                   11084:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   11085:                     '<p class="LC_info">'.
                   11086:                     &mt('A low percentage of matches results from one of the following:').
                   11087:                     '</p><ul>'.
                   11088:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   11089:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   11090:                                '<i>'.$cdom.'</i>').'</li>'.
                   11091:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   11092:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   11093:                     '</ul>';
                   11094:             }
1.770     raeburn  11095:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11096:                 if ($counts{$max_match_format}{'othersec'}) {
                   11097:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   11098:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   11099:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   11100:                     &js_escape(\$confirmdel);
                   11101:                     $output .= '<p class="LC_warning">'.
                   11102:                                &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',
                   11103:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   11104:                                '<br />'.
                   11105:                                &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>').
                   11106:                                '</p><p>'.
                   11107:                                &mt('If you prefer to delete the file now, use: [_1]').
                   11108:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   11109:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   11110:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   11111:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   11112:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   11113:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   11114:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   11115:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   11116:                                '</form></p>';
                   11117:                 }
                   11118:             }
1.567     raeburn  11119:         }
1.770     raeburn  11120:         if (($context eq 'download') && ($checksec ne '')) {
                   11121:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11122:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   11123:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   11124:             }
                   11125:         } 
                   11126:     } elsif ($context ne 'download') {
1.710     bisitz   11127:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  11128:     }
                   11129:     return $output;
                   11130: }
                   11131: 
1.770     raeburn  11132: sub gradable_sections {
                   11133:     my $checksec = $env{'request.course.sec'};
                   11134:     my @oksecs;
                   11135:     if ($checksec) {
                   11136:         my %availablesecs = &sections_grade_privs();
                   11137:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   11138:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   11139:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   11140:                     push(@oksecs,$sec);
                   11141:                 }
                   11142:             }
                   11143:             if (grep(/^all$/,@oksecs)) {
                   11144:                 undef($checksec);
                   11145:             }
                   11146:         }
                   11147:     }
                   11148:     return($checksec,@oksecs);
                   11149: }
                   11150: 
                   11151: sub sections_grade_privs {
                   11152:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11153:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11154:     my %availablesecs = (
                   11155:                           mgr => [],
                   11156:                           vgr => [],
                   11157:                           usc => [],
                   11158:                         );
                   11159:     my $ccrole = 'cc';
                   11160:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   11161:         $ccrole = 'co';
                   11162:     }
                   11163:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   11164:                                                      'userroles',['active'],
                   11165:                                                      [$ccrole,'in','cr'],$cdom,1);
                   11166:     my $crsid = $cnum.':'.$cdom;
                   11167:     foreach my $item (keys(%crsroleshash)) {
                   11168:         next unless ($item =~ /^$crsid\:/);
                   11169:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   11170:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   11171:         if ($sec ne '') {
                   11172:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   11173:         }
                   11174:         if (($role eq $ccrole) || ($role eq 'in')) {
                   11175:             foreach my $priv ('mgr','vgr','usc') { 
                   11176:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11177:                     if ($sec eq '') {
                   11178:                         $availablesecs{$priv} = ['all'];
                   11179:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   11180:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11181:                             push(@{$availablesecs{$priv}},$sec);
                   11182:                         }
                   11183:                     }
                   11184:                 }
                   11185:             }
                   11186:         } elsif ($role =~ m{^cr/}) {
                   11187:             foreach my $priv ('mgr','vgr','usc') {
                   11188:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11189:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   11190:                         if ($sec eq '') {
                   11191:                             $availablesecs{$priv} = ['all'];
                   11192:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   11193:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11194:                                 push(@{$availablesecs{$priv}},$sec);
                   11195:                             }
                   11196:                         }
                   11197:                     }
                   11198:                 }
                   11199:             }
                   11200:         }
                   11201:     }
                   11202:     return %availablesecs;
                   11203: }
                   11204: 
                   11205: sub scantron_upload_delete {
                   11206:     my ($r,$symb) = @_;
                   11207:     my $filename = $env{'form.uploadedfile'};
                   11208:     if ($filename =~ /^scantron_orig_/) {
                   11209:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   11210:             &Apache::lonnet::allowed('usc',
                   11211:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   11212:             &Apache::lonnet::allowed('usc',
                   11213:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   11214:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   11215:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   11216:             if ($retrieval eq '-1') {
                   11217:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11218:                           &mt('File requested for deletion not found.'));
                   11219:             } else {
                   11220:                 $filename =~ s/^scantron_orig_//;
                   11221:                 if ($filename ne '') {
                   11222:                     my ($is_valid,$numleft);
                   11223:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11224:                     if (keys(%info)) {
                   11225:                         if (ref($info{$filename}) eq 'HASH') {
                   11226:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   11227:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11228:                                     $is_valid = 1;
                   11229:                                     delete($info{$filename}{$timestamp}); 
                   11230:                                 }
                   11231:                             }
                   11232:                             $numleft = scalar(keys(%{$info{$filename}}));
                   11233:                         }
                   11234:                     }
                   11235:                     if ($is_valid) {
                   11236:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   11237:                         if ($result eq 'ok') {
                   11238:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   11239:                             if ($numleft) {
                   11240:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   11241:                             } else {
                   11242:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11243:                             }
                   11244:                         } else {
                   11245:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11246:                                       &mt('Result was [_1]',$result));
                   11247:                         }
                   11248:                     } else {
                   11249:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11250:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   11251:                     }
                   11252:                 } else {
                   11253:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11254:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11255:                 }
                   11256:             }
                   11257:         } else {
                   11258:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   11259:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   11260:         }
                   11261:     } else {
                   11262:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11263:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11264:     }
                   11265:     return;
                   11266: }
                   11267: 
1.202     albertel 11268: sub valid_file {
                   11269:     my ($requested_file)=@_;
                   11270:     foreach my $filename (sort(&scantron_filenames())) {
                   11271: 	if ($requested_file eq $filename) { return 1; }
                   11272:     }
                   11273:     return 0;
                   11274: }
                   11275: 
                   11276: sub scantron_download_scantron_data {
1.767     raeburn  11277:     my ($r,$symb) = @_;
1.608     www      11278:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 11279:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   11280:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   11281:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 11282:     if (! &valid_file($file)) {
1.492     albertel 11283: 	$r->print('
1.202     albertel 11284: 	<p>
1.686     bisitz   11285: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 11286:         </p>
1.492     albertel 11287: ');
1.202     albertel 11288: 	return;
                   11289:     }
1.770     raeburn  11290:     my (%uploader,$is_owner,%counts,$percent);
                   11291:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   11292:     if (ref($uploader{$file}) eq 'HASH') {
                   11293:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   11294:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11295:                 $is_owner = 1;
                   11296:                 last;
                   11297:             }
                   11298:         }
                   11299:     }
                   11300:     unless ($is_owner) {
                   11301:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   11302:         if ($counts{'totalanysec'}) {
                   11303:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   11304:             if ($percent_othersec >= 10) {
                   11305:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   11306:                 $r->print('<p class="LC_warning">'.
                   11307:                           &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).
                   11308:                           '</p>');
                   11309:                 return;
                   11310:             }
                   11311:         }
                   11312:     }
1.202     albertel 11313:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   11314:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   11315:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   11316:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   11317:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   11318:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 11319:     $r->print('
1.202     albertel 11320:     <p>
1.723     raeburn  11321: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 11322: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 11323:     </p>
                   11324:     <p>
1.492     albertel 11325: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   11326: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 11327:     </p>
                   11328:     <p>
1.492     albertel 11329: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   11330: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 11331:     </p>
1.492     albertel 11332: ');
1.202     albertel 11333:     return '';
                   11334: }
1.157     albertel 11335: 
1.523     raeburn  11336: sub checkscantron_results {
1.608     www      11337:     my ($r,$symb) = @_;
1.523     raeburn  11338:     if (!$symb) {return '';}
                   11339:     my $cid = $env{'request.course.id'};
1.755     raeburn  11340:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  11341:     my $numletts = scalar(keys(%lettdig));
                   11342:     my $cnum = $env{'course.'.$cid.'.num'};
                   11343:     my $cdom = $env{'course.'.$cid.'.domain'};
                   11344:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   11345:     my %record;
                   11346:     my %scantron_config =
1.754     raeburn  11347:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  11348:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  11349:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  11350:     my $classlist=&Apache::loncoursedata::get_classlist();
                   11351:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   11352:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  11353:     unless (ref($navmap)) {
                   11354:         $r->print(&navmap_errormsg());
                   11355:         return '';
                   11356:     }
1.523     raeburn  11357:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  11358:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   11359:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  11360:     if (ref($map)) { 
                   11361:         $randomorder=$map->randomorder();
1.689     raeburn  11362:         $randompick=$map->randompick();
1.788     raeburn  11363:         unless ($randomorder || $randompick) {
                   11364:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   11365:                 if ($res->randomorder()) {
                   11366:                     $randomorder = 1;
                   11367:                 }
                   11368:                 if ($res->randompick()) {
                   11369:                     $randompick = 1;
                   11370:                 }
                   11371:                 last if ($randomorder || $randompick);
                   11372:             }
                   11373:         }
1.677     raeburn  11374:     }
1.557     raeburn  11375:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  11376:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   11377:     if ($nav_error) {
                   11378:         $r->print(&navmap_errormsg());
                   11379:         return '';
1.678     raeburn  11380:     }
1.673     raeburn  11381:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   11382:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  11383:     my ($uname,$udom);
1.523     raeburn  11384:     my (%scandata,%lastname,%bylast);
                   11385:     $r->print('
                   11386: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   11387: 
                   11388:     my @delayqueue;
                   11389:     my %completedstudents;
                   11390: 
1.691     raeburn  11391:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      11392:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  11393:     my ($username,$domain,$started);
1.649     raeburn  11394:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  11395:     if ($nav_error) {
                   11396:         $r->print(&navmap_errormsg());
                   11397:         return '';
                   11398:     }
1.523     raeburn  11399: 
1.667     www      11400:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  11401:     my $start=&Time::HiRes::time();
                   11402:     my $i=-1;
                   11403: 
                   11404:     while ($i<$scanlines->{'count'}) {
                   11405:         ($username,$domain,$uname)=('','','');
                   11406:         $i++;
                   11407:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   11408:         if ($line=~/^[\s\cz]*$/) { next; }
                   11409:         if ($started) {
1.667     www      11410:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  11411:         }
                   11412:         $started=1;
                   11413:         my $scan_record=
                   11414:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   11415:                                                      $scan_data);
1.693     raeburn  11416:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   11417:                                               \%idmap,$i)) {
1.523     raeburn  11418:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11419:                                 'Unable to find a student that matches',1);
                   11420:             next;
                   11421:         }
                   11422:         if (exists $completedstudents{$uname}) {
                   11423:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11424:                                 'Student '.$uname.' has multiple sheets',2);
                   11425:             next;
                   11426:         }
                   11427:         my $pid = $scan_record->{'scantron.ID'};
                   11428:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   11429:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  11430:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   11431:         my $user = $uname.':'.$usec;
1.523     raeburn  11432:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  11433: 
1.678     raeburn  11434:         my $scancode;
1.677     raeburn  11435:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   11436:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   11437:             $scancode = $scan_record->{'scantron.CODE'};
                   11438:         } else {
                   11439:             $scancode = '';
                   11440:         }
                   11441: 
                   11442:         my @mapresources = @resources;
1.691     raeburn  11443:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   11444:         my %respnumlookup=();
                   11445:         my %startline=();
1.689     raeburn  11446:         if ($randomorder || $randompick) {
1.678     raeburn  11447:             @mapresources =
1.691     raeburn  11448:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   11449:                              \%orderedforcode);
                   11450:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   11451:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   11452:                                              \%grader_partids_by_symb,\%orderedforcode,
                   11453:                                              \%respnumlookup,\%startline);
                   11454:             if ($randompick && $total) {
                   11455:                 $lastpos = $total*$scantron_config{'Qlength'};
                   11456:             }
1.677     raeburn  11457:         }
1.691     raeburn  11458:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   11459:         chomp($scandata{$pid});
                   11460:         $scandata{$pid} =~ s/\r$//;
                   11461: 
1.523     raeburn  11462:         my $counter = -1;
1.677     raeburn  11463:         foreach my $resource (@mapresources) {
1.557     raeburn  11464:             my $parts;
1.554     raeburn  11465:             my $ressymb = $resource->symb();
1.557     raeburn  11466:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   11467:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  11468:                 my $currcode;
                   11469:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   11470:                     $currcode = $scancode;
                   11471:                 }
1.557     raeburn  11472:                 (my $analysis,$parts) =
1.672     raeburn  11473:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   11474:                                               $username,$domain,undef,
1.741     raeburn  11475:                                               $bubbles_per_row,$currcode);
1.557     raeburn  11476:             } else {
                   11477:                 $parts = $grader_partids_by_symb{$ressymb};
                   11478:             }
1.542     raeburn  11479:             ($counter,my $recording) =
                   11480:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  11481:                                          $scandata{$pid},$parts,
1.691     raeburn  11482:                                          \%scantron_config,\%lettdig,$numletts,
                   11483:                                          $randomorder,$randompick,
                   11484:                                          \%respnumlookup,\%startline);
1.542     raeburn  11485:             $record{$pid} .= $recording;
1.523     raeburn  11486:         }
                   11487:     }
                   11488:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   11489:     $r->print('<br />');
                   11490:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   11491:     $passed = 0;
                   11492:     $failed = 0;
                   11493:     $numstudents = 0;
                   11494:     foreach my $last (sort(keys(%bylast))) {
                   11495:         if (ref($bylast{$last}) eq 'ARRAY') {
                   11496:             foreach my $pid (sort(@{$bylast{$last}})) {
                   11497:                 my $showscandata = $scandata{$pid};
                   11498:                 my $showrecord = $record{$pid};
                   11499:                 $showscandata =~ s/\s/&nbsp;/g;
                   11500:                 $showrecord =~ s/\s/&nbsp;/g;
                   11501:                 if ($scandata{$pid} eq $record{$pid}) {
                   11502:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   11503:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      11504: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  11505: '</tr>'."\n".
                   11506: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11507: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  11508:                     $passed ++;
                   11509:                 } else {
                   11510:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      11511:                     $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  11512: '</tr>'."\n".
                   11513: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11514: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  11515: '</tr>'."\n";
                   11516:                     $failed ++;
                   11517:                 }
                   11518:                 $numstudents ++;
                   11519:             }
                   11520:         }
                   11521:     }
1.648     bisitz   11522:     $r->print(
                   11523:         '<p>'
                   11524:        .&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).',
                   11525:             '<b>',
                   11526:             $numstudents,
                   11527:             '</b>',
                   11528:             $env{'form.scantron_maxbubble'})
                   11529:        .'</p>'
                   11530:     );
1.682     raeburn  11531:     $r->print('<p>'
1.683     raeburn  11532:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  11533:              .'<br />'
                   11534:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   11535:              .'</p>'
                   11536:     );
1.523     raeburn  11537:     if ($passed) {
1.572     www      11538:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11539:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11540:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11541:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11542:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11543:                  $okstudents."\n".
                   11544:                  &Apache::loncommon::end_data_table().'<br />');
                   11545:     }
                   11546:     if ($failed) {
1.572     www      11547:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11548:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11549:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11550:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11551:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11552:                  $badstudents."\n".
                   11553:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      11554:                  &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  11555:     }
1.614     www      11556:     $r->print('</form><br />');
1.523     raeburn  11557:     return;
                   11558: }
                   11559: 
1.542     raeburn  11560: sub verify_scantron_grading {
1.554     raeburn  11561:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  11562:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   11563:         $respnumlookup,$startline) = @_;
1.542     raeburn  11564:     my ($record,%expected,%startpos);
                   11565:     return ($counter,$record) if (!ref($resource));
                   11566:     return ($counter,$record) if (!$resource->is_problem());
                   11567:     my $symb = $resource->symb();
1.554     raeburn  11568:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   11569:     foreach my $part_id (@{$partids}) {
1.542     raeburn  11570:         $counter ++;
                   11571:         $expected{$part_id} = 0;
1.691     raeburn  11572:         my $respnum = $counter;
                   11573:         if ($randomorder || $randompick) {
                   11574:             $respnum = $respnumlookup->{$counter};
                   11575:             $startpos{$part_id} = $startline->{$counter} + 1;
                   11576:         } else {
                   11577:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   11578:         }
                   11579:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   11580:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  11581:             foreach my $item (@sub_lines) {
                   11582:                 $expected{$part_id} += $item;
                   11583:             }
                   11584:         } else {
1.691     raeburn  11585:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  11586:         }
                   11587:     }
                   11588:     if ($symb) {
                   11589:         my %recorded;
                   11590:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   11591:         if ($returnhash{'version'}) {
                   11592:             my %lasthash=();
                   11593:             my $version;
                   11594:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   11595:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   11596:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   11597:                 }
                   11598:             }
                   11599:             foreach my $key (keys(%lasthash)) {
                   11600:                 if ($key =~ /\.scantron$/) {
                   11601:                     my $value = &unescape($lasthash{$key});
                   11602:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   11603:                     if ($value eq '') {
                   11604:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11605:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   11606:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11607:                             }
                   11608:                         }
                   11609:                     } else {
                   11610:                         my @tocheck;
                   11611:                         my @items = split(//,$value);
                   11612:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   11613:                             ($scantron_config->{'Qon'} eq 'number')) {
                   11614:                             if (@items < $expected{$part_id}) {
                   11615:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   11616:                                 my @singles = split(//,$fragment);
                   11617:                                 foreach my $pos (@singles) {
                   11618:                                     if ($pos eq ' ') {
                   11619:                                         push(@tocheck,$pos);
                   11620:                                     } else {
                   11621:                                         my $next = shift(@items);
                   11622:                                         push(@tocheck,$next);
                   11623:                                     }
                   11624:                                 }
                   11625:                             } else {
                   11626:                                 @tocheck = @items;
                   11627:                             }
                   11628:                             foreach my $letter (@tocheck) {
                   11629:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   11630:                                     if ($letter !~ /^[A-J]$/) {
                   11631:                                         $letter = $scantron_config->{'Qoff'};
                   11632:                                     }
                   11633:                                     $recorded{$part_id} .= $letter;
                   11634:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   11635:                                     my $digit;
                   11636:                                     if ($letter !~ /^[A-J]$/) {
                   11637:                                         $digit = $scantron_config->{'Qoff'};
                   11638:                                     } else {
                   11639:                                         $digit = $lettdig->{$letter};
                   11640:                                     }
                   11641:                                     $recorded{$part_id} .= $digit;
                   11642:                                 }
                   11643:                             }
                   11644:                         } else {
                   11645:                             @tocheck = @items;
                   11646:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11647:                                 my $curr_sub = shift(@tocheck);
                   11648:                                 my $digit;
                   11649:                                 if ($curr_sub =~ /^[A-J]$/) {
                   11650:                                     $digit = $lettdig->{$curr_sub}-1;
                   11651:                                 }
                   11652:                                 if ($curr_sub eq 'J') {
                   11653:                                     $digit += scalar($numletts);
                   11654:                                 }
                   11655:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11656:                                     if ($j == $digit) {
                   11657:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   11658:                                     } else {
                   11659:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11660:                                     }
                   11661:                                 }
                   11662:                             }
                   11663:                         }
                   11664:                     }
                   11665:                 }
                   11666:             }
                   11667:         }
1.554     raeburn  11668:         foreach my $part_id (@{$partids}) {
1.542     raeburn  11669:             if ($recorded{$part_id} eq '') {
                   11670:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11671:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11672:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11673:                     }
                   11674:                 }
                   11675:             }
                   11676:             $record .= $recorded{$part_id};
                   11677:         }
                   11678:     }
                   11679:     return ($counter,$record);
                   11680: }
                   11681: 
1.75      albertel 11682: #-------- end of section for handling grading scantron forms -------
                   11683: #
                   11684: #-------------------------------------------------------------------
                   11685: 
1.72      ng       11686: #-------------------------- Menu interface -------------------------
                   11687: #
1.614     www      11688: #--- Href with symb and command ---
                   11689: 
                   11690: sub href_symb_cmd {
                   11691:     my ($symb,$cmd)=@_;
1.796     raeburn  11692:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.
                   11693:            &HTML::Entities::encode($cmd,'<>&"');
1.72      ng       11694: }
                   11695: 
1.443     banghart 11696: sub grading_menu {
1.608     www      11697:     my ($request,$symb) = @_;
1.443     banghart 11698:     if (!$symb) {return '';}
                   11699: 
                   11700:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      11701:                   'command'=>'individual');
1.538     schulted 11702:     
1.598     www      11703:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11704: 
                   11705:     $fields{'command'}='ungraded';
                   11706:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11707: 
                   11708:     $fields{'command'}='table';
                   11709:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11710: 
                   11711:     $fields{'command'}='all_for_one';
                   11712:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11713: 
1.621     www      11714:     $fields{'command'}='downloadfilesselect';
                   11715:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11716: 
1.443     banghart 11717:     $fields{'command'} = 'csvform';
1.538     schulted 11718:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11719:     
1.443     banghart 11720:     $fields{'command'} = 'processclicker';
1.538     schulted 11721:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11722:     
1.443     banghart 11723:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 11724:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      11725: 
                   11726:     $fields{'command'} = 'initialverifyreceipt';
                   11727:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  11728: 
                   11729:     my %permissions;
                   11730:     if ($perm{'mgr'}) {
                   11731:         $permissions{'either'} = 'F';
                   11732:         $permissions{'mgr'} = 'F';
                   11733:     }
                   11734:     if ($perm{'vgr'}) {
                   11735:         $permissions{'either'} = 'F';
                   11736:         $permissions{'vgr'} = 'F';
                   11737:     }
                   11738: 
1.598     www      11739:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 11740:             items =>[
1.598     www      11741:                         {	linktext => 'Select individual students to grade',
                   11742:                     		url => $url1a,
1.781     raeburn  11743:                     		permission => $permissions{'either'},
1.636     wenzelju 11744:                     		icon => 'grade_students.png',
1.598     www      11745:                     		linktitle => 'Grade current resource for a selection of students.'
                   11746:                         }, 
1.764     raeburn  11747:                         {       linktext => 'Grade ungraded submissions',
1.598     www      11748:                                 url => $url1b,
1.781     raeburn  11749:                                 permission => $permissions{'either'},
1.636     wenzelju 11750:                                 icon => 'ungrade_sub.png',
1.598     www      11751:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 11752:                         },
1.598     www      11753: 
                   11754:                         {       linktext => 'Grading table',
                   11755:                                 url => $url1c,
1.781     raeburn  11756:                                 permission => $permissions{'either'},
1.636     wenzelju 11757:                                 icon => 'grading_table.png',
1.598     www      11758:                                 linktitle => 'Grade current resource for all students.'
                   11759:                         },
1.615     www      11760:                         {       linktext => 'Grade page/folder for one student',
1.598     www      11761:                                 url => $url1d,
1.781     raeburn  11762:                                 permission => $permissions{'either'},
1.636     wenzelju 11763:                                 icon => 'grade_PageFolder.png',
1.598     www      11764:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      11765:                         },
                   11766:                         {       linktext => 'Download submissions',
                   11767:                                 url => $url1e,
1.781     raeburn  11768:                                 permission => $permissions{'either'},
1.636     wenzelju 11769:                                 icon => 'download_sub.png',
1.621     www      11770:                                 linktitle => 'Download all students submissions.'
1.598     www      11771:                         }]},
                   11772:                          { categorytitle=>'Automated Grading',
                   11773:                items =>[
                   11774: 
1.538     schulted 11775:                 	    {	linktext => 'Upload Scores',
                   11776:                     		url => $url2,
1.780     raeburn  11777:                     		permission => $permissions{'mgr'},
1.538     schulted 11778:                     		icon => 'uploadscores.png',
                   11779:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   11780:                 	    },
                   11781:                 	    {	linktext => 'Process Clicker',
                   11782:                     		url => $url3,
1.780     raeburn  11783:                     		permission => $permissions{'mgr'},
1.538     schulted 11784:                     		icon => 'addClickerInfoFile.png',
                   11785:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   11786:                 	    },
1.587     raeburn  11787:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 11788:                     		url => $url4,
1.780     raeburn  11789:                     		permission => $permissions{'mgr'},
1.636     wenzelju 11790:                     		icon => 'bubblesheet.png',
1.648     bisitz   11791:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      11792:                 	    },
1.616     www      11793:                             {   linktext => 'Verify Receipt Number',
1.602     www      11794:                                 url => $url5,
1.780     raeburn  11795:                                 permission => $permissions{'either'},
1.636     wenzelju 11796:                                 icon => 'receipt_number.png',
1.602     www      11797:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   11798:                             }
                   11799: 
1.538     schulted 11800:                     ]
                   11801:             });
1.796     raeburn  11802:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   11803:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   11804:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   11805:     if (keys(%passback)) {
                   11806:         $fields{'command'} = 'initialpassback';
                   11807:         my $url6 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11808:         push (@{$menu[1]{items}},
                   11809:                   { linktext => 'Passback of Scores',
                   11810:                     url => $url6,
                   11811:                     permission => $permissions{'either'},
                   11812:                     icon => 'passback.png',
                   11813:                     linktitle => 'Passback scores to launcher CMS for resources accessed via LTI-mediated deep-linking',
                   11814:                   });
                   11815:     }
1.443     banghart 11816:     # Create the menu
                   11817:     my $Str;
1.445     banghart 11818:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   11819:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      11820:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 11821: 
1.602     www      11822:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 11823:     return $Str;    
                   11824: }
                   11825: 
1.598     www      11826: sub ungraded {
                   11827:     my ($request)=@_;
                   11828:     &submit_options($request);
                   11829: }
                   11830: 
1.599     www      11831: sub submit_options_sequence {
1.608     www      11832:     my ($request,$symb) = @_;
1.599     www      11833:     if (!$symb) {return '';}
1.600     www      11834:     &commonJSfunctions($request);
                   11835:     my $result;
1.599     www      11836: 
1.600     www      11837:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11838:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      11839:     $result.=&selectfield(0).
1.601     www      11840:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      11841:             <div>
                   11842:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11843:             </div>
                   11844:         </div>
                   11845:   </form>';
                   11846:     return $result;
                   11847: }
                   11848: 
                   11849: sub submit_options_table {
1.608     www      11850:     my ($request,$symb) = @_;
1.600     www      11851:     if (!$symb) {return '';}
1.599     www      11852:     &commonJSfunctions($request);
1.746     raeburn  11853:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      11854:     my $result;
                   11855: 
                   11856:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11857:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      11858: 
1.745     raeburn  11859:     $result.=&selectfield(1,$is_tool).
1.601     www      11860:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      11861:             <div>
                   11862:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11863:             </div>
                   11864:         </div>
                   11865:   </form>';
                   11866:     return $result;
                   11867: }
1.443     banghart 11868: 
1.621     www      11869: sub submit_options_download {
                   11870:     my ($request,$symb) = @_;
                   11871:     if (!$symb) {return '';}
                   11872: 
1.773     raeburn  11873:     my $res_error;
                   11874:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   11875:         &response_type($symb,\$res_error);
                   11876:     if ($res_error) {
                   11877:         $request->print(&mt('An error occurred retrieving response types'));
                   11878:         return;
                   11879:     }
                   11880:     unless ($numessay) {
                   11881:         $request->print(&mt('No essayresponse items found'));
                   11882:         return;
                   11883:     }
                   11884:     my $table;
                   11885:     if (ref($partlist) eq 'ARRAY') {
                   11886:         if (scalar(@$partlist) > 1 ) {
                   11887:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   11888:         }
                   11889:     }
                   11890: 
1.746     raeburn  11891:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      11892:     &commonJSfunctions($request);
                   11893: 
                   11894:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  11895:                $table."\n".
                   11896:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      11897:     $result.='
                   11898: <h2>
1.750     raeburn  11899:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  11900: </h2>'.&selectfield(1,$is_tool).'
1.621     www      11901:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   11902:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11903:             </div>
                   11904:           </div>
1.600     www      11905: 
                   11906: 
1.621     www      11907:   </form>';
                   11908:     return $result;
                   11909: }
                   11910: 
1.443     banghart 11911: #--- Displays the submissions first page -------
                   11912: sub submit_options {
1.608     www      11913:     my ($request,$symb) = @_;
1.72      ng       11914:     if (!$symb) {return '';}
                   11915: 
1.746     raeburn  11916:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       11917:     &commonJSfunctions($request);
1.473     albertel 11918:     my $result;
1.533     bisitz   11919: 
1.72      ng       11920:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11921: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  11922:     $result.=&selectfield(1,$is_tool).'
1.601     www      11923:                 <input type="hidden" name="command" value="submission" /> 
                   11924: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11925:             </div>
                   11926:           </div>
                   11927:   </form>';
                   11928:     return $result;
                   11929: }
1.533     bisitz   11930: 
1.601     www      11931: sub selectfield {
1.745     raeburn  11932:    my ($full,$is_tool)=@_;
                   11933:    my %options;
                   11934:    if ($is_tool) {
                   11935:        %options =
                   11936:            (&transtatus_options,
                   11937:             'select_form_order' => ['yes','incorrect','all']);
                   11938:    } else {
                   11939:        %options = 
                   11940:            (&substatus_options,
                   11941:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   11942:    }
1.782     raeburn  11943: 
                   11944:   #
                   11945:   # PrepareClasslist() needs to be called to avoid getting a sections list
                   11946:   # for a different course from the @Sections global in lonstatistics.pm, 
                   11947:   # populated by an earlier request.
                   11948:   #
                   11949:    &Apache::lonstatistics::PrepareClasslist();
                   11950: 
1.601     www      11951:    my $result='<div class="LC_columnSection">
1.537     harmsja  11952:   
1.533     bisitz   11953:     <fieldset>
                   11954:       <legend>
                   11955:        '.&mt('Sections').'
                   11956:       </legend>
1.601     www      11957:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   11958:     </fieldset>
1.537     harmsja  11959:   
1.533     bisitz   11960:     <fieldset>
                   11961:       <legend>
                   11962:         '.&mt('Groups').'
                   11963:       </legend>
                   11964:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   11965:     </fieldset>
1.537     harmsja  11966:   
1.533     bisitz   11967:     <fieldset>
                   11968:       <legend>
                   11969:         '.&mt('Access Status').'
                   11970:       </legend>
1.601     www      11971:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   11972:     </fieldset>';
                   11973:     if ($full) {
1.745     raeburn  11974:         my $heading = &mt('Submission Status');
                   11975:         if ($is_tool) {
                   11976:             $heading = &mt('Transaction Status');
                   11977:         }
                   11978:         $result.='
1.533     bisitz   11979:     <fieldset>
                   11980:       <legend>
1.745     raeburn  11981:         '.$heading.'
1.601     www      11982:       </legend>'.
1.635     raeburn  11983:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      11984:    '</fieldset>';
                   11985:     }
                   11986:     $result.='</div><br />';
1.44      ng       11987:     return $result;
1.2       albertel 11988: }
                   11989: 
1.738     raeburn  11990: sub substatus_options {
                   11991:     return &Apache::lonlocal::texthash(
                   11992:                                       'yes'       => 'with submissions',
                   11993:                                       'queued'    => 'in grading queue',
                   11994:                                       'graded'    => 'with ungraded submissions',
                   11995:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  11996:                                       'all'       => 'with any status',
                   11997:                                       );
1.738     raeburn  11998: }
                   11999: 
1.745     raeburn  12000: sub transtatus_options {
                   12001:     return &Apache::lonlocal::texthash(
                   12002:                                        'yes'       => 'with score transactions',
                   12003:                                        'incorrect' => 'with less than full credit',
                   12004:                                        'all'       => 'with any status',
                   12005:                                       );
                   12006: }
                   12007: 
1.285     albertel 12008: sub reset_perm {
                   12009:     undef(%perm);
                   12010: }
                   12011: 
                   12012: sub init_perm {
                   12013:     &reset_perm();
1.770     raeburn  12014:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 12015: 
                   12016: 	my $scope = $env{'request.course.id'};
                   12017: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   12018: 
                   12019: 	    $scope .= '/'.$env{'request.course.sec'};
                   12020: 	    if ( $perm{$test_perm}=
                   12021: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   12022: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   12023: 	    } else {
                   12024: 		delete($perm{$test_perm});
                   12025: 	    }
1.285     albertel 12026: 	}
                   12027:     }
                   12028: }
                   12029: 
1.674     raeburn  12030: sub init_old_essays {
                   12031:     my ($symb,$apath,$adom,$aname) = @_;
                   12032:     if ($symb ne '') {
                   12033:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   12034:         if (keys(%essays) > 0) {
                   12035:             $old_essays{$symb} = \%essays;
                   12036:         }
                   12037:     }
                   12038:     return;
                   12039: }
                   12040: 
                   12041: sub reset_old_essays {
                   12042:     undef(%old_essays);
                   12043: }
                   12044: 
1.400     www      12045: sub gather_clicker_ids {
1.408     albertel 12046:     my %clicker_ids;
1.400     www      12047: 
                   12048:     my $classlist = &Apache::loncoursedata::get_classlist();
                   12049: 
                   12050:     # Set up a couple variables.
1.407     albertel 12051:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   12052:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      12053:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      12054: 
1.407     albertel 12055:     foreach my $student (keys(%$classlist)) {
1.438     www      12056:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 12057:         my $username = $classlist->{$student}->[$username_idx];
                   12058:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      12059:         my $clickers =
1.408     albertel 12060: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      12061:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      12062:             $id=~s/^[\#0]+//;
1.421     www      12063:             $id=~s/[\-\:]//g;
1.407     albertel 12064:             if (exists($clicker_ids{$id})) {
1.408     albertel 12065: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      12066:             } else {
1.408     albertel 12067: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      12068:             }
                   12069:         }
                   12070:     }
1.407     albertel 12071:     return %clicker_ids;
1.400     www      12072: }
                   12073: 
1.402     www      12074: sub gather_adv_clicker_ids {
1.408     albertel 12075:     my %clicker_ids;
1.402     www      12076:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   12077:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   12078:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 12079:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      12080:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   12081:             my ($puname,$pudom)=split(/\:/,$person);
                   12082:             my $clickers =
1.408     albertel 12083: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      12084:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      12085: 		$id=~s/^[\#0]+//;
1.421     www      12086:                 $id=~s/[\-\:]//g;
1.408     albertel 12087: 		if (exists($clicker_ids{$id})) {
                   12088: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   12089: 		} else {
                   12090: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   12091: 		}
1.405     www      12092:             }
1.402     www      12093:         }
                   12094:     }
1.407     albertel 12095:     return %clicker_ids;
1.402     www      12096: }
                   12097: 
1.413     www      12098: sub clicker_grading_parameters {
                   12099:     return ('gradingmechanism' => 'scalar',
                   12100:             'upfiletype' => 'scalar',
                   12101:             'specificid' => 'scalar',
                   12102:             'pcorrect' => 'scalar',
                   12103:             'pincorrect' => 'scalar');
                   12104: }
                   12105: 
1.400     www      12106: sub process_clicker {
1.608     www      12107:     my ($r,$symb)=@_;
1.400     www      12108:     if (!$symb) {return '';}
                   12109:     my $result=&checkforfile_js();
1.632     www      12110:     $result.=&Apache::loncommon::start_data_table().
                   12111:              &Apache::loncommon::start_data_table_header_row().
                   12112:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   12113:              &Apache::loncommon::end_data_table_header_row().
                   12114:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      12115: # Attempt to restore parameters from last session, set defaults if not present
                   12116:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12117:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   12118:                                                  \%Saveable_Parameters);
                   12119:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   12120:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   12121:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   12122:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   12123: 
                   12124:     my %checked;
1.521     www      12125:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      12126:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   12127:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      12128:        }
                   12129:     }
                   12130: 
1.632     www      12131:     my $upload=&mt("Evaluate File");
1.400     www      12132:     my $type=&mt("Type");
1.402     www      12133:     my $attendance=&mt("Award points just for participation");
                   12134:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      12135:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      12136:     my $given=&mt("Correctness determined from given list of answers").' '.
                   12137:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      12138:     my $pcorrect=&mt("Percentage points for correct solution");
                   12139:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      12140:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  12141: 						   {'iclicker' => 'i>clicker',
1.666     www      12142:                                                     'interwrite' => 'interwrite PRS',
                   12143:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 12144:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 12145:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      12146: function sanitycheck() {
                   12147: // Accept only integer percentages
                   12148:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   12149:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   12150: // Find out grading choice
                   12151:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12152:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   12153:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   12154:       }
                   12155:    }
                   12156: // By default, new choice equals user selection
                   12157:    newgradingchoice=gradingchoice;
                   12158: // Not good to give more points for false answers than correct ones
                   12159:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   12160:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   12161:    }
                   12162: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   12163:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   12164:       document.forms.gradesupload.pcorrect.value=100;
                   12165:       document.forms.gradesupload.pincorrect.value=100;
                   12166:    }
                   12167: // If the values are different, cannot be attendance only
                   12168:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   12169:        (gradingchoice=='attendance')) {
                   12170:        newgradingchoice='personnel';
                   12171:    }
                   12172: // Change grading choice to new one
                   12173:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12174:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   12175:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   12176:       } else {
                   12177:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   12178:       }
                   12179:    }
                   12180: // Remember the old state
                   12181:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   12182: }
1.597     wenzelju 12183: ENDUPFORM
                   12184:     $result.= <<ENDUPFORM;
1.400     www      12185: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   12186: <input type="hidden" name="symb" value="$symb" />
                   12187: <input type="hidden" name="command" value="processclickerfile" />
                   12188: <input type="file" name="upfile" size="50" />
                   12189: <br /><label>$type: $selectform</label>
1.632     www      12190: ENDUPFORM
                   12191:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   12192:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   12193:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   12194: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   12195: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      12196: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   12197: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      12198: <br />&nbsp;&nbsp;&nbsp;
                   12199: <input type="text" name="givenanswer" size="50" />
1.413     www      12200: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      12201: ENDGRADINGFORM
1.766     raeburn  12202:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      12203:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   12204:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   12205: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   12206: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  12207: </form>
1.632     www      12208: ENDPERCFORM
                   12209:     $result.='</td>'.
                   12210:              &Apache::loncommon::end_data_table_row().
                   12211:              &Apache::loncommon::end_data_table();
1.400     www      12212:     return $result;
                   12213: }
                   12214: 
                   12215: sub process_clicker_file {
1.766     raeburn  12216:     my ($r,$symb) = @_;
1.400     www      12217:     if (!$symb) {return '';}
1.413     www      12218: 
                   12219:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12220:     &Apache::loncommon::store_course_settings('grades_clicker',
                   12221:                                               \%Saveable_Parameters);
1.598     www      12222:     my $result='';
1.404     www      12223:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 12224: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      12225: 	return $result;
1.404     www      12226:     }
1.522     www      12227:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      12228:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      12229:         return $result;
1.521     www      12230:     }
1.522     www      12231:     my $foundgiven=0;
1.521     www      12232:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12233:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   12234:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      12235:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      12236:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      12237:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   12238:         $foundgiven=$#answers+1;
1.521     www      12239:     }
1.407     albertel 12240:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 12241:     my %correct_ids;
1.404     www      12242:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 12243: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      12244:     }
                   12245:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      12246: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   12247: 	   $correct_id=~tr/a-z/A-Z/;
                   12248: 	   $correct_id=~s/\s//gs;
                   12249: 	   $correct_id=~s/^[\#0]+//;
1.421     www      12250:            $correct_id=~s/[\-\:]//g;
1.414     www      12251:            if ($correct_id) {
                   12252: 	      $correct_ids{$correct_id}='specified';
                   12253:            }
                   12254:         }
1.400     www      12255:     }
1.404     www      12256:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 12257: 	$result.=&mt('Score based on attendance only');
1.521     www      12258:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      12259:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      12260:     } else {
1.408     albertel 12261: 	my $number=0;
1.411     www      12262: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 12263: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      12264: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 12265: 	    if ($correct_ids{$id} eq 'specified') {
                   12266: 		$result.=&mt('specified');
                   12267: 	    } else {
                   12268: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   12269: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   12270: 	    }
                   12271: 	    $number++;
                   12272: 	}
1.411     www      12273:         $result.="</p>\n";
1.710     bisitz   12274:         if ($number==0) {
                   12275:             $result .=
                   12276:                  &Apache::lonhtmlcommon::confirm_success(
                   12277:                      &mt('No IDs found to determine correct answer'),1);
                   12278:             return $result;
                   12279:         }
1.404     www      12280:     }
1.405     www      12281:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   12282:         $result .=
                   12283:             &Apache::lonhtmlcommon::confirm_success(
                   12284:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   12285:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      12286:         return $result;
1.405     www      12287:     }
1.760     raeburn  12288:     my $mimetype;
                   12289:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   12290:         my $mm = new File::MMagic;
                   12291:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   12292:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   12293:             $result.= '<p>'.
                   12294:                 &Apache::lonhtmlcommon::confirm_success(
                   12295:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   12296:             return $result;
                   12297:         }
                   12298:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   12299:         $result .= '<p>'.
                   12300:             &Apache::lonhtmlcommon::confirm_success(
                   12301:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   12302:         return $result;
                   12303:     }
1.410     www      12304: 
                   12305: # Were able to get all the info needed, now analyze the file
                   12306: 
1.411     www      12307:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 12308:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      12309:     $result.=&Apache::loncommon::start_data_table().
                   12310:              &Apache::loncommon::start_data_table_header_row().
                   12311:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   12312:              &Apache::loncommon::end_data_table_header_row().
                   12313:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   12314: <td>
1.410     www      12315: <form method="post" action="/adm/grades" name="clickeranalysis">
                   12316: <input type="hidden" name="symb" value="$symb" />
                   12317: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      12318: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   12319: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   12320: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      12321: ENDHEADER
1.522     www      12322:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12323:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   12324:     } 
1.408     albertel 12325:     my %responses;
                   12326:     my @questiontitles;
1.405     www      12327:     my $errormsg='';
                   12328:     my $number=0;
                   12329:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  12330:         if ($mimetype eq 'text/plain') {
                   12331:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   12332:         } elsif ($mimetype eq 'text/html') {
                   12333:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   12334:         }
                   12335:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      12336:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  12337:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      12338:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   12339:     }
1.411     www      12340:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   12341:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   12342:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   12343:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   12344:              '<br />';
1.522     www      12345:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   12346:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      12347:        return $result;
1.522     www      12348:     } 
1.414     www      12349: # Remember Question Titles
                   12350: # FIXME: Possibly need delimiter other than ":"
                   12351:     for (my $i=0;$i<$number;$i++) {
                   12352:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   12353:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   12354:     }
1.411     www      12355:     my $correct_count=0;
                   12356:     my $student_count=0;
                   12357:     my $unknown_count=0;
1.414     www      12358: # Match answers with usernames
                   12359: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 12360:     foreach my $id (keys(%responses)) {
1.410     www      12361:        if ($correct_ids{$id}) {
1.414     www      12362:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      12363:           $correct_count++;
1.410     www      12364:        } elsif ($clicker_ids{$id}) {
1.437     www      12365:           if ($clicker_ids{$id}=~/\,/) {
                   12366: # More than one user with the same clicker!
1.632     www      12367:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12368:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12369:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      12370:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12371:                            "<select name='multi".$id."'>";
                   12372:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   12373:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   12374:              }
                   12375:              $result.='</select>';
                   12376:              $unknown_count++;
                   12377:           } else {
                   12378: # Good: found one and only one user with the right clicker
                   12379:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   12380:              $student_count++;
                   12381:           }
1.410     www      12382:        } else {
1.632     www      12383:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12384:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12385:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      12386:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12387:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   12388:                    "\n".&mt("Domain").": ".
                   12389:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  12390:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      12391:           $unknown_count++;
1.410     www      12392:        }
1.405     www      12393:     }
1.412     www      12394:     $result.='<hr />'.
                   12395:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      12396:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      12397:        if ($correct_count==0) {
1.696     bisitz   12398:           $errormsg.="Found no correct answers for grading!";
1.412     www      12399:        } elsif ($correct_count>1) {
1.414     www      12400:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      12401:        }
                   12402:     }
1.428     www      12403:     if ($number<1) {
                   12404:        $errormsg.="Found no questions.";
                   12405:     }
1.412     www      12406:     if ($errormsg) {
                   12407:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   12408:     } else {
                   12409:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   12410:     }
1.632     www      12411:     $result.='</form></td>'.
                   12412:              &Apache::loncommon::end_data_table_row().
                   12413:              &Apache::loncommon::end_data_table();
1.614     www      12414:     return $result;
1.400     www      12415: }
                   12416: 
1.405     www      12417: sub iclicker_eval {
1.406     www      12418:     my ($questiontitles,$responses)=@_;
1.405     www      12419:     my $number=0;
                   12420:     my $errormsg='';
                   12421:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      12422:         my %components=&Apache::loncommon::record_sep($line);
                   12423:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 12424: 	if ($entries[0] eq 'Question') {
                   12425: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   12426: 		$$questiontitles[$number]=$entries[$i];
                   12427: 		$number++;
                   12428: 	    }
                   12429: 	}
                   12430: 	if ($entries[0]=~/^\#/) {
                   12431: 	    my $id=$entries[0];
                   12432: 	    my @idresponses;
                   12433: 	    $id=~s/^[\#0]+//;
                   12434: 	    for (my $i=0;$i<$number;$i++) {
                   12435: 		my $idx=3+$i*6;
1.644     www      12436:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 12437: 		push(@idresponses,$entries[$idx]);
                   12438: 	    }
                   12439: 	    $$responses{$id}=join(',',@idresponses);
                   12440: 	}
1.405     www      12441:     }
                   12442:     return ($errormsg,$number);
                   12443: }
                   12444: 
1.760     raeburn  12445: sub iclickerxml_eval {
                   12446:     my ($questiontitles,$responses)=@_;
                   12447:     my $number=0;
                   12448:     my $errormsg='';
                   12449:     my @state;
                   12450:     my %respbyid;
                   12451:     my $p = HTML::Parser->new
                   12452:     (
                   12453:         xml_mode => 1,
                   12454:         start_h =>
                   12455:             [sub {
                   12456:                  my ($tagname,$attr) = @_;
                   12457:                  push(@state,$tagname);
                   12458:                  if ("@state" eq "ssn p") {
                   12459:                      my $title = $attr->{qn};
                   12460:                      $title =~ s/(^\s+|\s+$)//g;
                   12461:                      $questiontitles->[$number]=$title;
                   12462:                  } elsif ("@state" eq "ssn p v") {
                   12463:                      my $id = $attr->{id};
                   12464:                      my $entry = $attr->{ans};
                   12465:                      $id=~s/^[\#0]+//;
                   12466:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   12467:                      $respbyid{$id}[$number] = $entry;
                   12468:                  }
                   12469:             }, "tagname, attr"],
                   12470:          end_h =>
                   12471:                [sub {
                   12472:                    my ($tagname) = @_;
                   12473:                    if ("@state" eq "ssn p") {
                   12474:                        $number++;
                   12475:                    }
                   12476:                    pop(@state);
                   12477:                 }, "tagname"],
                   12478:     );
                   12479: 
                   12480:     $p->parse($env{'form.upfile'});
                   12481:     $p->eof;
                   12482:     foreach my $id (keys(%respbyid)) {
                   12483:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   12484:     }
                   12485:     return ($errormsg,$number);
                   12486: }
                   12487: 
1.419     www      12488: sub interwrite_eval {
                   12489:     my ($questiontitles,$responses)=@_;
                   12490:     my $number=0;
                   12491:     my $errormsg='';
1.420     www      12492:     my $skipline=1;
                   12493:     my $questionnumber=0;
                   12494:     my %idresponses=();
1.419     www      12495:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12496:         my %components=&Apache::loncommon::record_sep($line);
                   12497:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      12498:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   12499:         if ($entries[1] eq 'Response') { $skipline=1; }
                   12500:         next if $skipline;
                   12501:         if ($entries[0]!=$questionnumber) {
                   12502:            $questionnumber=$entries[0];
                   12503:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   12504:            $number++;
1.419     www      12505:         }
1.420     www      12506:         my $id=$entries[4];
                   12507:         $id=~s/^[\#0]+//;
1.421     www      12508:         $id=~s/^v\d*\://i;
                   12509:         $id=~s/[\-\:]//g;
1.420     www      12510:         $idresponses{$id}[$number]=$entries[6];
                   12511:     }
1.524     raeburn  12512:     foreach my $id (keys(%idresponses)) {
1.420     www      12513:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   12514:        $$responses{$id}=~s/^\s*\,//;
1.419     www      12515:     }
                   12516:     return ($errormsg,$number);
                   12517: }
                   12518: 
1.666     www      12519: sub turning_eval {
                   12520:     my ($questiontitles,$responses)=@_;
                   12521:     my $number=0;
                   12522:     my $errormsg='';
                   12523:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12524:         my %components=&Apache::loncommon::record_sep($line);
                   12525:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   12526:         if ($#entries>$number) { $number=$#entries; }
                   12527:         my $id=$entries[0];
                   12528:         my @idresponses;
                   12529:         $id=~s/^[\#0]+//;
                   12530:         unless ($id) { next; }
                   12531:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   12532:             $entries[$idx]=~s/\,/\;/g;
                   12533:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   12534:             push(@idresponses,$entries[$idx]);
                   12535:         }
                   12536:         $$responses{$id}=join(',',@idresponses);
                   12537:     }
                   12538:     for (my $i=1; $i<=$number; $i++) {
                   12539:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   12540:     }
                   12541:     return ($errormsg,$number);
                   12542: }
                   12543: 
                   12544: 
1.414     www      12545: sub assign_clicker_grades {
1.766     raeburn  12546:     my ($r,$symb) = @_;
1.414     www      12547:     if (!$symb) {return '';}
1.416     www      12548: # See which part we are saving to
1.582     raeburn  12549:     my $res_error;
                   12550:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   12551:     if ($res_error) {
                   12552:         return &navmap_errormsg();
                   12553:     }
1.416     www      12554: # FIXME: This should probably look for the first handgradeable part
                   12555:     my $part=$$partlist[0];
                   12556: # Start screen output
1.766     raeburn  12557:     my $result = &Apache::loncommon::start_data_table().
                   12558:                  &Apache::loncommon::start_data_table_header_row().
                   12559:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   12560:                  &Apache::loncommon::end_data_table_header_row().
                   12561:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      12562: # Get correct result
                   12563: # FIXME: Possibly need delimiter other than ":"
                   12564:     my @correct=();
1.415     www      12565:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   12566:     my $number=$env{'form.number'};
                   12567:     if ($gradingmechanism ne 'attendance') {
1.414     www      12568:        foreach my $key (keys(%env)) {
                   12569:           if ($key=~/^form\.correct\:/) {
                   12570:              my @input=split(/\,/,$env{$key});
                   12571:              for (my $i=0;$i<=$#input;$i++) {
                   12572:                  if (($correct[$i]) && ($input[$i]) &&
                   12573:                      ($correct[$i] ne $input[$i])) {
                   12574:                     $result.='<br /><span class="LC_warning">'.
                   12575:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   12576:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      12577:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      12578:                     $correct[$i]=$input[$i];
                   12579:                  }
                   12580:              }
                   12581:           }
                   12582:        }
1.415     www      12583:        for (my $i=0;$i<$number;$i++) {
1.644     www      12584:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      12585:              $result.='<br /><span class="LC_error">'.
                   12586:                       &mt('No correct result given for question "[_1]"!',
                   12587:                           $env{'form.question:'.$i}).'</span>';
                   12588:           }
                   12589:        }
1.644     www      12590:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      12591:     }
                   12592: # Start grading
1.415     www      12593:     my $pcorrect=$env{'form.pcorrect'};
                   12594:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      12595:     my $storecount=0;
1.632     www      12596:     my %users=();
1.415     www      12597:     foreach my $key (keys(%env)) {
1.420     www      12598:        my $user='';
1.415     www      12599:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      12600:           $user=$1;
                   12601:        }
                   12602:        if ($key=~/^form\.unknown\:(.*)$/) {
                   12603:           my $id=$1;
                   12604:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   12605:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      12606:           } elsif ($env{'form.multi'.$id}) {
                   12607:              $user=$env{'form.multi'.$id};
1.420     www      12608:           }
                   12609:        }
1.632     www      12610:        if ($user) {
                   12611:           if ($users{$user}) {
                   12612:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   12613:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      12614:                       '</span><br />';
                   12615:           }
                   12616:           $users{$user}=1; 
1.415     www      12617:           my @answer=split(/\,/,$env{$key});
                   12618:           my $sum=0;
1.522     www      12619:           my $realnumber=$number;
1.415     www      12620:           for (my $i=0;$i<$number;$i++) {
1.576     www      12621:              if  ($correct[$i] eq '-') {
                   12622:                 $realnumber--;
1.766     raeburn  12623:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      12624:                 if ($gradingmechanism eq 'attendance') {
                   12625:                    $sum+=$pcorrect;
1.576     www      12626:                 } elsif ($correct[$i] eq '*') {
1.522     www      12627:                    $sum+=$pcorrect;
1.415     www      12628:                 } else {
1.644     www      12629: # We actually grade if correct or not
                   12630:                    my $increment=$pincorrect;
                   12631: # Special case: numerical answer "0"
                   12632:                    if ($correct[$i] eq '0') {
                   12633:                       if ($answer[$i]=~/^[0\.]+$/) {
                   12634:                          $increment=$pcorrect;
                   12635:                       }
                   12636: # General numerical answer, both evaluate to something non-zero
                   12637:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   12638:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   12639:                          $increment=$pcorrect;
                   12640:                       }
                   12641: # Must be just alphanumeric
                   12642:                    } elsif ($answer[$i] eq $correct[$i]) {
                   12643:                       $increment=$pcorrect;
1.415     www      12644:                    }
1.644     www      12645:                    $sum+=$increment;
1.415     www      12646:                 }
                   12647:              }
                   12648:           }
1.522     www      12649:           my $ave=$sum/(100*$realnumber);
1.416     www      12650: # Store
                   12651:           my ($username,$domain)=split(/\:/,$user);
                   12652:           my %grades=();
                   12653:           $grades{"resource.$part.solved"}='correct_by_override';
                   12654:           $grades{"resource.$part.awarded"}=$ave;
                   12655:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   12656:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   12657:                                                  $env{'request.course.id'},
                   12658:                                                  $domain,$username);
                   12659:           if ($returncode ne 'ok') {
                   12660:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   12661:           } else {
                   12662:              $storecount++;
1.798     raeburn  12663:              #FIXME Do passback for $user if required
1.416     www      12664:           }
1.415     www      12665:        }
                   12666:     }
                   12667: # We are done
1.549     hauer    12668:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      12669:              '</td>'.
                   12670:              &Apache::loncommon::end_data_table_row().
                   12671:              &Apache::loncommon::end_data_table();
1.614     www      12672:     return $result;
1.414     www      12673: }
                   12674: 
1.582     raeburn  12675: sub navmap_errormsg {
                   12676:     return '<div class="LC_error">'.
                   12677:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  12678:            &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  12679:            '</div>';
                   12680: }
1.607     droeschl 12681: 
1.609     www      12682: sub startpage {
1.777     raeburn  12683:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  12684:     my %args;
                   12685:     if ($onload) {
                   12686:          my %loaditems = (
                   12687:                         'onload' => $onload,
                   12688:                       );
                   12689:          $args{'add_entries'} = \%loaditems;
                   12690:     }
1.671     raeburn  12691:     if ($nomenu) {
1.754     raeburn  12692:         $args{'only_body'} = 1; 
1.777     raeburn  12693:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  12694:     } else {
1.785     raeburn  12695:         if ($env{'request.course.id'}) { 
                   12696:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   12697:         }
1.754     raeburn  12698:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  12699:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  12700:         if ($env{'request.course.id'}) {
                   12701:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   12702:         }
1.671     raeburn  12703:     }
1.613     www      12704:     unless ($nodisplayflag) {
1.773     raeburn  12705:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      12706:     }
1.607     droeschl 12707: }
1.582     raeburn  12708: 
1.622     www      12709: sub select_problem {
                   12710:     my ($r)=@_;
1.632     www      12711:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  12712:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      12713:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   12714:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   12715: }
                   12716: 
1.793     raeburn  12717: #----- display problem, answer, and submissions for a single student (no grading)
                   12718: 
                   12719: sub view_as_user {
                   12720:     my ($symb,$vuname,$vudom,$hasperm) = @_;
                   12721:     my $plainname = &Apache::loncommon::plainname($vuname,$vudom,'lastname');
                   12722:     my $displayname = &nameUserString('',$plainname,$vuname,$vudom);
                   12723:     my $output = &Apache::loncommon::get_student_view($symb,$vuname,$vudom,
                   12724:                                                       $env{'request.course.id'},
                   12725:                                                       undef,{'disable_submit' => 1}).
                   12726:                  "\n\n".
                   12727:                  '<div class="LC_grade_show_user">'.
                   12728:                  '<h2>'.$displayname.'</h2>'.
                   12729:                  "\n".
                   12730:                  &Apache::loncommon::track_student_link('View recent activity',
                   12731:                                                         $vuname,$vudom,'check').' '.
                   12732:                  "\n";
                   12733:     if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) ||
                   12734:         (($env{'request.course.sec'} ne '') &&
                   12735:          &Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
                   12736:         $output .= &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   12737:                                                $vuname,$vudom,$symb,'check');
                   12738:     }
                   12739:     $output .= "\n";
                   12740:     my $companswer = &Apache::loncommon::get_student_answers($symb,$vuname,$vudom,
                   12741:                                                              $env{'request.course.id'});
                   12742:     $companswer=~s|<form(.*?)>||g;
                   12743:     $companswer=~s|</form>||g;
                   12744:     $companswer=~s|name="submit"|name="would_have_been_submit"|g;
                   12745:     $output .= '<div class="LC_Box">'.
                   12746:                '<h3 class="LC_hcell">'.&mt('Correct answer for[_1]',$displayname).'</h3>'.
                   12747:                $companswer.
                   12748:                '</div>'."\n";
                   12749:     my $is_tool = ($symb =~ /ext\.tool$/);
                   12750:     my ($essayurl,%coursedesc_by_cid);
                   12751:     (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   12752:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$vudom,$vuname);
                   12753:     my $res_error;
                   12754:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   12755:         &response_type($symb,\$res_error);
                   12756:     my $fullname;
                   12757:     my $collabinfo;
                   12758:     if ($numessay) {
                   12759:         unless ($hasperm) {
                   12760:             &init_perm();
                   12761:         }
                   12762:         ($collabinfo,$fullname)=
                   12763:             &check_collaborators($symb,$vuname,$vudom,\%record,$handgrade,0);
                   12764:         unless ($hasperm) {
                   12765:             &reset_perm();
                   12766:         }
                   12767:     }
                   12768:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   12769:                     '" src="'.$Apache::lonnet::perlvar{'lonIconsURL'}.
                   12770:                     '/check.gif" height="16" border="0" />';
                   12771:     my ($lastsubonly,$partinfo) =
                   12772:         &show_last_submission($vuname,$vudom,$symb,$essayurl,$responseType,'datesub',
                   12773:                               '',$fullname,\%record,\%coursedesc_by_cid);
                   12774:     $output .= '<div class="LC_Box">'.
                   12775:                '<h3 class="LC_hcell">'.&mt('Submissions').'</h3>'."\n".$collabinfo."\n";
                   12776:     if (($numresp > $numessay) & !$is_tool) {
                   12777:         $output .='<p class="LC_info">'.
                   12778:                   &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon).
                   12779:                   "</p>\n";
                   12780:     }
                   12781:     $output .= $partinfo;
                   12782:     $output .= $lastsubonly;
                   12783:     $output .= &displaySubByDates($symb,\%record,$partlist,$responseType,$checkIcon,$vuname,$vudom);
                   12784:     $output .= '</div></div>'."\n";
                   12785:     return $output;
                   12786: }
                   12787: 
1.1       albertel 12788: sub handler {
1.41      ng       12789:     my $request=$_[0];
1.434     albertel 12790:     &reset_caches();
1.646     raeburn  12791:     if ($request->header_only) {
                   12792:         &Apache::loncommon::content_type($request,'text/html');
                   12793:         $request->send_http_header;
                   12794:         return OK;
                   12795:     }
                   12796:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   12797: 
1.664     raeburn  12798: # see what command we need to execute
                   12799: 
                   12800:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   12801:     my $command=$commands[0];
                   12802: 
1.646     raeburn  12803:     &init_perm();
                   12804:     if (!$env{'request.course.id'}) {
1.664     raeburn  12805:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   12806:                 ($command =~ /^scantronupload/)) {
                   12807:             # Not in a course.
                   12808:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   12809:             return HTTP_NOT_ACCEPTABLE;
                   12810:         }
1.646     raeburn  12811:     } elsif (!%perm) {
                   12812:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  12813:         return OK;
1.41      ng       12814:     }
1.646     raeburn  12815:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       12816:     $request->send_http_header;
1.646     raeburn  12817: 
1.160     albertel 12818:     if ($#commands > 0) {
                   12819: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   12820:     }
1.608     www      12821: 
1.801   ! raeburn  12822: # -------------------------------------- Flag and buffer for registered cleanup
        !          12823:     $registered_cleanup=0;
        !          12824:     undef(@Apache::grades::ltipassback);
        !          12825: 
1.608     www      12826: # see what the symb is
                   12827: 
                   12828:     my $symb=$env{'form.symb'};
                   12829:     unless ($symb) {
                   12830:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   12831:        $symb=&Apache::lonnet::symbread($url);
                   12832:     }
1.646     raeburn  12833:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      12834: 
1.513     foxr     12835:     $ssi_error = 0;
1.637     www      12836:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      12837: #
1.637     www      12838: # Not called from a resource, but inside a course
1.601     www      12839: #    
1.622     www      12840:         &startpage($request,undef,[],1,1);
                   12841:         &select_problem($request);
1.41      ng       12842:     } else {
1.104     albertel 12843: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  12844:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  12845:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   12846:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12847:                     &choose_task_version_form($symb,$env{'form.student'},
                   12848:                                               $env{'form.userdom'});
                   12849:             }
1.773     raeburn  12850:             my $divforres;
                   12851:             if ($env{'form.student'} eq '') {
                   12852:                 $js .= &part_selector_js();
                   12853:                 $onload = "toggleParts('gradesub');";
                   12854:             } else {
                   12855:                 $divforres = 1;
                   12856:             }
1.778     raeburn  12857:             my $head_extra = $js;
                   12858:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12859:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12860:                 if ($csslinks) {
                   12861:                     $head_extra .= "\n$csslinks";
                   12862:                 }
                   12863:             }
1.777     raeburn  12864:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   12865:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  12866:             if ($versionform) {
1.775     raeburn  12867:                 if ($divforres) {
                   12868:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   12869:                 }
1.671     raeburn  12870:                 $request->print($versionform);
                   12871:             }
1.773     raeburn  12872: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  12873:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   12874:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12875:                 &choose_task_version_form($symb,$env{'form.student'},
                   12876:                                           $env{'form.userdom'},
                   12877:                                           $env{'form.inhibitmenu'});
1.778     raeburn  12878:             my $head_extra = $js;
                   12879:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12880:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12881:                 if ($csslinks) {
                   12882:                     $head_extra .= "\n$csslinks";
                   12883:                 }
                   12884:             }
1.777     raeburn  12885:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   12886:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  12887:             if ($versionform) {
                   12888:                 $request->print($versionform);
                   12889:             }
                   12890:             $request->print('<br clear="all" />');
                   12891:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 12892: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      12893:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12894:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      12895: 	    &pickStudentPage($request,$symb);
1.103     albertel 12896: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  12897:             my $csslinks;
                   12898:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12899:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  12900:             }
1.615     www      12901:             &startpage($request,$symb,
                   12902:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12903:                                        {href=>'',text=>'Select student'},
1.777     raeburn  12904:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      12905: 	    &displayPage($request,$symb);
1.104     albertel 12906: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      12907:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12908:                                        {href=>'',text=>'Select student'},
                   12909:                                        {href=>'',text=>'Grade student'},
                   12910:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      12911: 	    &updateGradeByPage($request,$symb);
1.104     albertel 12912: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  12913:             my $csslinks;
                   12914:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12915:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12916:             }
1.619     www      12917:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  12918:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      12919: 	    &processGroup($request,$symb);
1.104     albertel 12920: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      12921:             &startpage($request,$symb);
                   12922: 	    $request->print(&grading_menu($request,$symb));
1.598     www      12923: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      12924:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      12925: 	    $request->print(&submit_options($request,$symb));
1.598     www      12926:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  12927:             my $js = &part_selector_js();
                   12928:             my $onload = "toggleParts('gradesub');";
                   12929:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   12930:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      12931:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      12932:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      12933:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      12934:             $request->print(&submit_options_table($request,$symb));
1.598     www      12935:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      12936:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      12937:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 12938: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      12939:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      12940: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 12941: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      12942:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   12943:                                        {href=>'',text=>'Store grades'}]);
1.608     www      12944: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 12945: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      12946:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   12947:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   12948:                                                                              text=>"Modify grades"},
                   12949:                                        {href=>'', text=>"Store grades"}]);
1.608     www      12950: 	    $request->print(&editgrades($request,$symb));
1.602     www      12951:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      12952:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      12953:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 12954: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      12955:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   12956:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      12957: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      12958:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      12959:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      12960:             $request->print(&process_clicker($request,$symb));
1.400     www      12961:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      12962:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   12963:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      12964:             $request->print(&process_clicker_file($request,$symb));
1.414     www      12965:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      12966:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   12967:                                        {href=>'', text=>'Process clicker file'},
                   12968:                                        {href=>'', text=>'Store grades'}]);
1.608     www      12969:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 12970: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      12971:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12972: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 12973: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      12974:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12975: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 12976: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      12977:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12978: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 12979: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 12980: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      12981:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12982: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       12983: 	    } else {
1.257     albertel 12984: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   12985: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       12986: 		} else {
1.257     albertel 12987: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       12988: 		}
1.627     www      12989:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12990: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       12991: 	    }
1.246     albertel 12992: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      12993:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12994: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 12995: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  12996:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   12997:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      12998: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 12999:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      13000:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13001:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 13002: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      13003:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13004: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 13005: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      13006:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13007: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 13008:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  13009:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  13010:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   13011:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      13012:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 13013:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  13014:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      13015:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13016:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  13017:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      13018:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13019:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  13020:         } elsif ($command eq 'scantronupload_delete' &&
                   13021:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   13022:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   13023:             &scantron_upload_delete($request,$symb);
1.523     raeburn  13024:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      13025:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      13026:             $request->print(&checkscantron_results($request,$symb));
                   13027:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  13028:             my $js = &part_selector_js();
                   13029:             my $onload = "toggleParts('gradingMenu');";
                   13030:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   13031:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      13032:             $request->print(&submit_options_download($request,$symb));
                   13033:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   13034:             &startpage($request,$symb,
                   13035:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  13036:     {href=>'', text=>'Download submitted files'}],
                   13037:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  13038:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      13039:             &submit_download_link($request,$symb);
1.796     raeburn  13040:         } elsif ($command eq 'initialpassback') {
                   13041:             &startpage($request,$symb,[{href=>'', text=>'Choose Launcher'}],undef,1);
                   13042:             $request->print(&initialpassback($request,$symb));
                   13043:         } elsif ($command eq 'passback') {
                   13044:             &startpage($request,$symb,
                   13045:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13046:                         {href=>'', text=>'Types of User'}],undef,1);
                   13047:             $request->print(&passback_filters($request,$symb));
                   13048:         } elsif ($command eq 'passbacknames') {
                   13049:             my $chosen;
                   13050:             if ($env{'form.passback'} ne '') {
                   13051:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13052:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13053:                 }
                   13054:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13055:             }
                   13056:             &startpage($request,$symb,
                   13057:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13058:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13059:                         {href=>'', text=>'Select Users'}],undef,1);
                   13060:             $request->print(&names_for_passback($request,$symb));
                   13061:         } elsif ($command eq 'passbackscores') {
                   13062:             my ($chosen,$stu_status);
                   13063:             if ($env{'form.passback'} ne '') {
                   13064:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13065:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13066:                 }
                   13067:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13068:             }
                   13069:             if ($env{'form.Status'}) {
                   13070:                 $stu_status = &HTML::Entities::encode($env{'form.Status'});
                   13071:             }
                   13072:             &startpage($request,$symb,
                   13073:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13074:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13075:                         {href=>&href_symb_cmd($symb,'passbacknames').'&amp;Status='.$stu_status.'&amp;passback='.$chosen, text=>'Select Users'},
                   13076:                         {href=>'', text=>'Execute Passback'}],undef,1);
                   13077:             $request->print(&do_passback($request,$symb));
1.106     albertel 13078: 	} elsif ($command) {
1.620     www      13079:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   13080: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 13081: 	}
1.2       albertel 13082:     }
1.513     foxr     13083:     if ($ssi_error) {
                   13084: 	&ssi_print_error($request);
                   13085:     }
1.671     raeburn  13086:     if ($env{'form.inhibitmenu'}) {
                   13087:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  13088:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  13089:         &Apache::lonquickgrades::endGradeScreen($request);
                   13090:     }
1.434     albertel 13091:     &reset_caches();
1.646     raeburn  13092:     return OK;
1.44      ng       13093: }
                   13094: 
1.1       albertel 13095: 1;
                   13096: 
1.13      albertel 13097: __END__;
1.531     jms      13098: 
                   13099: 
                   13100: =head1 NAME
                   13101: 
                   13102: Apache::grades
                   13103: 
                   13104: =head1 SYNOPSIS
                   13105: 
                   13106: Handles the viewing of grades.
                   13107: 
                   13108: This is part of the LearningOnline Network with CAPA project
                   13109: described at http://www.lon-capa.org.
                   13110: 
                   13111: =head1 OVERVIEW
                   13112: 
                   13113: Do an ssi with retries:
1.715     bisitz   13114: While I'd love to factor out this with the version in lonprintout,
1.531     jms      13115: 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
                   13116: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   13117: 
                   13118: At least the logic that drives this has been pulled out into loncommon.
                   13119: 
                   13120: 
                   13121: 
                   13122: ssi_with_retries - Does the server side include of a resource.
                   13123:                      if the ssi call returns an error we'll retry it up to
                   13124:                      the number of times requested by the caller.
1.715     bisitz   13125:                      If we still have a problem, no text is appended to the
1.531     jms      13126:                      output and we set some global variables.
                   13127:                      to indicate to the caller an SSI error occurred.  
                   13128:                      All of this is supposed to deal with the issues described
1.715     bisitz   13129:                      in LON-CAPA BZ 5631 see:
1.531     jms      13130:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   13131:                      by informing the user that this happened.
                   13132: 
                   13133: Parameters:
                   13134:   resource   - The resource to include.  This is passed directly, without
                   13135:                interpretation to lonnet::ssi.
                   13136:   form       - The form hash parameters that guide the interpretation of the resource
                   13137:                
                   13138:   retries    - Number of retries allowed before giving up completely.
                   13139: Returns:
                   13140:   On success, returns the rendered resource identified by the resource parameter.
                   13141: Side Effects:
                   13142:   The following global variables can be set:
                   13143:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   13144:                               It is up to the caller to initialize this to false
                   13145:                               if desired.
                   13146:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   13147:                               of the resource that could not be rendered by the ssi
                   13148:                               call.
                   13149:    ssi_error_message   - The error string fetched from the ssi response
                   13150:                               in the event of an error.
                   13151: 
                   13152: 
                   13153: =head1 HANDLER SUBROUTINE
                   13154: 
                   13155: ssi_with_retries()
                   13156: 
                   13157: =head1 SUBROUTINES
                   13158: 
                   13159: =over
                   13160: 
1.671     raeburn  13161: =head1 Routines to display previous version of a Task for a specific student
                   13162: 
                   13163: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   13164: can receive another opportunity. Access to tasks is slot-based. If a slot
                   13165: requires a proctor to check-in the student, a new version of the Task will
                   13166: be created when the student is checked in to the new opportunity.
                   13167: 
                   13168: If a particular student has tried two or more versions of a particular task,
                   13169: the submission screen provides a user with vgr privileges (e.g., a Course
                   13170: Coordinator) the ability to display a previous version worked on by the
                   13171: student.  By default, the current version is displayed. If a previous version
                   13172: has been selected for display, submission data are only shown that pertain
                   13173: to that particular version, and the interface to submit grades is not shown.
                   13174: 
                   13175: =over 4
                   13176: 
                   13177: =item show_previous_task_version()
                   13178: 
                   13179: Displays a specified version of a student's Task, as the student sees it.
                   13180: 
                   13181: Inputs: 2
                   13182:         request - request object
                   13183:         symb    - unique symb for current instance of resource
                   13184: 
                   13185: Output: None.
                   13186: 
                   13187: Side Effects: calls &show_problem() to print version of Task, with
                   13188:               version contained in form item: $env{'form.previousversion'}
                   13189: 
                   13190: =item choose_task_version_form()
                   13191: 
                   13192: Displays a web form used to select which version of a student's view of a
                   13193: Task should be displayed.  Either launches a pop-up window, or replaces
                   13194: content in existing pop-up, or replaces page in main window.
                   13195: 
                   13196: Inputs: 4
                   13197:         symb    - unique symb for current instance of resource
                   13198:         uname   - username of student
                   13199:         udom    - domain of student
                   13200:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13201:                   breadcrumbs etc., are displayed
                   13202: 
                   13203: Output: 4
                   13204:         current   - student's current version
                   13205:         displayed - student's version being displayed
                   13206:         result    - scalar containing HTML for web form used to switch to
                   13207:                     a different version (or a link to close window, if pop-up).
                   13208:         js        - javascript for processing selection in versions web form
                   13209: 
                   13210: Side Effects: None.
                   13211: 
                   13212: =item previous_display_javascript()
                   13213: 
                   13214: Inputs: 2
                   13215:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13216:                   breadcrumbs etc., are displayed.
                   13217:         current - student's current version number.
                   13218: 
                   13219: Output: 1
                   13220:         js      - javascript for processing selection in versions web form.
                   13221: 
                   13222: Side Effects: None.
                   13223: 
                   13224: =back
                   13225: 
                   13226: =head1 Routines to process bubblesheet data.
                   13227: 
                   13228: =over 4
                   13229: 
1.531     jms      13230: =item scantron_get_correction() : 
                   13231: 
                   13232:    Builds the interface screen to interact with the operator to fix a
                   13233:    specific error condition in a specific scanline
                   13234: 
                   13235:  Arguments:
                   13236:     $r           - Apache request object
                   13237:     $i           - number of the current scanline
                   13238:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  13239:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      13240:     $line        - full contents of the current scanline
                   13241:     $error       - error condition, valid values are
                   13242:                    'incorrectCODE', 'duplicateCODE',
                   13243:                    'doublebubble', 'missingbubble',
                   13244:                    'duplicateID', 'incorrectID'
                   13245:     $arg         - extra information needed
                   13246:        For errors:
                   13247:          - duplicateID   - paper number that this studentID was seen before on
                   13248:          - duplicateCODE - array ref of the paper numbers this CODE was
                   13249:                            seen on before
                   13250:          - incorrectCODE - current incorrect CODE 
                   13251:          - doublebubble  - array ref of the bubble lines that have double
                   13252:                            bubble errors
                   13253:          - missingbubble - array ref of the bubble lines that have missing
                   13254:                            bubble errors
                   13255: 
1.788     raeburn  13256:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   13257:    $randompick  - True if exam folder (or a sub-folder) has randompick set
1.691     raeburn  13258:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   13259:                      for current line to question number used for same question
                   13260:                      in "Master Seqence" (as seen by Course Coordinator).
                   13261:    $startline   - Reference to hash where key is question number (0 is first)
                   13262:                   and value is number of first bubble line for current student
                   13263:                   or code-based randompick and/or randomorder.
                   13264: 
                   13265: 
                   13266: 
1.531     jms      13267: =item  scantron_get_maxbubble() : 
                   13268: 
1.582     raeburn  13269:    Arguments:
                   13270:        $nav_error  - Reference to scalar which is a flag to indicate a
                   13271:                       failure to retrieve a navmap object.
                   13272:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   13273:        calling routine should trap the error condition and display the warning
                   13274:        found in &navmap_errormsg().
                   13275: 
1.649     raeburn  13276:        $scantron_config - Reference to bubblesheet format configuration hash.
                   13277: 
1.531     jms      13278:    Returns the maximum number of bubble lines that are expected to
                   13279:    occur. Does this by walking the selected sequence rendering the
                   13280:    resource and then checking &Apache::lonxml::get_problem_counter()
                   13281:    for what the current value of the problem counter is.
                   13282: 
                   13283:    Caches the results to $env{'form.scantron_maxbubble'},
                   13284:    $env{'form.scantron.bubble_lines.n'}, 
                   13285:    $env{'form.scantron.first_bubble_line.n'} and
                   13286:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  13287:    which are the total number of bubble lines, the number of bubble
1.531     jms      13288:    lines for response n and number of the first bubble line for response n,
                   13289:    and a comma separated list of numbers of bubble lines for sub-questions
                   13290:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   13291: 
                   13292: 
                   13293: =item  scantron_validate_missingbubbles() : 
                   13294: 
                   13295:    Validates all scanlines in the selected file to not have any
                   13296:     answers that don't have bubbles that have not been verified
                   13297:     to be bubble free.
                   13298: 
                   13299: =item  scantron_process_students() : 
                   13300: 
1.659     raeburn  13301:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      13302: 
                   13303:    The parsed scanline hash is added to %env 
                   13304: 
                   13305:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   13306:    foreach resource , with the form data of
                   13307: 
                   13308: 	'submitted'     =>'scantron' 
                   13309: 	'grade_target'  =>'grade',
                   13310: 	'grade_username'=> username of student
                   13311: 	'grade_domain'  => domain of student
                   13312: 	'grade_courseid'=> of course
                   13313: 	'grade_symb'    => symb of resource to grade
                   13314: 
                   13315:     This triggers a grading pass. The problem grading code takes care
                   13316:     of converting the bubbled letter information (now in %env) into a
                   13317:     valid submission.
                   13318: 
                   13319: =item  scantron_upload_scantron_data() :
                   13320: 
1.659     raeburn  13321:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      13322: 
                   13323: =item  scantron_upload_scantron_data_save() : 
                   13324: 
                   13325:    Adds a provided bubble information data file to the course if user
1.770     raeburn  13326:    has the correct privileges to do so.
                   13327: 
                   13328: = item scantron_upload_delete() :
                   13329: 
                   13330:    Deletes a previously uploaded bubble information data file, if user
                   13331:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      13332: 
                   13333: =item  valid_file() :
                   13334: 
                   13335:    Validates that the requested bubble data file exists in the course.
                   13336: 
                   13337: =item  scantron_download_scantron_data() : 
                   13338: 
                   13339:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  13340:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      13341:    course.
                   13342: 
                   13343: =item  scantron_validate_ID() : 
                   13344: 
                   13345:    Validates all scanlines in the selected file to not have any
1.556     weissno  13346:    invalid or underspecified student/employee IDs
1.531     jms      13347: 
1.582     raeburn  13348: =item navmap_errormsg() :
                   13349: 
                   13350:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  13351:    Should be called whenever the request to instantiate a navmap object fails.
                   13352: 
                   13353: =back
1.582     raeburn  13354: 
1.531     jms      13355: =back
                   13356: 
                   13357: =cut

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