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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.805   ! raeburn     4: # $Id: grades.pm,v 1.804 2024/12/10 18:38:10 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");
1.805   ! raeburn  1444:                                         my $key = &Time::HiRes::time().':'.$uname.':'.$udom.':'.
        !          1445:                                                   "$linkuri\0$linkprotector\0$scope"; 
1.796     raeburn  1446:                                         my $ltigrade = {
1.805   ! raeburn  1447:                                                          $key => {
        !          1448:                                                                    'ltinum'   => $ltinum,
        !          1449:                                                                    'lti'      => $lti_in_use,
        !          1450:                                                                    'crsdef'   => $crsdef,
        !          1451:                                                                    'cid'      => $cdom.'_'.$cnum,
        !          1452:                                                                    'uname'    => $uname,
        !          1453:                                                                    'udom'     => $udom,
        !          1454:                                                                    'uhome'    => $uhome,
        !          1455:                                                                    'pbid'     => $id,
        !          1456:                                                                    'pburl'    => $url,
        !          1457:                                                                    'pbtype'   => $pb{'type'},
        !          1458:                                                                    'pbscope'  => $pbscope,
        !          1459:                                                                    'pbmap'    => $pbmap,
        !          1460:                                                                    'pbsymb'   => $pbsymb,
        !          1461:                                                                    'format'   => $scoretype,
        !          1462:                                                                    'scope'    => $scope,
        !          1463:                                                                    'clientip' => $pb{'clientip'},
        !          1464:                                                                    'linkprot' => $linkprotector.':'.$linkuri,
        !          1465:                                                                    'total'    => $total,
        !          1466:                                                                    'possible' => $possible,
        !          1467:                                                                    'score'    => $score,
        !          1468:                                                                  },
1.796     raeburn  1469:                                         };
                   1470:                                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1471:                                     }
                   1472:                                 } else {
                   1473:                                     if (($id ne '') && ($url ne '')) {
                   1474:                                         $zeroposs{$student} = 1;
                   1475:                                     } else {
                   1476:                                         $nopbinfo{$student} = 1;
                   1477:                                     }
                   1478:                                 }
                   1479:                             }
                   1480:                             &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
                   1481:                             if ($ctr%2 ==1) {
                   1482:                                 $outcome .= &Apache::loncommon::end_data_table_row();
                   1483:                             }
                   1484:                             $outcome .= &Apache::loncommon::end_data_table();
                   1485:                             if ($ctr) {
                   1486:                                 $request->print('<p><br />'.&mt('Scores sent to launcher CMS').'</p>'.
                   1487:                                                 '<p>'.$outcome.'</p>');
                   1488:                             } else {
                   1489:                                 $request->print('<p>'.&mt('No scores sent to launcher CMS').'</p>');
                   1490:                             }
                   1491:                             if (keys(%tosend)) {
                   1492:                                 $request->print('<p>'.&mt('No scores sent for following'));
                   1493:                                 my ($zeros,$nopbcreds,$noconfirm,$noscore);
                   1494:                                 foreach my $student (sort
                   1495:                                 {
                   1496:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1497:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1498:                                      }
                   1499:                                      return $a cmp $b;
                   1500:                                 } (keys(%$fullname))) {
                   1501:                                     next unless ($tosend{$student});
                   1502:                                     my ($uname,$udom) = split(/:/,$student);
                   1503:                                     my $line = '<li>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).'</li>'."\n";
                   1504:                                     if ($zeroposs{$student}) {
                   1505:                                         $zeros .= $line;
                   1506:                                     } elsif ($nopbinfo{$student}) {
                   1507:                                         $nopbcreds .= $line;
                   1508:                                     } elsif ($remotenotok{$student}) {
                   1509:                                         $noconfirm .= $line;
                   1510:                                     } elsif ($scorenotok{$student}) {
                   1511:                                         $noscore .= $line;
                   1512:                                     }
                   1513:                                 }
                   1514:                                 if ($zeros) {
                   1515:                                     $request->print('<br />'.&mt('Total points possible was 0').':'.
                   1516:                                                     '<ul>'.$zeros.'</ul><br />');
                   1517:                                 }
                   1518:                                 if ($nopbcreds) {
                   1519:                                     $request->print('<br />'.&mt('Missing unique identifier and/or passback location').':'.
                   1520:                                                     '<ul>'.$nopbcreds.'</ul><br />');
                   1521:                                 }
                   1522:                                 if ($noconfirm) {
                   1523:                                     $request->print('<br />'.&mt('Score receipt not confirmed by receiving CMS').':'.
                   1524:                                                     '<ul>'.$noconfirm.'</ul><br />');
                   1525:                                 }
                   1526:                                 if ($noscore) {
                   1527:                                     $request->print('<br />'.&mt('Score computation or transmission failed').':'.
                   1528:                                                     '<ul>'.$noscore.'</ul><br />');
                   1529:                                 }
                   1530:                                 $request->print('</p>');
                   1531:                             }
                   1532:                         } else {
                   1533:                             $error = &mt('Settings for deep-link launch target unavailable, so no scores were sent');
                   1534:                         }
                   1535:                     } else {
                   1536:                         $error = &mt('No available students for whom scores can be sent.');
                   1537:                     }
                   1538:                 } else {
                   1539:                     $error = &mt('Classlist could not be retrieved so no scores were sent.');
                   1540:                 }
                   1541:             } else {
                   1542:                 $error = &mt('No students selected to receive scores so none were sent.');
                   1543:             }
                   1544:         } else {
                   1545:             if ($env{'form.passback'}) {
                   1546:                 $error = &mt('Deep-link launch target was invalid so no scores were sent.');
                   1547:             } else {
                   1548:                 $error = &mt('Deep-link launch target was missing so no scores were sent.');
                   1549:             }
                   1550:         }
                   1551:     } else {
                   1552:         $error = &mt('You do not have permission to manage grades, so no scores were sent');
                   1553:     }
                   1554:     if ($error) {
                   1555:         $request->print('<p class="LC_info">'.$error.'</p>');
                   1556:     }
                   1557:     return;
                   1558: }
                   1559: 
                   1560: sub get_passback_launcher {
                   1561:     my ($cdom,$cnum,$chosen) = @_;
                   1562:     my ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1563:     my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
                   1564:     my ($appname,$setter);
                   1565:     if ($ltitype eq 'c') {
                   1566:         my %lti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1567:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1568:             $appname = $lti{$ltinum}{'name'};
                   1569:             if ($appname) {
                   1570:                 $setter = ' (defined in course)';
                   1571:             }
                   1572:         }
                   1573:     } elsif ($ltitype eq 'd') {
                   1574:         my %lti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1575:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1576:             $appname = $lti{$ltinum}{'name'};
                   1577:             if ($appname) {
                   1578:                 $setter = ' (defined in domain)';
                   1579:             }
                   1580:         }
                   1581:     }
                   1582:     if ($linkuri =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   1583:         my $key = $1;
                   1584:         my $tinyurl;
                   1585:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   1586:         if (defined($cached)) {
                   1587:             $tinyurl = $result;
                   1588:         } else {
                   1589:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   1590:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   1591:             if ($currtiny{$key} ne '') {
                   1592:                 $tinyurl = $currtiny{$key};
                   1593:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   1594:             }
                   1595:         }
                   1596:         if ($tinyurl) {
                   1597:             my ($crsnum,$launchsymb) = split(/\&/,$tinyurl);
                   1598:             if ($crsnum eq $cnum) {
                   1599:                 my %passback = &Apache::lonnet::get('nohist_linkprot_passback',[$launchsymb],$cdom,$cnum);
                   1600:                 if (ref($passback{$launchsymb}) eq 'HASH') {
                   1601:                     if (exists($passback{$launchsymb}{$chosen})) {
1.798     raeburn  1602:                         return ($launchsymb,$appname,$setter);
1.796     raeburn  1603:                     }
                   1604:                 }
                   1605:             }
                   1606:         }
                   1607:     }
                   1608:     return ();
                   1609: }
                   1610: 
                   1611: sub sections_and_groups {
                   1612:     my (@sections,@groups,$group_display);
                   1613:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   1614:     if (grep(/^all$/,@groups)) {
                   1615:          @groups = ('all');
                   1616:          $group_display = 'all';
                   1617:     } elsif (grep(/^none$/,@groups)) {
                   1618:          @groups = ('none');
                   1619:          $group_display = 'none';
                   1620:     } elsif (@groups > 0) {
                   1621:          $group_display = join(', ',@groups);
                   1622:     }
                   1623:     if ($env{'request.course.sec'} ne '') {
                   1624:         @sections = ($env{'request.course.sec'});
                   1625:     } else {
                   1626:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1627:     }
                   1628:     my $disabled = ' disabled="disabled"';
                   1629:     if ($perm{'mgr'}) {
                   1630:         if (grep(/^all$/,@sections)) {
                   1631:             undef($disabled);
                   1632:         } else {
                   1633:             foreach my $sec (@sections) {
                   1634:                 if (&canmodify($sec)) {
                   1635:                     undef($disabled);
                   1636:                     last;
                   1637:                 }
                   1638:             }
                   1639:         }
                   1640:     }
                   1641:     if (grep(/^all$/,@sections)) {
                   1642:         @sections = ('all');
                   1643:     }
                   1644:     return(\@sections,\@groups,$group_display,$disabled);
                   1645: }
                   1646: 
                   1647: sub launcher_info_box {
                   1648:     my ($launcher,$appname,$setter,$linkuri,$scope) = @_;
                   1649:     my $shownscope;
                   1650:     if ($scope eq 'res') {
                   1651:         $shownscope = &mt('Resource');
                   1652:     } elsif ($scope eq 'map') {
                   1653:         $shownscope = &mt('Folder');
                   1654:     }  elsif ($scope eq 'rec') {
                   1655:         $shownscope = &mt('Folder + sub-folders');
                   1656:     }
                   1657:     return '<p>'.
                   1658:            &Apache::lonhtmlcommon::start_pick_box().
                   1659:            &Apache::lonhtmlcommon::row_title(&mt('Launch Item Title')).
1.797     raeburn  1660:            &Apache::lonnet::gettitle($launcher).
1.796     raeburn  1661:            &Apache::lonhtmlcommon::row_closure().
                   1662:            &Apache::lonhtmlcommon::row_title(&mt('Deep-link')).
                   1663:            $linkuri.
                   1664:            &Apache::lonhtmlcommon::row_closure().
                   1665:            &Apache::lonhtmlcommon::row_title(&mt('Launcher')).
                   1666:            $appname.' '.$setter.
                   1667:            &Apache::lonhtmlcommon::row_closure().
                   1668:            &Apache::lonhtmlcommon::row_title(&mt('Score Type')).
                   1669:            $shownscope.      
                   1670:            &Apache::lonhtmlcommon::row_closure(1).
                   1671:            &Apache::lonhtmlcommon::end_pick_box().'</p>'."\n";
                   1672: }
                   1673: 
1.798     raeburn  1674: sub passbacks_for_symb {
                   1675:     my ($cdom,$cnum,$symb) = @_;
                   1676:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   1677:     my %needpb;
                   1678:     if (keys(%passback)) {
                   1679:         my $checkpb = 1;
                   1680:         if (exists($passback{$symb})) {
                   1681:             if (keys(%passback) == 1) {
                   1682:                 undef($checkpb);
                   1683:             }
                   1684:             if (ref($passback{$symb}) eq 'HASH') {
                   1685:                 foreach my $launcher (keys(%{$passback{$symb}})) {
                   1686:                     $needpb{$launcher} = 1;
                   1687:                 }
                   1688:             }
                   1689:         }
                   1690:         if ($checkpb) {
                   1691:             my ($map,$id,$url) = &Apache::lonnet::decode_symb($symb);
                   1692:             my $navmap = Apache::lonnavmaps::navmap->new();
                   1693:             if (ref($navmap)) {
                   1694:                 my $mapres = $navmap->getResourceByUrl($map);
                   1695:                 if (ref($mapres)) {
                   1696:                     my $mapsymb = $mapres->symb();
                   1697:                     if (exists($passback{$mapsymb})) {
                   1698:                         if (keys(%passback) == 1) {
                   1699:                             undef($checkpb);
                   1700:                         }
                   1701:                         if (ref($passback{$mapsymb}) eq 'HASH') {
                   1702:                             foreach my $launcher (keys(%{$passback{$mapsymb}})) {
                   1703:                                 $needpb{$launcher} = 1;
                   1704:                             }
                   1705:                         }
                   1706:                     }
                   1707:                     my %posspb;
                   1708:                     if ($checkpb) {
                   1709:                         my @recurseup = $navmap->recurseup_maps($map,1);
                   1710:                         if (@recurseup) {
                   1711:                             map { $posspb{$_} = 1; } @recurseup;
                   1712:                         }
                   1713:                     }
                   1714:                     foreach my $key (keys(%passback)) {
                   1715:                         if (exists($posspb{$key})) {
                   1716:                             if (ref($passback{$key}) eq 'HASH') {
                   1717:                                 foreach my $launcher (keys(%{$passback{$key}})) {
                   1718:                                     my ($linkuri,$linkprotector,$scope) = split("\0",$launcher);
                   1719:                                     next unless ($scope eq 'rec');
                   1720:                                     $needpb{$launcher} = 1;
                   1721:                                 }
                   1722:                             }
                   1723:                         }
                   1724:                     }
                   1725:                 }
                   1726:             }
                   1727:         }
                   1728:     }
                   1729:     return %needpb;
                   1730: }
                   1731: 
                   1732: sub process_passbacks {
1.802     raeburn  1733:     my ($context,$symbs,$cdom,$cnum,$udom,$uname,$usec,$weights,$awardeds,$excuseds,$needpb,
1.798     raeburn  1734:         $skip_passback,$pbsave,$pbids) = @_;
                   1735:     if ((ref($needpb) eq 'HASH') && (ref($skip_passback) eq 'HASH') && (ref($pbsave) eq 'HASH')) {
                   1736:         my (%weight,%awarded,%excused);
                   1737:         if ((ref($symbs) eq 'ARRAY') && (ref($weights) eq 'HASH') && (ref($awardeds) eq 'HASH') &&
                   1738:             (ref($excuseds) eq 'HASH')) {
                   1739:             %weight = %{$weights};
                   1740:             %awarded = %{$awardeds};
                   1741:             %excused = %{$excuseds};
                   1742:         }
                   1743:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
                   1744:         my @launchers = keys(%{$needpb});
                   1745:         my %pbinfo;
                   1746:         if (ref($pbids) eq 'HASH') {
                   1747:             %pbinfo = %{$pbids};
                   1748:         } else {
                   1749:             %pbinfo = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@launchers,$udom,$uname);
                   1750:         }
                   1751:         my %pbc = &common_passback_info();
                   1752:         foreach my $launcher (@launchers) {
                   1753:             if (ref($pbinfo{$launcher}) eq 'ARRAY') {
                   1754:                 my $pbid = $pbinfo{$launcher}[0];
                   1755:                 my $pburl = $pbinfo{$launcher}[1];
                   1756:                 my (%total_by_symb,%possible_by_symb);
                   1757:                 if (($pbid ne '') && ($pburl ne '')) {
                   1758:                     next if ($skip_passback->{$launcher});
                   1759:                     my %pb = %pbc;
                   1760:                     if ((exists($pbsave->{$launcher})) &&
                   1761:                         (ref($pbsave->{$launcher}) eq 'HASH')) {
                   1762:                         foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
                   1763:                                           'symb','map','pbscope','linkuri','linkprotector','scope') {
                   1764:                             $pb{$item} = $pbsave->{$launcher}{$item};
                   1765:                         }
                   1766:                     } else {
                   1767:                         my $ltitype;
                   1768:                         ($pb{'linkuri'},$pb{'linkprotector'},$pb{'scope'}) = split("\0",$launcher);
                   1769:                         ($pb{'ltinum'},$ltitype) = ($pb{'linkprotector'} =~ /^(\d+)(c|d)$/);
                   1770:                         if ($ltitype eq 'c') {
                   1771:                             my %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1772:                             $pb{'lti_in_use'} = $crslti{$pb{'ltinum'}};
                   1773:                             $pb{'crsdef'} = 1;
                   1774:                         } else {
                   1775:                             my %domlti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1776:                             $pb{'lti_in_use'} = $domlti{$pb{'ltinum'}};
                   1777:                         }
                   1778:                         if (ref($pb{'lti_in_use'}) eq 'HASH') {
                   1779:                             $pb{'msgformat'} = $pb{'lti_in_use'}->{'passbackformat'};
                   1780:                             $pb{'keynum'} = $pb{'lti_in_use'}->{'cipher'};
                   1781:                             $pb{'scoretype'} = 'decimal';
                   1782:                             if ($pb{'lti_in_use'}->{'scoreformat'} =~ /^(decimal|ratio|percentage)$/) {
                   1783:                                 $pb{'scoretype'} = $1;
                   1784:                             }
                   1785:                             $pb{'symb'} = &Apache::loncommon::symb_from_tinyurl($pb{'linkuri'},$cnum,$cdom);
                   1786:                             if ($pb{'symb'} =~ /\.(page|sequence)$/) {
                   1787:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[2]);
                   1788:                             } else {
                   1789:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[0]);
                   1790:                             }
                   1791:                             $pb{'map'} = &Apache::lonnet::clutter($pb{'map'});
                   1792:                             if ($pb{'scope'} eq 'res') {
                   1793:                                 $pb{'pbscope'} = 'resource';
                   1794:                             } elsif ($pb{'scope'} eq 'map') {
                   1795:                                 $pb{'pbscope'} = 'nonrec';
                   1796:                             } elsif ($pb{'scope'} eq 'rec') {
                   1797:                                 $pb{'pbscope'} = 'map';
                   1798:                             }
                   1799:                             foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
                   1800:                                               'symb','map','pbscope','linkuri','linkprotector','scope') {
                   1801:                                 $pbsave->{$launcher}{$item} = $pb{$item};
                   1802:                             }
                   1803:                         } else {
                   1804:                             $skip_passback->{$launcher} = 1;
                   1805:                         }
                   1806:                     }
                   1807:                     if (ref($symbs) eq 'ARRAY') {
                   1808:                         foreach my $symb (@{$symbs}) {
                   1809:                             if ((ref($weight{$symb}) eq 'HASH') && (ref($awarded{$symb}) eq 'HASH') &&
                   1810:                                 (ref($excused{$symb}) eq 'HASH')) {
                   1811:                                 foreach my $part (keys(%{$weight{$symb}})) {
                   1812:                                     if ($excused{$symb}{$part}) {
                   1813:                                         next;
                   1814:                                     }
                   1815:                                     my $partweight = $weight{$symb}{$part} eq '' ? 1 :
                   1816:                                                      $weight{$symb}{$part};
                   1817:                                     if ($awarded{$symb}{$part}) {
                   1818:                                         $total_by_symb{$symb} += $partweight * $awarded{$symb}{$part};
                   1819:                                     }
                   1820:                                     $possible_by_symb{$symb} += $partweight;
                   1821:                                 }
                   1822:                             }
                   1823:                         }
                   1824:                     }
                   1825:                     if ($context eq 'updatebypage') {
                   1826:                         my $ltigrade = {
                   1827:                                         'ltinum'     => $pb{'ltinum'},
                   1828:                                         'lti'        => $pb{'lti_in_use'},
                   1829:                                         'crsdef'     => $pb{'crsdef'},
                   1830:                                         'cid'        => $cdom.'_'.$cnum,
                   1831:                                         'uname'      => $uname,
                   1832:                                         'udom'       => $udom,
                   1833:                                         'uhome'      => $uhome,
1.802     raeburn  1834:                                         'usec'       => $usec,
1.798     raeburn  1835:                                         'pbid'       => $pbid,
                   1836:                                         'pburl'      => $pburl,
                   1837:                                         'pbtype'     => $pb{'type'},
                   1838:                                         'pbscope'    => $pb{'pbscope'},
                   1839:                                         'pbmap'      => $pb{'map'},
                   1840:                                         'pbsymb'     => $pb{'symb'},
                   1841:                                         'format'     => $pb{'scoretype'},
                   1842:                                         'scope'      => $pb{'scope'},
                   1843:                                         'clientip'   => $pb{'clientip'},
1.799     raeburn  1844:                                         'linkprot'   => $pb{'linkprotector'}.':'.$pb{'linkuri'},
1.798     raeburn  1845:                                         'total_s'    => \%total_by_symb,
                   1846:                                         'possible_s' => \%possible_by_symb,
                   1847:                         };
1.801     raeburn  1848:                         push(@Apache::grades::ltipassback,$ltigrade);
1.798     raeburn  1849:                         next;
                   1850:                     }
                   1851:                     my ($total,$possible);
                   1852:                     if ($pb{'pbscope'} eq 'resource') {
                   1853:                         $total = $total_by_symb{$pb{'symb'}};
                   1854:                         $possible = $possible_by_symb{$pb{'symb'}};
                   1855:                     } elsif (($pb{'pbscope'} eq 'map') || ($pb{'pbscope'} eq 'nonrec')) {
                   1856:                         ($total,$possible) =
                   1857:                             &Apache::lonhomework::get_lti_score($uname,$udom,$pb{'map'},$pb{'pbscope'},
                   1858:                                                                 \%total_by_symb,\%possible_by_symb);
                   1859:                     }
                   1860:                     if (!$possible) {
                   1861:                         $total = 0;
                   1862:                         $possible = 1;
                   1863:                     }
                   1864:                     my ($sent,$score,$code,$result) =
                   1865:                         &LONCAPA::ltiutils::send_grade($cdom,$cnum,$pb{'crsdef'},$pb{'type'},$pb{'ltinum'},
                   1866:                                                        $pb{'keynum'},$pbid,$pburl,$pb{'scoretype'},$pb{'sigmethod'},
                   1867:                                                        $pb{'msgformat'},$total,$possible);
                   1868:                     my $no_passback;
                   1869:                     if ($sent) {
                   1870:                         if ($code == 200) {
                   1871:                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
                   1872:                             my $store = {
                   1873:                                 'score' => $score,
                   1874:                                 'ip' => $pb{'ip'},
                   1875:                                 'host' => $pb{'lonhost'},
                   1876:                                 'protector' => $pb{'linkprotector'},
                   1877:                                 'deeplink' => $pb{'linkuri'},
                   1878:                                 'scope' => $pb{'scope'},
                   1879:                                 'url' => $pburl,
                   1880:                                 'id' => $pbid,
                   1881:                                 'clientip' => $pb{'clientip'},
                   1882:                                 'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
                   1883:                             };
                   1884:                             my $value='';
                   1885:                             foreach my $key (keys(%{$store})) {
                   1886:                                  $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
                   1887:                             }
                   1888:                             $value=~s/\&$//;
                   1889:                             &Apache::lonnet::courselog(&escape($pb{'linkuri'}).':'.$uname.':'.$udom.':EXPORT:'.$value);
                   1890:                             &Apache::lonnet::cstore({'score' => $score},$launcher,$namespace,$udom,$uname,'',$pb{'ip'},1);
                   1891:                         } else {
                   1892:                             $no_passback = 1;
                   1893:                         }
                   1894:                     } else {
                   1895:                         $no_passback = 1;
                   1896:                     }
                   1897:                     if ($no_passback) {
                   1898:                         &Apache::lonnet::log($udom,$uname,$uhome,$no_passback." score: $score; total: $total; possible: $possible");
                   1899:                         my $ltigrade = {
                   1900:                            'ltinum'   => $pb{'ltinum'},
                   1901:                            'lti'      => $pb{'lti_in_use'},
                   1902:                            'crsdef'   => $pb{'crsdef'},
                   1903:                            'cid'      => $cdom.'_'.$cnum,
                   1904:                            'uname'    => $uname,
                   1905:                            'udom'     => $udom,
                   1906:                            'uhome'    => $uhome,
                   1907:                            'pbid'     => $pbid,
                   1908:                            'pburl'    => $pburl,
                   1909:                            'pbtype'   => $pb{'type'},
                   1910:                            'pbscope'  => $pb{'pbscope'},
                   1911:                            'pbmap'    => $pb{'map'},
                   1912:                            'pbsymb'   => $pb{'symb'},
                   1913:                            'format'   => $pb{'scoretype'},
                   1914:                            'scope'    => $pb{'scope'},
                   1915:                            'clientip' => $pb{'clientip'},
1.799     raeburn  1916:                            'linkprot' => $pb{'linkprotector'}.':'.$pb{'linkuri'},
1.798     raeburn  1917:                            'total'    => $total,
                   1918:                            'possible' => $possible,
                   1919:                            'score'    => $score,
                   1920:                         };
                   1921:                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1922:                     }
                   1923:                 }
                   1924:             }
                   1925:         }
                   1926:     }
                   1927:     return;
                   1928: }
                   1929: 
                   1930: sub common_passback_info {
                   1931:     my %pbc = (
                   1932:                sigmethod => 'HMAC-SHA1',
                   1933:                type      => 'linkprot',
                   1934:                clientip  => &Apache::lonnet::get_requestor_ip(),
                   1935:                lonhost   => $Apache::lonnet::perlvar{'lonHostID'},
                   1936:                ip        => &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}),
                   1937:              );
                   1938:     return %pbc;
                   1939: }
                   1940: 
1.44      ng       1941: #--- This is called by a number of programs.
                   1942: #--- Called from the Grading Menu - View/Grade an individual student
                   1943: #--- Also called directly when one clicks on the subm button 
                   1944: #    on the problem page.
1.30      ng       1945: sub listStudents {
1.773     raeburn  1946:     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1947: 
1.747     raeburn  1948:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1949:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1950:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1951:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1952:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www      1953:     unless ($submitonly) {
1.766     raeburn  1954:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www      1955:     }
1.49      albertel 1956: 
1.632     www      1957:     my $result='';
1.623     www      1958:     my $res_error;
1.773     raeburn  1959:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   1960: 
                   1961:     my $table;
                   1962:     if (ref($partlist) eq 'ARRAY') {
                   1963:         if (scalar(@$partlist) > 1 ) {
                   1964:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1965:         } elsif ($divforres) {
                   1966:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1967:         } else {
                   1968:             $table = '<br clear="all" />';
                   1969:         }
                   1970:     }
1.49      albertel 1971: 
1.796     raeburn  1972:     $request->print(&checkselect_js());
1.597     wenzelju 1973:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1974: 
                   1975:     function reLoadList(formname) {
1.112     ng       1976: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1977: 	formname.command.value = 'submission';
                   1978: 	formname.submit();
                   1979:     }
1.45      ng       1980: LISTJAVASCRIPT
                   1981: 
1.118     ng       1982:     &commonJSfunctions($request);
1.41      ng       1983:     $request->print($result);
1.39      ng       1984: 
1.154     albertel 1985:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.773     raeburn  1986: 	"\n".$table;
                   1987: 
1.561     bisitz   1988:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn  1989:     unless ($is_tool) {
                   1990:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1991:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1992:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1993:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1994:                       .&Apache::lonhtmlcommon::row_closure();
                   1995:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1996:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1997:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1998:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1999:                       .&Apache::lonhtmlcommon::row_closure();
                   2000:     }
1.485     albertel 2001: 
1.442     banghart 2002:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   2003:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 2004:     $env{'form.Status'} = $saveStatus;
1.745     raeburn  2005:     my %optiontext;
                   2006:     if ($is_tool) {
                   2007:         %optiontext = &Apache::lonlocal::texthash (
                   2008:                           lastonly => 'last transaction',
                   2009:                           last     => 'last transaction with details',
                   2010:                           datesub  => 'all transactions',
                   2011:                           all      => 'all transactions with details',
                   2012:                       );
                   2013:     } else {
                   2014:         %optiontext = &Apache::lonlocal::texthash (
                   2015:                           lastonly => 'last submission',
                   2016:                           last     => 'last submission with details',
                   2017:                           datesub  => 'all submissions',
                   2018:                           all      => 'all submissions with details',
                   2019:                       );
                   2020:     }
1.773     raeburn  2021:     my $submission_options =
1.592     bisitz   2022:         '<span class="LC_nobreak">'.
1.624     www      2023:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  2024:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   2025:         '<span class="LC_nobreak">'.
                   2026:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  2027:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   2028:         '<span class="LC_nobreak">'.
1.628     www      2029:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  2030:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   2031:         '<span class="LC_nobreak">'.
                   2032:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  2033:         $optiontext{'all'}.'</label></span>';
                   2034:     my $viewtitle;
                   2035:     if ($is_tool) {
                   2036:         $viewtitle = &mt('View Transactions');
                   2037:     } else {
                   2038:         $viewtitle = &mt('View Submissions');
                   2039:     }
1.773     raeburn  2040:     my ($compmsg,$nocompmsg);
                   2041:     $nocompmsg = ' checked="checked"';
                   2042:     if ($numessay) {
                   2043:         $compmsg = $nocompmsg;
                   2044:         $nocompmsg = '';
                   2045:     }
1.745     raeburn  2046:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.780     raeburn  2047:                   .$submission_options;
                   2048: # Check if any gradable
                   2049:     my $showmore;
                   2050:     if ($perm{'mgr'}) {
                   2051:         my @sections;
                   2052:         if ($env{'request.course.sec'} ne '') {
                   2053:             @sections = ($env{'request.course.sec'});
1.783     raeburn  2054:         } elsif ($env{'form.section'} eq '') {
                   2055:             @sections = ('all');
1.780     raeburn  2056:         } else {
                   2057:             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   2058:         }
                   2059:         if (grep(/^all$/,@sections)) {
                   2060:             $showmore = 1;
                   2061:         } else {
                   2062:             foreach my $sec (@sections) {
                   2063:                 if (&canmodify($sec)) {
                   2064:                     $showmore = 1;
                   2065:                     last;
                   2066:                 }
                   2067:             }
                   2068:         }
                   2069:     }
                   2070: 
                   2071:     if ($showmore) {
                   2072:         $gradeTable .=
                   2073:                    &Apache::lonhtmlcommon::row_closure()
1.773     raeburn  2074:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   2075:                   .'<span class="LC_nobreak">'
                   2076:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   2077:                   .&mt('No').('&nbsp;'x2).'</label>'
                   2078:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   2079:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   2080:                   .&Apache::lonhtmlcommon::row_closure();
                   2081: 
1.780     raeburn  2082:         $gradeTable .= 
                   2083:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   2084:                   .'<select name="increment">'
                   2085:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   2086:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   2087:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   2088:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773     raeburn  2089:                   .'</select>';
1.780     raeburn  2090:     }
1.485     albertel 2091:     $gradeTable .= 
1.432     banghart 2092:         &build_section_inputs().
1.45      ng       2093: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 2094: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       2095: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      2096:     if (exists($env{'form.Status'})) {
1.784     raeburn  2097: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng       2098:     } else {
1.773     raeburn  2099:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2100:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   2101:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773     raeburn  2102:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       2103:     }
1.773     raeburn  2104:     if ($numessay) {
                   2105:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2106:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   2107:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  2108:     }
1.773     raeburn  2109:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
                   2110:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  2111:     my $regrademsg;
                   2112:     if ($is_tool) {
                   2113:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
                   2114:     } else {
                   2115:         $regrademsg = &mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.");
                   2116:     }
1.561     bisitz   2117:     $gradeTable .= '<p>'
1.745     raeburn  2118:                   .$regrademsg."\n"
1.561     bisitz   2119:                   .'<input type="hidden" name="command" value="processGroup" />'
                   2120:                   .'</p>';
1.249     albertel 2121: 
                   2122: # checkall buttons
                   2123:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       2124:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   2125:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   2126:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 2127:     $gradeTable.=&check_buttons();
1.450     banghart 2128:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 2129:     $gradeTable.= &Apache::loncommon::start_data_table().
                   2130: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       2131:     my $loop = 0;
                   2132:     while ($loop < 2) {
1.485     albertel 2133: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   2134: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      2135: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 2136: 	    foreach my $part (sort(@$partlist)) {
                   2137: 		my $display_part=
                   2138: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   2139: 		$gradeTable.=
                   2140: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       2141: 	    }
1.301     albertel 2142: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 2143: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       2144: 	}
                   2145: 	$loop++;
1.126     ng       2146: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       2147:     }
1.474     albertel 2148:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       2149: 
1.45      ng       2150:     my $ctr = 0;
1.294     albertel 2151:     foreach my $student (sort 
                   2152: 			 {
                   2153: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2154: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2155: 			     }
                   2156: 			     return $a cmp $b;
                   2157: 			 }
                   2158: 			 (keys(%$fullname))) {
1.41      ng       2159: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2160: 
1.110     ng       2161: 	my %status = ();
1.301     albertel 2162: 
                   2163: 	if ($submitonly eq 'queued') {
                   2164: 	    my %queue_status = 
                   2165: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2166: 							$udom,$uname);
                   2167: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2168: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   2169: 	}
                   2170: 
1.618     www      2171: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 2172: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2173: 	    my $submitted = 0;
1.164     albertel 2174: 	    my $graded = 0;
1.248     albertel 2175: 	    my $incorrect = 0;
1.110     ng       2176: 	    foreach (keys(%status)) {
1.145     albertel 2177: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2178: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   2179: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   2180: 		
1.110     ng       2181: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2182: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 2183: 		    $submitted = 0;
1.150     albertel 2184: 		    my ($part)=split(/\./,$partid);
1.110     ng       2185: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 2186: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       2187: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   2188: 		}
1.41      ng       2189: 	    }
1.248     albertel 2190: 	    
1.156     albertel 2191: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2192: 				     $submitonly eq 'incorrect' ||
                   2193: 				     $submitonly eq 'graded'));
1.248     albertel 2194: 	    next if (!$graded && ($submitonly eq 'graded'));
                   2195: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2196: 	}
1.34      ng       2197: 
1.45      ng       2198: 	$ctr++;
1.249     albertel 2199: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 2200:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 2201: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 2202: 	    if ($ctr%2 ==1) {
                   2203: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   2204: 	    }
1.126     ng       2205: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   2206:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 2207:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   2208: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   2209: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 2210: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       2211: 
1.618     www      2212: 	    if ($submitonly ne 'all') {
1.524     raeburn  2213: 		foreach (sort(keys(%status))) {
1.485     albertel 2214: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   2215: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       2216: 		}
1.41      ng       2217: 	    }
1.126     ng       2218: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 2219: 	    if ($ctr%2 ==0) {
                   2220: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   2221: 	    }
1.41      ng       2222: 	}
                   2223:     }
1.110     ng       2224:     if ($ctr%2 ==1) {
1.126     ng       2225: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      2226: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       2227: 		foreach (@$partlist) {
                   2228: 		    $gradeTable.='<td>&nbsp;</td>';
                   2229: 		}
1.301     albertel 2230: 	    } elsif ($submitonly eq 'queued') {
                   2231: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       2232: 	    }
1.474     albertel 2233: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       2234:     }
                   2235: 
1.474     albertel 2236:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   2237:         '<input type="button" '.
                   2238:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   2239:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       2240:     if ($ctr == 0) {
1.96      albertel 2241: 	my $num_students=(scalar(keys(%$fullname)));
                   2242: 	if ($num_students eq 0) {
1.485     albertel 2243: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 2244: 	} else {
1.171     albertel 2245: 	    my $submissions='submissions';
                   2246: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   2247: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 2248: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 2249: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   2250: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 2251: 		    $num_students).
                   2252: 		'</span><br />';
1.96      albertel 2253: 	}
1.46      ng       2254:     } elsif ($ctr == 1) {
1.474     albertel 2255: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       2256:     }
                   2257:     $request->print($gradeTable);
1.44      ng       2258:     return '';
1.10      ng       2259: }
                   2260: 
1.796     raeburn  2261: #---- Called from the listStudents and the names_for_passback routines.
                   2262: 
                   2263: sub checkselect_js {
                   2264:     my ($formname) = @_;
                   2265:     if ($formname eq '') {
                   2266:         $formname = 'gradesub';
                   2267:     }
                   2268:     my %js_lt;
                   2269:     if ($formname eq 'passbackusers') {
                   2270:         %js_lt = &Apache::lonlocal::texthash (
                   2271:                      'multiple' => 'Please select a student or group of students before pushing the Save Scores button.',
                   2272:                      'single'   => 'Please select the student before pushing the Save Scores button.',
                   2273:                  );
                   2274:     } else {
                   2275:         %js_lt = &Apache::lonlocal::texthash (
                   2276:                      'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   2277:                      'single'   => 'Please select the student before clicking on the Next button.',
                   2278:                  );
                   2279:     }
                   2280:     &js_escape(\%js_lt);
                   2281:     return &Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT);
                   2282: 
                   2283:     function checkSelect(checkBox) {
                   2284:         var ctr=0;
                   2285:         var sense="";
                   2286:         var len = checkBox.length;
                   2287:         if (len == undefined) len = 1;
                   2288:         if (len > 1) {
                   2289:             for (var i=0; i<len; i++) {
                   2290:                 if (checkBox[i].checked) {
                   2291:                     ctr++;
                   2292:                 }
                   2293:             }
                   2294:             sense = '$js_lt{'multiple'}';
                   2295:         } else {
                   2296:             if (checkBox.checked) {
                   2297:                 ctr = 1;
                   2298:             }
                   2299:             sense = '$js_lt{'single'}';
                   2300:         }
                   2301:         if (ctr == 0) {
                   2302:             alert(sense);
                   2303:             return false;
                   2304:         }
                   2305:         document.$formname.submit();
                   2306:     }
                   2307: LISTJAVASCRIPT
                   2308: 
                   2309: }
1.249     albertel 2310: 
                   2311: sub check_script {
1.766     raeburn  2312:     my ($form,$type) = @_;
                   2313:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 2314:     function checkall() {
                   2315:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2316:             ele = document.forms.'.$form.'.elements[i];
                   2317:             if (ele.name == "'.$type.'") {
                   2318:             document.forms.'.$form.'.elements[i].checked=true;
                   2319:                                        }
                   2320:         }
                   2321:     }
                   2322: 
                   2323:     function checksec() {
                   2324:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2325:             ele = document.forms.'.$form.'.elements[i];
                   2326:            string = document.forms.'.$form.'.chksec.value;
                   2327:            if
                   2328:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   2329:               document.forms.'.$form.'.elements[i].checked=true;
                   2330:             }
                   2331:         }
                   2332:     }
                   2333: 
                   2334: 
                   2335:     function uncheckall() {
                   2336:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2337:             ele = document.forms.'.$form.'.elements[i];
                   2338:             if (ele.name == "'.$type.'") {
                   2339:             document.forms.'.$form.'.elements[i].checked=false;
                   2340:                                        }
                   2341:         }
                   2342:     }
                   2343: 
1.597     wenzelju 2344: '."\n");
1.249     albertel 2345:     return $chkallscript;
                   2346: }
                   2347: 
                   2348: sub check_buttons {
1.485     albertel 2349:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   2350:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   2351:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 2352:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   2353:     return $buttons;
                   2354: }
                   2355: 
1.44      ng       2356: #     Displays the submissions for one student or a group of students
1.34      ng       2357: sub processGroup {
1.766     raeburn  2358:     my ($request,$symb) = @_;
1.41      ng       2359:     my $ctr        = 0;
1.155     albertel 2360:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       2361:     my $total      = scalar(@stuchecked)-1;
1.45      ng       2362: 
1.396     banghart 2363:     foreach my $student (@stuchecked) {
                   2364: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 2365: 	$env{'form.student'}        = $uname;
                   2366: 	$env{'form.userdom'}        = $udom;
                   2367: 	$env{'form.fullname'}       = $fullname;
1.619     www      2368: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2369: 	$ctr++;
                   2370:     }
                   2371:     return '';
1.35      ng       2372: }
1.34      ng       2373: 
1.44      ng       2374: #------------------------------------------------------------------------------------
                   2375: #
                   2376: #-------------------------- Next few routines handles grading by student, essentially
                   2377: #                           handles essay response type problem/part
                   2378: #
                   2379: #--- Javascript to handle the submission page functionality ---
                   2380: sub sub_page_js {
                   2381:     my $request = shift;
1.736     damieng  2382:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   2383:     &js_escape(\$alertmsg);
1.597     wenzelju 2384:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       2385:     function updateRadio(formname,id,weight) {
1.125     ng       2386: 	var gradeBox = formname["GD_BOX"+id];
                   2387: 	var radioButton = formname["RADVAL"+id];
                   2388: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       2389: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       2390: 	gradeBox.value = pts;
                   2391: 	var resetbox = false;
                   2392: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  2393: 	    alert("$alertmsg"+pts);
1.71      ng       2394: 	    for (var i=0; i<radioButton.length; i++) {
                   2395: 		if (radioButton[i].checked) {
                   2396: 		    gradeBox.value = i;
                   2397: 		    resetbox = true;
                   2398: 		}
                   2399: 	    }
                   2400: 	    if (!resetbox) {
                   2401: 		formtextbox.value = "";
                   2402: 	    }
                   2403: 	    return;
1.44      ng       2404: 	}
1.71      ng       2405: 
                   2406: 	if (pts > weight) {
                   2407: 	    var resp = confirm("You entered a value ("+pts+
                   2408: 			       ") greater than the weight for the part. Accept?");
                   2409: 	    if (resp == false) {
1.125     ng       2410: 		gradeBox.value = oldpts;
1.71      ng       2411: 		return;
                   2412: 	    }
1.44      ng       2413: 	}
1.13      albertel 2414: 
1.71      ng       2415: 	for (var i=0; i<radioButton.length; i++) {
                   2416: 	    radioButton[i].checked=false;
                   2417: 	    if (pts == i && pts != "") {
                   2418: 		radioButton[i].checked=true;
                   2419: 	    }
                   2420: 	}
                   2421: 	updateSelect(formname,id);
1.125     ng       2422: 	formname["stores"+id].value = "0";
1.41      ng       2423:     }
1.5       albertel 2424: 
1.72      ng       2425:     function writeBox(formname,id,pts) {
1.125     ng       2426: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2427: 	if (checkSolved(formname,id) == 'update') {
                   2428: 	    gradeBox.value = pts;
                   2429: 	} else {
1.125     ng       2430: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       2431: 	    gradeBox.value = oldpts;
1.125     ng       2432: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       2433: 	    for (var i=0; i<radioButton.length; i++) {
                   2434: 		radioButton[i].checked=false;
1.72      ng       2435: 		if (i == oldpts) {
1.71      ng       2436: 		    radioButton[i].checked=true;
                   2437: 		}
                   2438: 	    }
1.41      ng       2439: 	}
1.125     ng       2440: 	formname["stores"+id].value = "0";
1.71      ng       2441: 	updateSelect(formname,id);
                   2442: 	return;
1.41      ng       2443:     }
1.44      ng       2444: 
1.71      ng       2445:     function clearRadBox(formname,id) {
                   2446: 	if (checkSolved(formname,id) == 'noupdate') {
                   2447: 	    updateSelect(formname,id);
                   2448: 	    return;
                   2449: 	}
1.125     ng       2450: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       2451: 	for (var i=0; i<gradeSelect.length; i++) {
                   2452: 	    if (gradeSelect[i].selected) {
                   2453: 		var selectx=i;
                   2454: 	    }
                   2455: 	}
1.125     ng       2456: 	var stores = formname["stores"+id];
1.71      ng       2457: 	if (selectx == stores.value) { return };
1.125     ng       2458: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2459: 	gradeBox.value = "";
1.125     ng       2460: 	var radioButton = formname["RADVAL"+id];
1.71      ng       2461: 	for (var i=0; i<radioButton.length; i++) {
                   2462: 	    radioButton[i].checked=false;
                   2463: 	}
                   2464: 	stores.value = selectx;
                   2465:     }
1.5       albertel 2466: 
1.71      ng       2467:     function checkSolved(formname,id) {
1.125     ng       2468: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       2469: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   2470: 	    if (!reply) {return "noupdate";}
1.120     ng       2471: 	    formname.overRideScore.value = 'yes';
1.41      ng       2472: 	}
1.71      ng       2473: 	return "update";
1.13      albertel 2474:     }
1.71      ng       2475: 
                   2476:     function updateSelect(formname,id) {
1.125     ng       2477: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       2478: 	return;
1.41      ng       2479:     }
1.33      ng       2480: 
1.121     ng       2481: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       2482:     function checksubmit(formname,val,total,parttot) {
1.121     ng       2483: 	formname.gradeOpt.value = val;
1.71      ng       2484: 	if (val == "Save & Next") {
                   2485: 	    for (i=0;i<=total;i++) {
                   2486: 		for (j=0;j<parttot;j++) {
1.125     ng       2487: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       2488: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2489: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       2490: 			if (points == "") {
1.125     ng       2491: 			    var name = formname["name"+i].value;
1.129     ng       2492: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   2493: 			    var resp = confirm("You did not assign a score for "+studentID+
                   2494: 					       ", part "+partid+". Continue?");
1.71      ng       2495: 			    if (resp == false) {
1.125     ng       2496: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       2497: 				return false;
                   2498: 			    }
                   2499: 			}
                   2500: 		    }
                   2501: 		}
                   2502: 	    }
                   2503: 	}
1.120     ng       2504: 	formname.submit();
                   2505:     }
                   2506: 
1.71      ng       2507: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   2508:     function checkSubmitPage(formname,total) {
                   2509: 	noscore = new Array(100);
                   2510: 	var ptr = 0;
                   2511: 	for (i=1;i<total;i++) {
1.125     ng       2512: 	    var partid = formname["q_"+i].value;
1.127     ng       2513: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2514: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   2515: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       2516: 		if (points == "" && status != "correct_by_student") {
                   2517: 		    noscore[ptr] = i;
                   2518: 		    ptr++;
                   2519: 		}
                   2520: 	    }
                   2521: 	}
                   2522: 	if (ptr != 0) {
                   2523: 	    var sense = ptr == 1 ? ": " : "s: ";
                   2524: 	    var prolist = "";
                   2525: 	    if (ptr == 1) {
                   2526: 		prolist = noscore[0];
                   2527: 	    } else {
                   2528: 		var i = 0;
                   2529: 		while (i < ptr-1) {
                   2530: 		    prolist += noscore[i]+", ";
                   2531: 		    i++;
                   2532: 		}
                   2533: 		prolist += "and "+noscore[i];
                   2534: 	    }
                   2535: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   2536: 	    if (resp == false) {
                   2537: 		return false;
                   2538: 	    }
                   2539: 	}
1.45      ng       2540: 
1.71      ng       2541: 	formname.submit();
                   2542:     }
                   2543: SUBJAVASCRIPT
                   2544: }
1.45      ng       2545: 
1.773     raeburn  2546: #--- javascript for grading message center
                   2547: sub sub_grademessage_js {
1.71      ng       2548:     my $request = shift;
1.80      ng       2549:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       2550:     &commonJSfunctions($request);
1.350     albertel 2551: 
1.629     www      2552:     my $inner_js_msg_central= (<<INNERJS);
                   2553: <script type="text/javascript">
1.350     albertel 2554:     function checkInput() {
                   2555:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   2556:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   2557:       var usrctr = document.msgcenter.usrctr.value;
                   2558:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   2559:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   2560: 
                   2561:       var msgchk = "";
                   2562:       if (document.msgcenter.subchk.checked) {
                   2563:          msgchk = "msgsub,";
                   2564:       }
                   2565:       var includemsg = 0;
                   2566:       for (var i=1; i<=nmsg; i++) {
                   2567:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   2568:           var frmmsg = document.msgcenter["msg"+i];
                   2569:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   2570:           var showflg = opener.document.SCORE["shownOnce"+i];
                   2571:           showflg.value = "1";
                   2572:           var chkbox = document.msgcenter["msgn"+i];
                   2573:           if (chkbox.checked) {
                   2574:              msgchk += "savemsg"+i+",";
                   2575:              includemsg = 1;
                   2576:           }
                   2577:       }
                   2578:       if (document.msgcenter.newmsgchk.checked) {
                   2579:          msgchk += "newmsg"+usrctr;
                   2580:          includemsg = 1;
                   2581:       }
                   2582:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   2583:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   2584:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   2585:       includemsg.value = msgchk;
                   2586: 
                   2587:       self.close()
                   2588: 
                   2589:     }
1.629     www      2590: </script>
1.350     albertel 2591: INNERJS
                   2592: 
1.773     raeburn  2593:     my $start_page_msg_central =
1.351     albertel 2594:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   2595: 				       {'js_ready'  => 1,
                   2596: 					'only_body' => 1,
                   2597: 					'bgcolor'   =>'#FFFFFF',});
1.773     raeburn  2598:     my $end_page_msg_central =
1.350     albertel 2599: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   2600: 
1.219     www      2601:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 2602:     $docopen=~s/^document\.//;
1.773     raeburn  2603: 
1.736     damieng  2604:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  2605:                 comp => 'Compose Message for: ',
                   2606:                 incl => 'Include',
1.656     raeburn  2607:                 type => 'Type',
1.652     raeburn  2608:                 subj => 'Subject',
                   2609:                 mesa => 'Message',
                   2610:                 new  => 'New',
                   2611:                 save => 'Save',
                   2612:                 canc => 'Cancel',
                   2613:              );
1.736     damieng  2614:     &html_escape(\%html_js_lt);
                   2615:     &js_escape(\%html_js_lt);
1.597     wenzelju 2616:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       2617: 
1.44      ng       2618: //===================== Script to view submitted by ==================
                   2619:   function viewSubmitter(submitter) {
                   2620:     document.SCORE.refresh.value = "on";
                   2621:     document.SCORE.NCT.value = "1";
                   2622:     document.SCORE.unamedom0.value = submitter;
                   2623:     document.SCORE.submit();
                   2624:     return;
                   2625:   }
                   2626: 
                   2627: //====================== Script for composing message ==============
1.80      ng       2628:    // preload images
                   2629:    img1 = new Image();
                   2630:    img1.src = "$iconpath/mailbkgrd.gif";
                   2631:    img2 = new Image();
                   2632:    img2.src = "$iconpath/mailto.gif";
                   2633: 
1.44      ng       2634:   function msgCenter(msgform,usrctr,fullname) {
                   2635:     var Nmsg  = msgform.savemsgN.value;
                   2636:     savedMsgHeader(Nmsg,usrctr,fullname);
                   2637:     var subject = msgform.msgsub.value;
1.127     ng       2638:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       2639:     re = /msgsub/;
                   2640:     var shwsel = "";
                   2641:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       2642:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   2643:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       2644:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       2645: 	var testmsg = "savemsg"+i+",";
                   2646: 	re = new RegExp(testmsg,"g");
1.44      ng       2647: 	shwsel = "";
                   2648: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       2649: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       2650: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       2651: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   2652: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       2653:     }
1.125     ng       2654:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       2655:     shwsel = "";
                   2656:     re = /newmsg/;
                   2657:     if (re.test(msgchk)) { shwsel = "checked" }
                   2658:     newMsg(newmsg,shwsel);
                   2659:     msgTail(); 
                   2660:     return;
                   2661:   }
                   2662: 
1.123     ng       2663:   function checkEntities(strx) {
                   2664:     if (strx.length == 0) return strx;
                   2665:     var orgStr = ["&", "<", ">", '"']; 
                   2666:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   2667:     var counter = 0;
                   2668:     while (counter < 4) {
                   2669: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   2670: 	counter++;
                   2671:     }
                   2672:     return strx;
                   2673:   }
                   2674: 
                   2675:   function strReplace(strx, orgStr, newStr) {
                   2676:     return strx.split(orgStr).join(newStr);
                   2677:   }
                   2678: 
1.44      ng       2679:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       2680:     var height = 70*Nmsg+250;
1.44      ng       2681:     if (height > 600) {
                   2682: 	height = 600;
                   2683:     }
1.118     ng       2684:     var xpos = (screen.width-600)/2;
                   2685:     xpos = (xpos < 0) ? '0' : xpos;
                   2686:     var ypos = (screen.height-height)/2-30;
                   2687:     ypos = (ypos < 0) ? '0' : ypos;
                   2688: 
1.668     www      2689:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       2690:     pWin.focus();
                   2691:     pDoc = pWin.document;
1.219     www      2692:     pDoc.$docopen;
1.351     albertel 2693:     pDoc.write('$start_page_msg_central');
1.76      ng       2694: 
                   2695:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   2696:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  2697:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       2698: 
1.676     golterma 2699:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  2700:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       2701: }
                   2702:     function displaySubject(msg,shwsel) {
1.76      ng       2703:     pDoc = pWin.document;
1.676     golterma 2704:     pDoc.write("<tr>");
                   2705:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2706:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 2707:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       2708: }
                   2709: 
1.72      ng       2710:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       2711:     pDoc = pWin.document;
1.676     golterma 2712:     pDoc.write("<tr>");
                   2713:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 2714:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   2715:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2716: }
                   2717: 
                   2718:   function newMsg(newmsg,shwsel) {
1.76      ng       2719:     pDoc = pWin.document;
1.676     golterma 2720:     pDoc.write("<tr>");
                   2721:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2722:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 2723:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2724: }
                   2725: 
                   2726:   function msgTail() {
1.76      ng       2727:     pDoc = pWin.document;
1.676     golterma 2728:     //pDoc.write("<\\/table>");
1.465     albertel 2729:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  2730:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   2731:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 2732:     pDoc.write("<\\/form>");
1.351     albertel 2733:     pDoc.write('$end_page_msg_central');
1.128     ng       2734:     pDoc.close();
1.44      ng       2735: }
                   2736: 
1.773     raeburn  2737: SUBJAVASCRIPT
                   2738: }
                   2739: 
                   2740: #--- javascript for essay type problem --
                   2741: sub sub_page_kw_js {
                   2742:     my $request = shift;
                   2743: 
                   2744:     unless ($env{'form.compmsg'}) {
                   2745:         &commonJSfunctions($request);
                   2746:     }
                   2747: 
                   2748:     my $inner_js_highlight_central= (<<INNERJS);
                   2749: <script type="text/javascript">
                   2750:     function updateChoice(flag) {
                   2751:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   2752:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   2753:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   2754:       opener.document.SCORE.refresh.value = "on";
                   2755:       if (opener.document.SCORE.keywords.value!=""){
                   2756:          opener.document.SCORE.submit();
                   2757:       }
                   2758:       self.close()
                   2759:     }
                   2760: </script>
                   2761: INNERJS
                   2762: 
                   2763:     my $start_page_highlight_central =
                   2764:         &Apache::loncommon::start_page('Highlight Central',
                   2765:                                        $inner_js_highlight_central,
                   2766:                                        {'js_ready'  => 1,
                   2767:                                         'only_body' => 1,
                   2768:                                         'bgcolor'   =>'#FFFFFF',});
                   2769:     my $end_page_highlight_central =
                   2770:         &Apache::loncommon::end_page({'js_ready' => 1});
                   2771: 
                   2772:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   2773:     $docopen=~s/^document\.//;
                   2774: 
                   2775:     my %js_lt = &Apache::lonlocal::texthash(
                   2776:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   2777:                 plse => 'Please select a word or group of words from document and then click this link.',
                   2778:                 adds => 'Add selection to keyword list? Edit if desired.',
                   2779:                 col1 => 'red',
                   2780:                 col2 => 'green',
                   2781:                 col3 => 'blue',
                   2782:                 siz1 => 'normal',
                   2783:                 siz2 => '+1',
                   2784:                 siz3 => '+2',
                   2785:                 sty1 => 'normal',
                   2786:                 sty2 => 'italic',
                   2787:                 sty3 => 'bold',
                   2788:              );
                   2789:     my %html_js_lt = &Apache::lonlocal::texthash(
                   2790:                 save => 'Save',
                   2791:                 canc => 'Cancel',
                   2792:                 kehi => 'Keyword Highlight Options',
                   2793:                 txtc => 'Text Color',
                   2794:                 font => 'Font Size',
                   2795:                 fnst => 'Font Style',
                   2796:              );
                   2797:     &js_escape(\%js_lt);
                   2798:     &html_escape(\%html_js_lt);
                   2799:     &js_escape(\%html_js_lt);
                   2800:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   2801: 
                   2802: //===================== Show list of keywords ====================
                   2803:   function keywords(formname) {
                   2804:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   2805:     if (nret==null) return;
                   2806:     formname.keywords.value = nret;
                   2807: 
                   2808:     if (formname.keywords.value != "") {
                   2809:         formname.refresh.value = "on";
                   2810:         formname.submit();
                   2811:     }
                   2812:     return;
                   2813:   }
                   2814: 
                   2815: //===================== Script to add keyword(s) ==================
                   2816:   function getSel() {
                   2817:     if (document.getSelection) txt = document.getSelection();
                   2818:     else if (document.selection) txt = document.selection.createRange().text;
                   2819:     else return;
                   2820:     if (typeof(txt) != 'string') {
                   2821:         txt = String(txt);
                   2822:     }
                   2823:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   2824:     if (cleantxt=="") {
                   2825:         alert("$js_lt{'plse'}");
                   2826:         return;
                   2827:     }
                   2828:     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   2829:     if (nret==null) return;
                   2830:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   2831:     if (document.SCORE.keywords.value != "") {
                   2832:         document.SCORE.refresh.value = "on";
                   2833:         document.SCORE.submit();
                   2834:     }
                   2835:     return;
                   2836:   }
                   2837: 
1.44      ng       2838: //====================== Script for keyword highlight options ==============
                   2839:   function kwhighlight() {
                   2840:     var kwclr    = document.SCORE.kwclr.value;
                   2841:     var kwsize   = document.SCORE.kwsize.value;
                   2842:     var kwstyle  = document.SCORE.kwstyle.value;
                   2843:     var redsel = "";
                   2844:     var grnsel = "";
                   2845:     var blusel = "";
1.736     damieng  2846:     var txtcol1 = "$js_lt{'col1'}";
                   2847:     var txtcol2 = "$js_lt{'col2'}";
                   2848:     var txtcol3 = "$js_lt{'col3'}";
                   2849:     var txtsiz1 = "$js_lt{'siz1'}";
                   2850:     var txtsiz2 = "$js_lt{'siz2'}";
                   2851:     var txtsiz3 = "$js_lt{'siz3'}";
                   2852:     var txtsty1 = "$js_lt{'sty1'}";
                   2853:     var txtsty2 = "$js_lt{'sty2'}";
                   2854:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   2855:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   2856:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   2857:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       2858:     var sznsel = "";
                   2859:     var sz1sel = "";
                   2860:     var sz2sel = "";
1.718     bisitz   2861:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   2862:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   2863:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       2864:     var synsel = "";
                   2865:     var syisel = "";
                   2866:     var sybsel = "";
1.718     bisitz   2867:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   2868:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   2869:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       2870:     highlightCentral();
1.718     bisitz   2871:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   2872:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   2873:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       2874:     highlightend();
                   2875:     return;
                   2876:   }
                   2877: 
                   2878:   function highlightCentral() {
1.76      ng       2879: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       2880:     var xpos = (screen.width-400)/2;
                   2881:     xpos = (xpos < 0) ? '0' : xpos;
                   2882:     var ypos = (screen.height-330)/2-30;
                   2883:     ypos = (ypos < 0) ? '0' : ypos;
                   2884: 
1.206     albertel 2885:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       2886:     hwdWin.focus();
                   2887:     var hDoc = hwdWin.document;
1.219     www      2888:     hDoc.$docopen;
1.351     albertel 2889:     hDoc.write('$start_page_highlight_central');
1.76      ng       2890:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  2891:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       2892: 
1.718     bisitz   2893:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  2894:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       2895:   }
                   2896: 
                   2897:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       2898:     var hDoc = hwdWin.document;
1.718     bisitz   2899:     hDoc.write("<tr>");
1.76      ng       2900:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2901:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       2902:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2903:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       2904:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2905:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 2906:     hDoc.write("<\\/tr>");
1.44      ng       2907:   }
                   2908: 
                   2909:   function highlightend() { 
1.76      ng       2910:     var hDoc = hwdWin.document;
1.718     bisitz   2911:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  2912:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   2913:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 2914:     hDoc.write("<\\/form>");
1.351     albertel 2915:     hDoc.write('$end_page_highlight_central');
1.128     ng       2916:     hDoc.close();
1.44      ng       2917:   }
                   2918: 
                   2919: SUBJAVASCRIPT
                   2920: }
                   2921: 
1.349     albertel 2922: sub get_increment {
1.348     bowersj2 2923:     my $increment = $env{'form.increment'};
                   2924:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   2925:         $increment != .1) {
                   2926:         $increment = 1;
                   2927:     }
                   2928:     return $increment;
                   2929: }
                   2930: 
1.585     bisitz   2931: sub gradeBox_start {
                   2932:     return (
                   2933:         &Apache::loncommon::start_data_table()
                   2934:        .&Apache::loncommon::start_data_table_header_row()
                   2935:        .'<th>'.&mt('Part').'</th>'
                   2936:        .'<th>'.&mt('Points').'</th>'
                   2937:        .'<th>&nbsp;</th>'
                   2938:        .'<th>'.&mt('Assign Grade').'</th>'
                   2939:        .'<th>'.&mt('Weight').'</th>'
                   2940:        .'<th>'.&mt('Grade Status').'</th>'
                   2941:        .&Apache::loncommon::end_data_table_header_row()
                   2942:     );
                   2943: }
                   2944: 
                   2945: sub gradeBox_end {
                   2946:     return (
                   2947:         &Apache::loncommon::end_data_table()
                   2948:     );
                   2949: }
1.71      ng       2950: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   2951: sub gradeBox {
1.322     albertel 2952:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 2953:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2954: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2955:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2956:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2957:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2958:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2959:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2960: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   2961:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2962:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2963:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2964: 				       [$partid]);
                   2965:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2966:     if ($last_resets{$partid}) {
                   2967:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2968:     }
1.695     bisitz   2969:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2970:     my $ctr = 0;
1.348     bowersj2 2971:     my $thisweight = 0;
1.349     albertel 2972:     my $increment = &get_increment();
1.485     albertel 2973: 
                   2974:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2975:     while ($thisweight<=$wgt) {
1.532     bisitz   2976: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2977:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2978: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2979: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2980: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2981:         $thisweight += $increment;
1.71      ng       2982: 	$ctr++;
                   2983:     }
1.485     albertel 2984:     $radio.='</tr></table>';
                   2985: 
                   2986:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2987: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2988: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2989: 	$wgt.')" /></td>'."\n";
1.485     albertel 2990:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2991: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2992: 	' </td>'."\n";
                   2993:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2994: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2995:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2996: 	$line.='<option></option>'.
                   2997: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2998:     } else {
1.485     albertel 2999: 	$line.='<option selected="selected"></option>'.
                   3000: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       3001:     }
1.485     albertel 3002:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   3003: 
                   3004: 
                   3005:     $result .= 
1.695     bisitz   3006: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   3007:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   3008:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       3009:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   3010: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   3011: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  3012: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   3013:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   3014:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   3015:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   3016:         $aggtries.'" />'."\n";
1.582     raeburn  3017:     my $res_error;
                   3018:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   3019:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  3020:     if ($res_error) {
                   3021:         return &navmap_errormsg();
                   3022:     }
1.318     banghart 3023:     return $result;
                   3024: }
1.322     albertel 3025: 
                   3026: sub handback_box {
1.623     www      3027:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773     raeburn  3028:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   3029:     return unless ($numessay);
1.323     banghart 3030:     my (@respids);
1.652     raeburn  3031:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 3032:     foreach my $part_response_id (@part_response_id) {
                   3033:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 3034:         if ($part eq $partid) {
1.375     albertel 3035:             push(@respids,$resp);
1.323     banghart 3036:         }
                   3037:     }
1.318     banghart 3038:     my $result;
1.323     banghart 3039:     foreach my $respid (@respids) {
1.322     albertel 3040: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   3041: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3042: 	next if (!@$files);
1.654     raeburn  3043: 	my $file_counter = 0;
1.313     banghart 3044: 	foreach my $file (@$files) {
1.368     banghart 3045: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  3046:                 $file_counter++;
1.368     banghart 3047:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  3048:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 3049:     	        $file_disp = "$name.$ext";
                   3050:     	        $file = $file_path.$file_disp;
                   3051:     	        $result.=&mt('Return commented version of [_1] to student.',
                   3052:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   3053:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  3054:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 3055: 	    }
1.322     albertel 3056: 	}
1.654     raeburn  3057:         if ($file_counter) {
                   3058:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   3059:                        '<span class="LC_info">'.
                   3060:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   3061:         }
1.313     banghart 3062:     }
1.318     banghart 3063:     return $result;    
1.71      ng       3064: }
1.44      ng       3065: 
1.58      albertel 3066: sub show_problem {
1.382     albertel 3067:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 3068:     my $rendered;
1.382     albertel 3069:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 3070:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 3071:     if ($mode eq 'both' or $mode eq 'text') {
                   3072: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 3073: 						       $env{'request.course.id'},
                   3074: 						       undef,\%form);
1.144     albertel 3075:     }
1.58      albertel 3076:     if ($removeform) {
                   3077: 	$rendered=~s|<form(.*?)>||g;
                   3078: 	$rendered=~s|</form>||g;
1.374     albertel 3079: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 3080:     }
1.144     albertel 3081:     my $companswer;
                   3082:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 3083: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 3084: 	$companswer=
                   3085: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   3086: 						    $env{'request.course.id'},
                   3087: 						    %form);
1.144     albertel 3088:     }
1.58      albertel 3089:     if ($removeform) {
                   3090: 	$companswer=~s|<form(.*?)>||g;
                   3091: 	$companswer=~s|</form>||g;
1.144     albertel 3092: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 3093:     }
1.671     raeburn  3094:     my $renderheading = &mt('View of the problem');
                   3095:     my $answerheading = &mt('Correct answer');
                   3096:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   3097:         my $stu_fullname = $env{'form.fullname'};
                   3098:         if ($stu_fullname eq '') {
                   3099:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3100:         }
                   3101:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   3102:         if ($forwhom ne '') {
                   3103:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   3104:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   3105:         }
                   3106:     }
1.468     albertel 3107:     $rendered=
1.588     bisitz   3108:         '<div class="LC_Box">'
1.671     raeburn  3109:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   3110:        .$rendered
                   3111:        .'</div>';
1.468     albertel 3112:     $companswer=
1.588     bisitz   3113:         '<div class="LC_Box">'
1.671     raeburn  3114:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   3115:        .$companswer
                   3116:        .'</div>';
1.468     albertel 3117:     my $result;
1.144     albertel 3118:     if ($mode eq 'both') {
1.588     bisitz   3119:         $result=$rendered.$companswer;
1.144     albertel 3120:     } elsif ($mode eq 'text') {
1.588     bisitz   3121:         $result=$rendered;
1.144     albertel 3122:     } elsif ($mode eq 'answer') {
1.588     bisitz   3123:         $result=$companswer;
1.144     albertel 3124:     }
1.71      ng       3125:     return $result;
1.58      albertel 3126: }
1.397     albertel 3127: 
1.396     banghart 3128: sub files_exist {
                   3129:     my ($r, $symb) = @_;
                   3130:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   3131:     foreach my $student (@students) {
                   3132:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 3133:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3134: 					      $udom,$uname);
1.792     raeburn  3135:         my ($string)= &get_last_submission(\%record);
1.397     albertel 3136:         foreach my $submission (@$string) {
                   3137:             my ($partid,$respid) =
                   3138: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3139:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   3140: 					   \%record);
                   3141:             return 1 if (@$files);
1.396     banghart 3142:         }
                   3143:     }
1.397     albertel 3144:     return 0;
1.396     banghart 3145: }
1.397     albertel 3146: 
1.394     banghart 3147: sub download_all_link {
                   3148:     my ($r,$symb) = @_;
1.621     www      3149:     unless (&files_exist($r, $symb)) {
1.766     raeburn  3150:         $r->print(&mt('There are currently no submitted documents.'));
                   3151:         return;
1.621     www      3152:     }
1.395     albertel 3153:     my $all_students = 
                   3154: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   3155: 
                   3156:     my $parts =
                   3157: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   3158: 
1.394     banghart 3159:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  3160:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   3161:                              'cgi.'.$identifier.'.symb' => $symb,
                   3162:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 3163:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   3164: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      3165:     return;
                   3166: }
                   3167: 
                   3168: sub submit_download_link {
                   3169:     my ($request,$symb) = @_;
                   3170:     if (!$symb) { return ''; }
1.750     raeburn  3171:     my $res_error;
1.773     raeburn  3172:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   3173:         &response_type($symb,\$res_error);
                   3174:     if ($res_error) {
                   3175:         $request->print(&mt('An error occurred retrieving response types'));
                   3176:         return;
                   3177:     }
                   3178:     unless ($numessay) {
                   3179:         $request->print(&mt('No essayresponse items found'));
                   3180:         return;
1.750     raeburn  3181:     }
1.773     raeburn  3182:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3183:     if (@chosenparts) {
                   3184:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   3185:                                           undef,undef,1));
1.750     raeburn  3186:     }
1.773     raeburn  3187:     if ($numessay) {
1.750     raeburn  3188:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   3189:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3190:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   3191:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   3192:         if (ref($fullname) eq 'HASH') {
                   3193:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   3194:             if (@students) {
                   3195:                 @{$env{'form.stuinfo'}} = @students;
1.773     raeburn  3196:                 if ($numdropbox) {
1.750     raeburn  3197:                     &download_all_link($request,$symb);
1.773     raeburn  3198:                 } else {
                   3199:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  3200:                 }
1.773     raeburn  3201: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  3202: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   3203:             } else {
                   3204:                 $request->print(&mt('No students match the criteria you selected'));
                   3205:             }
                   3206:         } else {
                   3207:             $request->print(&mt('Could not retrieve student information'));
                   3208:         }
                   3209:     } else {
                   3210:         $request->print(&mt('No essayresponse items found'));
                   3211:     }
                   3212:     return;
1.394     banghart 3213: }
1.395     albertel 3214: 
1.432     banghart 3215: sub build_section_inputs {
                   3216:     my $section_inputs;
                   3217:     if ($env{'form.section'} eq '') {
                   3218:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   3219:     } else {
                   3220:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 3221:         foreach my $section (@sections) {
1.432     banghart 3222:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   3223:         }
                   3224:     }
                   3225:     return $section_inputs;
                   3226: }
                   3227: 
1.44      ng       3228: # --------------------------- show submissions of a student, option to grade 
                   3229: sub submission {
1.773     raeburn  3230:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 3231:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   3232:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   3233:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3234:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      3235: 
1.324     albertel 3236:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773     raeburn  3237:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  3238:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  3239:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 3240: 
                   3241:     if (!&canview($usec)) {
1.712     bisitz   3242:         $request->print(
                   3243:             '<span class="LC_warning">'.
1.713     bisitz   3244:             &mt('Unable to view requested student.').
1.712     bisitz   3245:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3246:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3247:             '</span>');
1.104     albertel 3248: 	return;
                   3249:     }
                   3250: 
1.773     raeburn  3251:     my $res_error;
                   3252:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   3253:         &response_type($symb,\$res_error);
                   3254:     if ($res_error) {
                   3255:         $request->print(&navmap_errormsg());
                   3256:         return;
                   3257:     }
                   3258: 
1.257     albertel 3259:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  3260:     unless ($is_tool) { 
                   3261:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   3262:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   3263:     }
1.773     raeburn  3264:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   3265:         $env{'form.compmsg'} = 1;
                   3266:     }
1.257     albertel 3267:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 3268:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   3269: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       3270: 	'/check.gif" height="16" border="0" />';
1.41      ng       3271: 
                   3272:     # header info
                   3273:     if ($counter == 0) {
1.773     raeburn  3274:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3275:         if (@chosenparts) {
                   3276:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   3277:         } elsif ($divforres) {
                   3278:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   3279:         } else {
                   3280:             $request->print('<br clear="all" />');
                   3281:         }
1.41      ng       3282: 	&sub_page_js($request);
1.773     raeburn  3283:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   3284: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       3285: 
1.44      ng       3286: 	# option to display problem, only once else it cause problems 
                   3287:         # with the form later since the problem has a form.
1.257     albertel 3288: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 3289: 	    my $mode;
1.257     albertel 3290: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 3291: 		$mode='both';
1.257     albertel 3292: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 3293: 		$mode='text';
1.257     albertel 3294: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 3295: 		$mode='answer';
                   3296: 	    }
1.329     albertel 3297: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 3298: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       3299: 	}
1.441     www      3300: 
1.41      ng       3301: 	my %keyhash = ();
1.773     raeburn  3302: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       3303: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 3304: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   3305: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773     raeburn  3306: 	}
                   3307: 	# kwclr is the only variable that is guaranteed not to be blank
                   3308: 	# if this subroutine has been called once.
                   3309: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 3310: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3311: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   3312: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   3313: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   3314: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773     raeburn  3315: 	}
                   3316: 	if ($env{'form.compmsg'}) {
                   3317: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      3318: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 3319: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       3320: 	}
1.773     raeburn  3321: 
1.257     albertel 3322: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 3323: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 3324: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       3325: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 3326: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       3327: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       3328: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       3329: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   3330: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 3331: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3332: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   3333: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   3334: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773     raeburn  3335: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 3336: 			&build_section_inputs().
1.326     albertel 3337: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       3338: 			'<input type="hidden" name="NCT"'.
1.257     albertel 3339: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773     raeburn  3340: 	if ($env{'form.compmsg'}) {
                   3341: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   3342: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   3343: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   3344: 	}
                   3345: 	if ($numessay) {
1.257     albertel 3346: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   3347: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   3348: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773     raeburn  3349: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       3350: 	}
1.773     raeburn  3351: 
1.41      ng       3352: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 3353: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       3354: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       3355: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 3356: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       3357: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       3358: 		'" />'."\n".
                   3359: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       3360: 	    $cts++;
                   3361: 	}
                   3362: 	$request->print($prnmsg);
1.32      ng       3363: 
1.773     raeburn  3364: 	if ($numessay) {
1.652     raeburn  3365: 
                   3366:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   3367:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  3368:                           keyw => 'Keyword Options',
1.655     raeburn  3369:                           list => 'List',
1.652     raeburn  3370:                           past => 'Paste Selection to List',
1.661     www      3371:                           high => 'Highlight Attribute',
1.773     raeburn  3372:                      );
1.88      www      3373: #
                   3374: # Print out the keyword options line
                   3375: #
1.718     bisitz   3376: 	    $request->print(
                   3377:                 '<div class="LC_columnSection">'
                   3378:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   3379:                .&Apache::lonhtmlcommon::funclist_from_array(
                   3380:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   3381:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   3382:  class="page">'.$lt{'past'}.'</a>',
                   3383:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   3384:                     {legend => $lt{'keyw'}})
                   3385:                .'</fieldset></div>'
                   3386:             );
                   3387: 
1.88      www      3388: #
                   3389: # Load the other essays for similarity check
                   3390: #
1.753     raeburn  3391:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   3392:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3393:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3394:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3395:                 if ($cdom ne '' && $cnum ne '') {
                   3396:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   3397:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   3398:                         my $apath = $1.'_'.$id;
                   3399:                         $apath=~s/\W/\_/gs;
                   3400:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   3401:                     }
                   3402:                 }
                   3403:             } else {
                   3404: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   3405: 	        $apath=&escape($apath);
                   3406: 	        $apath=~s/\W/\_/gs;
                   3407:                 &init_old_essays($symb,$apath,$adom,$aname);
                   3408:             }
1.41      ng       3409:         }
                   3410:     }
1.44      ng       3411: 
1.441     www      3412: # This is where output for one specific student would start
1.592     bisitz   3413:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   3414:     $request->print(
                   3415:         "\n\n"
                   3416:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   3417:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   3418:        ."\n"
                   3419:     );
1.441     www      3420: 
1.592     bisitz   3421:     # Show additional functions if allowed
                   3422:     if ($perm{'vgr'}) {
                   3423:         $request->print(
                   3424:             &Apache::loncommon::track_student_link(
1.708     bisitz   3425:                 'View recent activity',
1.592     bisitz   3426:                 $uname,$udom,'check')
                   3427:            .' '
                   3428:         );
                   3429:     }
                   3430:     if ($perm{'opa'}) {
                   3431:         $request->print(
                   3432:             &Apache::loncommon::pprmlink(
                   3433:                 &mt('Set/Change parameters'),
                   3434:                 $uname,$udom,$symb,'check'));
                   3435:     }
                   3436: 
                   3437:     # Show Problem
1.257     albertel 3438:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 3439: 	my $mode;
1.257     albertel 3440: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 3441: 	    $mode='both';
1.257     albertel 3442: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 3443: 	    $mode='text';
1.257     albertel 3444: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 3445: 	    $mode='answer';
                   3446: 	}
1.329     albertel 3447: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 3448: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 3449:     }
1.144     albertel 3450: 
1.257     albertel 3451:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       3452: 
1.44      ng       3453:     # Display student info
1.41      ng       3454:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   3455: 
1.745     raeburn  3456:     my $boxtitle = &mt('Submissions');
                   3457:     if ($is_tool) {
                   3458:         $boxtitle = &mt('Transactions')
                   3459:     }
1.590     bisitz   3460:     my $result='<div class="LC_Box">'
1.745     raeburn  3461:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       3462:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   3463:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773     raeburn  3464:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   3465:         $result.='<p class="LC_info">'
                   3466:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   3467:                 ."</p>\n";
1.469     albertel 3468:     }
                   3469: 
1.773     raeburn  3470:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 3471:     my $fullname;
                   3472:     my $col_fullnames = [];
1.773     raeburn  3473:     if ($numessay) {
1.464     albertel 3474: 	(my $sub_result,$fullname,$col_fullnames)=
                   3475: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   3476: 				 $counter);
                   3477: 	$result.=$sub_result;
1.41      ng       3478:     }
1.44      ng       3479:     $request->print($result."\n");
1.773     raeburn  3480: 
1.44      ng       3481:     # print student answer/submission
1.773     raeburn  3482:     # Options are (1) Last submission only
                   3483:     #             (2) Last submission (with detailed information for that submission)
                   3484:     #             (3) All transactions (by date)
                   3485:     #             (4) The whole record (with detailed information for all transactions)
                   3486: 
1.793     raeburn  3487:     my ($lastsubonly,$partinfo) =
                   3488:         &show_last_submission($uname,$udom,$symb,$essayurl,$responseType,$env{'form.lastSub'},
                   3489:                               $is_tool,$fullname,\%record,\%coursedesc_by_cid);
                   3490:     $request->print($partinfo);
                   3491:     $request->print($lastsubonly);
                   3492: 
                   3493:     if ($env{'form.lastSub'} eq 'datesub') {
                   3494:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3495: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
                   3496:     }
                   3497:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   3498:         my $identifier = (&canmodify($usec)? $counter : '');
                   3499:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
                   3500: 								 $env{'request.course.id'},
                   3501: 								 $last,'.submission',
                   3502: 								 'Apache::grades::keywords_highlight',
                   3503:                                                                  $usec,$identifier));
                   3504:     }
                   3505:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   3506: 	.$udom.'" />'."\n");
                   3507:     # return if view submission with no grading option
                   3508:     if (!&canmodify($usec)) {
                   3509: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   3510: 	return;
                   3511:     } else {
                   3512: 	$request->print('</div>'."\n");
                   3513:     }
                   3514: 
                   3515:     # grading message center
                   3516: 
                   3517:     if ($env{'form.compmsg'}) {
                   3518:         my $result='<div class="LC_Box">'.
                   3519:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   3520:                    '<div class="LC_grade_message_center_body">';
                   3521:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   3522:         my $msgfor = $givenn.' '.$lastname;
                   3523:         if (scalar(@$col_fullnames) > 0) {
                   3524:             my $lastone = pop(@$col_fullnames);
                   3525:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   3526:         }
                   3527:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   3528:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   3529:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   3530:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   3531:                  ',\''.$msgfor.'\');" target="_self">'.
                   3532:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   3533:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   3534:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   3535:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   3536:                  '<br />&nbsp;('.
                   3537:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   3538:                  '</div></div>';
                   3539:         $request->print($result);
                   3540:     }
                   3541: 
                   3542:     my %seen = ();
                   3543:     my @partlist;
                   3544:     my @gradePartRespid;
                   3545:     my @part_response_id;
                   3546:     if ($is_tool) {
                   3547:         @part_response_id = ([0,'']);
                   3548:     } else {
                   3549:         @part_response_id = &flatten_responseType($responseType);
                   3550:     }
                   3551:     $request->print(
                   3552:         '<div class="LC_Box">'
                   3553:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
                   3554:     );
                   3555:     $request->print(&gradeBox_start());
                   3556:     foreach my $part_response_id (@part_response_id) {
                   3557:     	my ($partid,$respid) = @{ $part_response_id };
                   3558: 	my $part_resp = join('_',@{ $part_response_id });
                   3559: 	next if ($seen{$partid} > 0);
                   3560: 	$seen{$partid}++;
                   3561: 	push(@partlist,$partid);
                   3562: 	push(@gradePartRespid,$partid.'.'.$respid);
                   3563: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
                   3564:     }
                   3565:     $request->print(&gradeBox_end()); # </div>
                   3566:     $request->print('</div>');
                   3567: 
                   3568:     $request->print('<div class="LC_grade_info_links">');
                   3569:     $request->print('</div>');
                   3570: 
                   3571:     $result='<input type="hidden" name="partlist'.$counter.
                   3572: 	'" value="'.(join ":",@partlist).'" />'."\n";
                   3573:     $result.='<input type="hidden" name="gradePartRespid'.
                   3574: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
                   3575:     my $ctr = 0;
                   3576:     while ($ctr < scalar(@partlist)) {
                   3577: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   3578: 	    $partlist[$ctr].'" />'."\n";
                   3579: 	$ctr++;
                   3580:     }
                   3581:     $request->print($result.''."\n");
                   3582: 
                   3583: # Done with printing info for one student
                   3584: 
                   3585:     $request->print('</div>');#LC_grade_show_user
                   3586: 
                   3587: 
                   3588:     # print end of form
                   3589:     if ($counter == $total) {
                   3590:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
                   3591: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
                   3592: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
                   3593: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
                   3594: 	my $ntstu ='<select name="NTSTU">'.
                   3595: 	    '<option>1</option><option>2</option>'.
                   3596: 	    '<option>3</option><option>5</option>'.
                   3597: 	    '<option>7</option><option>10</option></select>'."\n";
                   3598: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
                   3599: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
                   3600:         $endform.=&mt('[_1]student(s)',$ntstu);
                   3601: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
                   3602: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
                   3603: 	    '<input type="button" value="'.&mt('Next').'" '.
                   3604: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
                   3605:         $endform.='<span class="LC_warning">'.
                   3606:                   &mt('(Next and Previous (student) do not save the scores.)').
                   3607:                   '</span>'."\n" ;
                   3608:         $endform.="<input type='hidden' value='".&get_increment().
                   3609:             "' name='increment' />";
                   3610: 	$endform.='</td></tr></table></form>';
                   3611: 	$request->print($endform);
                   3612:     }
                   3613:     return '';
                   3614: }
                   3615: 
                   3616: sub show_last_submission {
                   3617:     my ($uname,$udom,$symb,$essayurl,$responseType,$viewtype,$is_tool,$fullname,
                   3618:         $record,$coursedesc_by_cid) = @_;
1.792     raeburn  3619:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
1.793     raeburn  3620:         &get_last_submission($record,$is_tool);
1.468     albertel 3621: 
1.793     raeburn  3622:     my ($lastsubonly,$partinfo);
1.792     raeburn  3623:     if ($timestamp eq '') {
1.793     raeburn  3624:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>';
1.745     raeburn  3625:     } elsif ($is_tool) {
                   3626:         $lastsubonly =
                   3627:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3628:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$timestamp."</div>\n";
1.702     kruse    3629:     } else {
1.792     raeburn  3630:         my ($shownsubmdate,$showngradedate);
                   3631:         if ($lastsubmittime && $lastgradetime) {
                   3632:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
                   3633:             if ($lastgradetime > $lastsubmittime) {
                   3634:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
                   3635:              }
                   3636:         } else {
                   3637:             $shownsubmdate = $timestamp;
                   3638:         }
1.702     kruse    3639:         $lastsubonly =
                   3640:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3641:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
                   3642:         if ($showngradedate) {
                   3643:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
                   3644:         }
1.702     kruse    3645: 
1.793     raeburn  3646:         my %seenparts;
                   3647:         my @part_response_id = &flatten_responseType($responseType);
                   3648:         foreach my $part (@part_response_id) {
                   3649:             my ($partid,$respid) = @{ $part };
                   3650:             my $display_part=&get_display_part($partid,$symb);
                   3651:             if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   3652:                 if (exists($seenparts{$partid})) { next; }
                   3653:                 $seenparts{$partid}=1;
                   3654:                 $partinfo .=
1.702     kruse    3655:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3656:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   3657:                                '<a href="javascript:viewSubmitter(\''.
                   3658:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   3659:                                '\');" target="_self">'.
                   3660:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
1.793     raeburn  3661:                     '<br />';
                   3662:                 next;
                   3663:             }
                   3664:             my $responsetype = $responseType->{$partid}->{$respid};
                   3665:             if (!exists($record->{"resource.$partid.$respid.submission"})) {
1.702     kruse    3666:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   3667:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3668:                     ' <span class="LC_internal_info">'.
                   3669:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   3670:                     '</span>&nbsp; &nbsp;'.
1.793     raeburn  3671:                     '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   3672:                 next;
                   3673:             }
                   3674:             foreach my $submission (@$string) {
                   3675:                 my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3676:                 if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   3677:                 my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   3678:                 # Similarity check
1.702     kruse    3679:                 my $similar='';
                   3680:                 my ($type,$trial,$rndseed);
                   3681:                 if ($hide eq 'rand') {
                   3682:                     $type = 'randomizetry';
1.793     raeburn  3683:                     $trial = $record->{"resource.$partid.tries"};
                   3684:                     $rndseed = $record->{"resource.$partid.rndseed"};
1.702     kruse    3685:                 }
1.793     raeburn  3686:                 if ($env{'form.checkPlag'}) {
                   3687:                     my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   3688:                     &most_similar($uname,$udom,$symb,$subval);
                   3689:                     if ($osim) {
                   3690:                         $osim=int($osim*100.0);
1.702     kruse    3691:                         if ($hide eq 'anon') {
                   3692:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   3693:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   3694:                         } else {
1.793     raeburn  3695:                             $similar='<hr />';
1.753     raeburn  3696:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3697:                                 $similar .= '<h3><span class="LC_warning">'.
                   3698:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   3699:                                                 $osim,
                   3700:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3701:                                             '</span></h3>';
                   3702:                             } else {
                   3703:                                 my %old_course_desc;
                   3704:                                 if ($ocrsid ne '') {
1.793     raeburn  3705:                                     if (ref($coursedesc_by_cid->{$ocrsid}) eq 'HASH') {
                   3706:                                         %old_course_desc = %{$coursedesc_by_cid->{$ocrsid}};
1.753     raeburn  3707:                                     } else {
                   3708:                                         my $args;
                   3709:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   3710:                                             $args = {'one_time' => 1};
                   3711:                                         }
                   3712:                                         %old_course_desc =
                   3713:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
1.793     raeburn  3714:                                         $coursedesc_by_cid->{$ocrsid} = \%old_course_desc;
1.753     raeburn  3715:                                     }
                   3716:                                     $similar .=
                   3717:                                         '<h3><span class="LC_warning">'.
                   3718:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   3719:                                             $osim,
                   3720:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   3721:                                             $old_course_desc{'description'},
                   3722:                                             $old_course_desc{'num'},
                   3723:                                             $old_course_desc{'domain'}).
                   3724:                                         '</span></h3>';
                   3725:                                 } else {
                   3726:                                     $similar .=
                   3727:                                         '<h3><span class="LC_warning">'.
                   3728:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   3729:                                             $osim,
                   3730:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3731:                                         '</span></h3>';
                   3732:                                 }
                   3733:                             }
                   3734:                             $similar .= '<blockquote><i>'.
                   3735:                                         &keywords_highlight($oessay).
                   3736:                                         '</i></blockquote><hr />';
1.702     kruse    3737:                         }
1.793     raeburn  3738:                     }
                   3739:                 }
                   3740:                 my $order=&get_order($partid,$respid,$symb,$uname,$udom,
1.702     kruse    3741:                                      undef,$type,$trial,$rndseed);
1.793     raeburn  3742:                 if (($viewtype eq 'lastonly') ||
                   3743:                     ($viewtype eq 'datesub')  ||
                   3744:                     ($viewtype =~ /^(last|all)$/)) {
                   3745:                     my $display_part=&get_display_part($partid,$symb);
1.702     kruse    3746:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   3747:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3748:                         ' <span class="LC_internal_info">'.
                   3749:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   3750:                         '</span>&nbsp; &nbsp;';
1.793     raeburn  3751:                     my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3752:                     if (@$files) {
1.702     kruse    3753:                         if ($hide eq 'anon') {
                   3754:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   3755:                         } else {
                   3756:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   3757:                                         .'<br /><span class="LC_warning">';
                   3758:                             if(@$files == 1) {
                   3759:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  3760:                             } else {
1.702     kruse    3761:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   3762:                             }
1.774     raeburn  3763:                             $lastsubonly .= '</span>';
1.702     kruse    3764:                             foreach my $file (@$files) {
                   3765:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   3766:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  3767:                             }
                   3768:                         }
1.793     raeburn  3769:                         $lastsubonly.='<br />';
1.702     kruse    3770:                     }
                   3771:                     if ($hide eq 'anon') {
1.793     raeburn  3772:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
1.702     kruse    3773:                     } else {
1.774     raeburn  3774:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  3775:                         if ($draft) {
                   3776:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   3777:                         }
                   3778:                         $subval =
1.793     raeburn  3779:                             &cleanRecord($subval,$responsetype,$symb,$partid,
                   3780:                                          $respid,$record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  3781:                         if ($responsetype eq 'essay') {
                   3782:                             $subval =~ s{\n}{<br />}g;
                   3783:                         }
                   3784:                         $lastsubonly.=$subval."\n";
1.702     kruse    3785:                     }
1.774     raeburn  3786:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.793     raeburn  3787:                     $lastsubonly.='</div>';
                   3788:                 }
1.702     kruse    3789:             }
1.773     raeburn  3790:         }
1.793     raeburn  3791:         $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.118     ng       3792:     }
1.793     raeburn  3793:     return ($lastsubonly,$partinfo);
1.38      ng       3794: }
                   3795: 
1.464     albertel 3796: sub check_collaborators {
                   3797:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   3798:     my ($result,@col_fullnames);
                   3799:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   3800:     foreach my $part (keys(%$handgrade)) {
                   3801: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   3802: 					'.maxcollaborators',
                   3803: 					$symb,$udom,$uname);
                   3804: 	next if ($ncol <= 0);
                   3805: 	$part =~ s/\_/\./g;
                   3806: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   3807: 	my (@good_collaborators, @bad_collaborators);
                   3808: 	foreach my $possible_collaborator
1.630     www      3809: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 3810: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   3811: 	    next if ($possible_collaborator eq '');
1.631     www      3812: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 3813: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   3814: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   3815: 	    # Doing this grep allows 'fuzzy' specification
                   3816: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   3817: 			       keys(%$classlist));
                   3818: 	    if (! scalar(@matches)) {
                   3819: 		push(@bad_collaborators, $possible_collaborator);
                   3820: 	    } else {
                   3821: 		push(@good_collaborators, @matches);
                   3822: 	    }
                   3823: 	}
                   3824: 	if (scalar(@good_collaborators) != 0) {
1.630     www      3825: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 3826: 	    foreach my $name (@good_collaborators) {
                   3827: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   3828: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      3829: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 3830: 	    }
1.630     www      3831: 	    $result.='</ol><br />'."\n";
1.466     albertel 3832: 	    my ($part)=split(/\./,$part);
1.464     albertel 3833: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   3834: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   3835: 		"\n";
                   3836: 	}
                   3837: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 3838: 	    $result.='<div class="LC_warning">';
1.464     albertel 3839: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   3840: 	    $result .= '</div>';
                   3841: 	}         
                   3842: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 3843: 	    $result .= '<div class="LC_warning">';
1.464     albertel 3844: 	    $result .= &mt('This student has submitted too many '.
                   3845: 		'collaborators.  Maximum is [_1].',$ncol);
                   3846: 	    $result .= '</div>';
                   3847: 	}
                   3848:     }
                   3849:     return ($result,$fullname,\@col_fullnames);
                   3850: }
                   3851: 
1.44      ng       3852: #--- Retrieve the last submission for all the parts
1.38      ng       3853: sub get_last_submission {
1.745     raeburn  3854:     my ($returnhash,$is_tool)=@_;
1.792     raeburn  3855:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
1.119     ng       3856:     if ($$returnhash{'version'}) {
1.46      ng       3857: 	my %lasthash=();
1.792     raeburn  3858:         my %prevsolved=();
                   3859:         my %solved=();
                   3860: 	my $version;
1.119     ng       3861: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.792     raeburn  3862:             my %handgraded = ();
1.397     albertel 3863: 	    foreach my $key (sort(split(/\:/,
                   3864: 					$$returnhash{$version.':keys'}))) {
                   3865: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
1.792     raeburn  3866:                 if ($key =~ /\.([^.]+)\.regrader$/) {
                   3867:                     $handgraded{$1} = 1;
                   3868:                 } elsif ($key =~ /\.portfiles$/) {
                   3869:                     if (($$returnhash{$version.':'.$key} ne '') &&
                   3870:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
                   3871:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3872:                     }
                   3873:                 } elsif ($key =~ /\.submission$/) {
                   3874:                     if ($$returnhash{$version.':'.$key} ne '') {
                   3875:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3876:                     }
                   3877:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
                   3878:                     $prevsolved{$1} = $solved{$1};
                   3879:                     $solved{$1} = $lasthash{$key};
                   3880:                 }
                   3881:             }
                   3882:             foreach my $partid (keys(%handgraded)) {
                   3883:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
                   3884:                     (($solved{$partid} eq 'incorrect_by_override') ||
                   3885:                      ($solved{$partid} eq 'correct_by_override'))) {
                   3886:                     $lastgradetime = $$returnhash{$version.':timestamp'};
                   3887:                 }
                   3888:                 if ($solved{$partid} ne '') {
                   3889:                     $prevsolved{$partid} = $solved{$partid};
                   3890:                 }
1.46      ng       3891: 	    }
                   3892: 	}
1.795     raeburn  3893: #
                   3894: # Timestamp is for last transaction for this resource, which does not
                   3895: # necessarily correspond to the time of last submission for problem (or part).
                   3896: #
                   3897:         if ($lasthash{'timestamp'} ne '') {
                   3898:             $timestamp = &Apache::lonlocal::locallocaltime($lasthash{'timestamp'});
                   3899:         }
1.640     raeburn  3900:         my (%typeparts,%randombytry);
1.596     raeburn  3901:         my $showsurv = 
                   3902:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   3903:         foreach my $key (sort(keys(%lasthash))) {
                   3904:             if ($key =~ /\.type$/) {
                   3905:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  3906:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   3907:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  3908:                     my ($ign,@parts) = split(/\./,$key);
                   3909:                     pop(@parts);
1.641     raeburn  3910:                     my $id = join('.',@parts);
1.640     raeburn  3911:                     if ($lasthash{$key} eq 'randomizetry') {
                   3912:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   3913:                     } else {
                   3914:                         unless ($showsurv) {
                   3915:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   3916:                         }
1.596     raeburn  3917:                     }
                   3918:                     delete($lasthash{$key});
                   3919:                 }
                   3920:             }
                   3921:         }
                   3922:         my @hidden = keys(%typeparts);
1.640     raeburn  3923:         my @randomize = keys(%randombytry);
1.397     albertel 3924: 	foreach my $key (keys(%lasthash)) {
                   3925: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  3926:             my $hide;
                   3927:             if (@hidden) {
                   3928:                 foreach my $id (@hidden) {
                   3929:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  3930:                         $hide = 'anon';
1.596     raeburn  3931:                         last;
                   3932:                     }
                   3933:                 }
                   3934:             }
1.640     raeburn  3935:             unless ($hide) {
                   3936:                 if (@randomize) {
1.732     raeburn  3937:                     foreach my $id (@randomize) {
1.640     raeburn  3938:                         if ($key =~ /^\Q$id\E/) {
                   3939:                             $hide = 'rand';
                   3940:                             last;
                   3941:                         }
                   3942:                     }
                   3943:                 }
                   3944:             }
1.397     albertel 3945: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  3946: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   3947:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   3948:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   3949:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       3950: 	}
                   3951:     }
1.397     albertel 3952:     if (!@string) {
1.745     raeburn  3953:         my $msg;
                   3954:         if ($is_tool) {
1.747     raeburn  3955:             $msg = &mt('No grade passed back.');
1.745     raeburn  3956:         } else {
                   3957:             $msg = &mt('Nothing submitted - no attempts.');
                   3958:         }
1.397     albertel 3959: 	$string[0] =
1.745     raeburn  3960: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 3961:     }
1.792     raeburn  3962:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       3963: }
1.35      ng       3964: 
1.44      ng       3965: #--- High light keywords, with style choosen by user.
1.38      ng       3966: sub keywords_highlight {
1.44      ng       3967:     my $string    = shift;
1.257     albertel 3968:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   3969:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       3970:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 3971:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 3972:     foreach my $keyword (@keylist) {
                   3973: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       3974:     }
                   3975:     return $string;
1.38      ng       3976: }
1.36      ng       3977: 
1.671     raeburn  3978: # For Tasks provide a mechanism to display previous version for one specific student
                   3979: 
                   3980: sub show_previous_task_version {
                   3981:     my ($request,$symb) = @_;
                   3982:     if ($symb eq '') {
1.717     bisitz   3983:         $request->print(
                   3984:             '<span class="LC_error">'.
                   3985:             &mt('Unable to handle ambiguous references.').
                   3986:             '</span>');
1.671     raeburn  3987:         return '';
                   3988:     }
                   3989:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3990:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3991:     if (!&canview($usec)) {
1.712     bisitz   3992:         $request->print(
                   3993:             '<span class="LC_warning">'.
1.713     bisitz   3994:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   3995:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3996:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3997:             '</span>');
1.671     raeburn  3998:         return;
                   3999:     }
                   4000:     my $mode = 'both';
                   4001:     my $isTask = ($symb =~/\.task$/);
                   4002:     if ($isTask) {
                   4003:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   4004:             if ($env{'form.fullname'} eq '') {
                   4005:                 $env{'form.fullname'} =
                   4006:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   4007:             }
                   4008:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   4009:             $request->print("\n\n".
                   4010:                             '<div class="LC_grade_show_user">'.
                   4011:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   4012:                             '</h2>'."\n");
                   4013:             &Apache::lonxml::clear_problem_counter();
                   4014:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   4015:                             {'previousversion' => $env{'form.previousversion'} }));
                   4016:             $request->print("\n</div>");
                   4017:         }
                   4018:     }
                   4019:     return;
                   4020: }
                   4021: 
                   4022: sub choose_task_version_form {
                   4023:     my ($symb,$uname,$udom,$nomenu) = @_;
                   4024:     my $isTask = ($symb =~/\.task$/);
                   4025:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   4026:     if ($isTask) {
                   4027:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4028:                                               $udom,$uname);
                   4029:         if (($record{'resource.0.version'} eq '') ||
                   4030:             ($record{'resource.0.version'} < 2)) {
                   4031:             return ($record{'resource.0.version'},
                   4032:                     $record{'resource.0.version'},$result,$js);
                   4033:         } else {
                   4034:             $current = $record{'resource.0.version'};
                   4035:         }
                   4036:         if ($env{'form.previousversion'}) {
                   4037:             $displayed = $env{'form.previousversion'};
                   4038:             $rowtitle = &mt('Choose another version:')
                   4039:         } else {
                   4040:             $displayed = $current;
                   4041:             $rowtitle = &mt('Show earlier version:');
                   4042:         }
                   4043:         $result = '<div class="LC_left_float">';
                   4044:         my $list;
                   4045:         my $numversions = 0;
                   4046:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   4047:             if ($i == $current) {
                   4048:                 if (!$env{'form.previousversion'} || $nomenu) {
                   4049:                     next;
                   4050:                 } else {
                   4051:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   4052:                     $numversions ++;
                   4053:                 }
                   4054:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   4055:                 unless ($i == $env{'form.previousversion'}) {
                   4056:                     $numversions ++;
                   4057:                 }
                   4058:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   4059:             }
                   4060:         }
                   4061:         if ($numversions) {
                   4062:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   4063:             $result .=
                   4064:                 '<form name="getprev" method="post" action=""'.
                   4065:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   4066:                 &Apache::loncommon::start_data_table().
                   4067:                 &Apache::loncommon::start_data_table_row().
                   4068:                 '<th align="left">'.$rowtitle.'</th>'.
                   4069:                 '<td><select name="version">'.
                   4070:                 '<option>'.&mt('Select').'</option>'.
                   4071:                 $list.
                   4072:                 '</select></td>'.
                   4073:                 &Apache::loncommon::end_data_table_row();
                   4074:             unless ($nomenu) {
                   4075:                 $result .= &Apache::loncommon::start_data_table_row().
                   4076:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   4077:                 '<td><span class="LC_nobreak">'.
                   4078:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   4079:                 &mt('Yes').'</label>'.
                   4080:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   4081:                 '</span></td>'.
                   4082:                 &Apache::loncommon::end_data_table_row();
                   4083:             }
                   4084:             $result .=
                   4085:                 &Apache::loncommon::start_data_table_row().
                   4086:                 '<th align="left">&nbsp;</th>'.
                   4087:                 '<td>'.
                   4088:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   4089:                 '</td>'.
                   4090:                 &Apache::loncommon::end_data_table_row().
                   4091:                 &Apache::loncommon::end_data_table().
                   4092:                 '</form>';
                   4093:             $js = &previous_display_javascript($nomenu,$current);
                   4094:         } elsif ($displayed && $nomenu) {
                   4095:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   4096:         } else {
                   4097:             $result .= &mt('No previous versions to show for this student');
                   4098:         }
                   4099:         $result .= '</div>';
                   4100:     }
                   4101:     return ($current,$displayed,$result,$js);
                   4102: }
                   4103: 
                   4104: sub previous_display_javascript {
                   4105:     my ($nomenu,$current) = @_;
                   4106:     my $js = <<"JSONE";
                   4107: <script type="text/javascript">
                   4108: // <![CDATA[
                   4109: function previousVersion(uname,udom,symb) {
                   4110:     var current = '$current';
                   4111:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   4112:     var prevstr = new RegExp("^\\\\d+\$");
                   4113:     if (!prevstr.test(version)) {
                   4114:         return false;
                   4115:     }
                   4116:     var url = '';
                   4117:     if (version == current) {
                   4118:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   4119:     } else {
                   4120:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   4121:     }
                   4122: JSONE
                   4123:     if ($nomenu) {
                   4124:         $js .= <<"JSTWO";
                   4125:     document.location.href = url;
                   4126: JSTWO
                   4127:     } else {
                   4128:         $js .= <<"JSTHREE";
                   4129:     var newwin = 0;
                   4130:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   4131:         if (document.getprev.prevwin[i].checked == true) {
                   4132:             newwin = document.getprev.prevwin[i].value;
                   4133:         }
                   4134:     }
                   4135:     if (newwin == 1) {
                   4136:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   4137:         url = url+'&inhibitmenu=yes';
                   4138:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   4139:             previousWin = window.open(url,'',options,1);
                   4140:         } else {
                   4141:             previousWin.location.href = url;
                   4142:         }
                   4143:         previousWin.focus();
                   4144:         return false;
                   4145:     } else {
                   4146:         document.location.href = url;
                   4147:         return false;
                   4148:     }
                   4149: JSTHREE
                   4150:     }
                   4151:     $js .= <<"ENDJS";
                   4152:     return false;
                   4153: }
                   4154: // ]]>
                   4155: </script>
                   4156: ENDJS
                   4157: 
                   4158: }
                   4159: 
1.44      ng       4160: #--- Called from submission routine
1.38      ng       4161: sub processHandGrade {
1.608     www      4162:     my ($request,$symb) = @_;
1.324     albertel 4163:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 4164:     my $button = $env{'form.gradeOpt'};
                   4165:     my $ngrade = $env{'form.NCT'};
                   4166:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 4167:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4168:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.786     raeburn  4169:     my ($res_error,%queueable);
                   4170:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   4171:     if ($res_error) {
                   4172:         $request->print(&navmap_errormsg());
                   4173:         return;
                   4174:     } else {
                   4175:         foreach my $part (@{$partlist}) {
                   4176:             if (ref($responseType->{$part}) eq 'HASH') {
                   4177:                 foreach my $id (keys(%{$responseType->{$part}})) {
                   4178:                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   4179:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   4180:                         $queueable{$part} = 1;
                   4181:                         last;
                   4182:                     }
                   4183:                 }
                   4184:             }
                   4185:         }
                   4186:     }
1.301     albertel 4187: 
1.44      ng       4188:     if ($button eq 'Save & Next') {
1.798     raeburn  4189:         my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   4190:         my (%skip_passback,%pbsave,%pbcollab);
1.44      ng       4191: 	my $ctr = 0;
                   4192: 	while ($ctr < $ngrade) {
1.257     albertel 4193: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  4194: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
1.798     raeburn  4195:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable,\%needpb,\%skip_passback,\%pbsave);
1.71      ng       4196: 	    if ($errorflag eq 'no_score') {
                   4197: 		$ctr++;
                   4198: 		next;
                   4199: 	    }
1.104     albertel 4200: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   4201: 		$request->print(
                   4202:                     '<span class="LC_error">'
                   4203:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   4204:                    .'</span>');
1.104     albertel 4205: 		$ctr++;
                   4206: 		next;
                   4207: 	    }
1.726     raeburn  4208:             if ($numhidden) {
                   4209:                 $request->print(
                   4210:                     '<span class="LC_info">'
                   4211:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   4212:                    .'</span><br />');
                   4213:             }
1.257     albertel 4214: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       4215: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 4216: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   4217:             my ($feedurl,$showsymb) =
                   4218: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   4219: 	    my $messagetail;
1.62      albertel 4220: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      4221: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      4222: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  4223: 		$subject.=' ['.$restitle.']';
1.44      ng       4224: 		my (@msgnum) = split(/,/,$includemsg);
                   4225: 		foreach (@msgnum) {
1.257     albertel 4226: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       4227: 		}
1.80      ng       4228: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      4229: 		if ($env{'form.withgrades'.$ctr}) {
                   4230: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  4231: 		    $messagetail = " for <a href=\"".
1.605     www      4232: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  4233: 		}
                   4234: 		$msgstatus = 
                   4235:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   4236: 						     $message.$messagetail,
1.418     albertel 4237:                                                      undef,$feedurl,undef,
1.386     raeburn  4238:                                                      undef,undef,$showsymb,
                   4239:                                                      $restitle);
1.574     bisitz   4240: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  4241: 				$msgstatus.'<br />');
1.44      ng       4242: 	    }
1.257     albertel 4243: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 4244: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 4245: 		foreach my $collabstr (@collabstrs) {
                   4246: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 4247: 		    foreach my $collaborator (@collaborators) {
1.803     raeburn  4248: 			my ($errorflag,$pts,$wgt,$numchg,$numupdate) = 
1.324     albertel 4249: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.803     raeburn  4250: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 4251: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 4252: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 4253: 			    next;
1.798     raeburn  4254: 			} else {
1.803     raeburn  4255:                             if ($numchg || $numupdate) { 
                   4256:                                 $pbcollab{$collaborator}{$part} = [$pts,$wgt];
                   4257:                             }
1.798     raeburn  4258:                             if ($message ne '') {
1.800     raeburn  4259: 			        my ($baseurl,$showsymb) = 
                   4260: 				    &get_feedurl_and_symb($symb,$collaborator,
1.801     raeburn  4261: 						          $udom);
1.800     raeburn  4262: 			        if ($env{'form.withgrades'.$ctr}) {
                   4263: 				    $messagetail = " for <a href=\"".
                   4264:                                         $baseurl."?symb=$showsymb\">$restitle</a>";
                   4265: 			        }
                   4266: 			        $msgstatus =
                   4267: 				    &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.150     albertel 4268: 			    }
1.800     raeburn  4269: 		        }
1.44      ng       4270: 		    }
                   4271: 		}
                   4272: 	    }
                   4273: 	    $ctr++;
                   4274: 	}
1.798     raeburn  4275:         if ((keys(%pbcollab)) && (keys(%needpb))) {
1.803     raeburn  4276:             foreach my $user (keys(%pbcollab)) {
                   4277:                 my ($clbuname,$clbudom) = split(/:/,$user);
                   4278:                 my $clbusec = &Apache::lonnet::getsection($clbudom,$clbuname,$cdom.'_'.$cnum); 
                   4279:                 if (ref($pbcollab{$user}) eq 'HASH') {
                   4280:                     my @clparts = keys(%{$pbcollab{$user}});
                   4281:                     if (@clparts) {
                   4282:                         my $navmap = Apache::lonnavmaps::navmap->new($clbuname,$clbudom,$clbusec);
                   4283:                         if (ref($navmap)) {
                   4284:                             my $res = $navmap->getBySymb($symb);
                   4285:                             if (ref($res)) {
                   4286:                                 my $partlist = $res->parts();
                   4287:                                 if (ref($partlist) eq 'ARRAY') {
                   4288:                                     my (%weights,%awardeds,%excuseds);
                   4289:                                     foreach my $part (@{$partlist}) {
                   4290:                                         if ($res->status($part) eq $res->EXCUSED) {
                   4291:                                             $excuseds{$symb}{$part} = 1;
                   4292:                                         } else { 
                   4293:                                             $excuseds{$symb}{$part} = '';
                   4294:                                         }
                   4295:                                         if ((exists($pbcollab{$user}{$part})) && (ref($pbcollab{$user}{$part}) eq 'ARRAY')) {
                   4296:                                             my $pts = $pbcollab{$user}{$part}[0];
                   4297:                                             my $wt = $pbcollab{$user}{$part}[1];
                   4298:                                             if ($wt) {
                   4299:                                                 $awardeds{$symb}{$part} = $pts/$wt;
                   4300:                                                 $weights{$symb}{$part} = $wt;
                   4301:                                             } else {
                   4302:                                                 $awardeds{$symb}{$part} = 0;
                   4303:                                                 $weights{$symb}{$part} = 0;
                   4304:                                             }
                   4305:                                         } else {
                   4306:                                             $awardeds{$symb}{$part} = $res->awarded($part);
                   4307:                                             $weights{$symb}{$part} = $res->weight($part);
                   4308:                                         }
                   4309:                                     }
                   4310:                                     &process_passbacks('handgrade',[$symb],$cdom,$cnum,$clbudom,$clbuname,$clbusec,\%weights,
                   4311:                                                        \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   4312:                                 }
                   4313:                             }
                   4314:                         }
                   4315:                     }
                   4316:                 }
                   4317:             }
1.798     raeburn  4318:         }
1.44      ng       4319:     }
                   4320: 
1.773     raeburn  4321:     my %keyhash = ();
                   4322:     if ($numessay) {
1.119     ng       4323: 	# Keywords sorted in alphabatical order
1.257     albertel 4324: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   4325: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  4326: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 4327: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   4328: 	$env{'form.keywords'} = join(' ',@keywords);
                   4329: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   4330: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   4331: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   4332: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   4333: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  4334:     }
1.119     ng       4335: 
1.773     raeburn  4336:     if ($env{'form.compmsg'}) {
1.119     ng       4337: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 4338: 	# New messages are saved in env for the next student.
1.119     ng       4339: 	# All messages are saved in nohist_handgrade.db
                   4340: 	my ($ctr,$idx) = (1,1);
1.257     albertel 4341: 	while ($ctr <= $env{'form.savemsgN'}) {
                   4342: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   4343: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       4344: 		$idx++;
                   4345: 	    }
                   4346: 	    $ctr++;
1.41      ng       4347: 	}
1.119     ng       4348: 	$ctr = 0;
                   4349: 	while ($ctr < $ngrade) {
1.257     albertel 4350: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  4351: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4352: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4353: 	        $idx++;
1.119     ng       4354: 	    }
                   4355: 	    $ctr++;
1.41      ng       4356: 	}
1.257     albertel 4357: 	$env{'form.savemsgN'} = --$idx;
                   4358: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       4359:     }
1.773     raeburn  4360:     if (($numessay) || ($env{'form.compmsg'})) {
                   4361:         my $putresult = &Apache::lonnet::put
                   4362:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   4363:     }
                   4364: 
1.44      ng       4365:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 4366:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   4367:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       4368: 	my ($ctr,$total) = (0,0);
                   4369: 	while ($ctr < $ngrade) {
1.257     albertel 4370: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       4371: 	    $ctr++;
                   4372: 	}
1.257     albertel 4373: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       4374: 	$ctr = 0;
                   4375: 	while ($ctr < $total) {
1.257     albertel 4376: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   4377: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   4378: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      4379: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       4380: 	    $ctr++;
                   4381: 	}
                   4382: 	return '';
                   4383:     }
1.36      ng       4384: 
1.44      ng       4385:     # Get the next/previous one or group of students
1.257     albertel 4386:     my $firststu = $env{'form.unamedom0'};
                   4387:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       4388:     my $ctr = 2;
1.41      ng       4389:     while ($laststu eq '') {
1.257     albertel 4390: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       4391: 	$ctr++;
                   4392: 	$laststu = $firststu if ($ctr > $ngrade);
                   4393:     }
1.44      ng       4394: 
1.41      ng       4395:     my (@parsedlist,@nextlist);
                   4396:     my ($nextflg) = 0;
1.524     raeburn  4397:     foreach my $item (sort 
1.294     albertel 4398: 	     {
                   4399: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4400: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4401: 		 }
                   4402: 		 return $a cmp $b;
                   4403: 	     } (keys(%$fullname))) {
1.41      ng       4404: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  4405: 	    push(@parsedlist,$item);
1.41      ng       4406: 	}
1.524     raeburn  4407: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       4408: 	if ($button eq 'Previous') {
1.524     raeburn  4409: 	    last if ($item eq $firststu);
                   4410: 	    push(@parsedlist,$item);
1.41      ng       4411: 	}
                   4412:     }
                   4413:     $ctr = 0;
                   4414:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   4415:     foreach my $student (@parsedlist) {
1.257     albertel 4416: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       4417: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 4418: 	
                   4419: 	if ($submitonly eq 'queued') {
                   4420: 	    my %queue_status = 
                   4421: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4422: 							$udom,$uname);
                   4423: 	    next if (!defined($queue_status{'gradingqueue'}));
                   4424: 	}
                   4425: 
1.156     albertel 4426: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 4427: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 4428: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 4429: 	    my $submitted = 0;
1.248     albertel 4430: 	    my $ungraded = 0;
                   4431: 	    my $incorrect = 0;
1.524     raeburn  4432: 	    foreach my $item (keys(%status)) {
                   4433: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   4434: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   4435: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   4436: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 4437: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   4438: 		    $submitted = 0;
                   4439: 		}
1.41      ng       4440: 	    }
1.156     albertel 4441: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   4442: 				     $submitonly eq 'incorrect' ||
                   4443: 				     $submitonly eq 'graded'));
1.248     albertel 4444: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   4445: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       4446: 	}
1.524     raeburn  4447: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       4448: 	last if ($ctr == $ntstu);
1.41      ng       4449: 	$ctr++;
                   4450:     }
1.36      ng       4451: 
1.41      ng       4452:     $ctr = 0;
                   4453:     my $total = scalar(@nextlist)-1;
1.39      ng       4454: 
1.524     raeburn  4455:     foreach (sort(@nextlist)) {
1.41      ng       4456: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 4457: 	$env{'form.student'}  = $uname;
                   4458: 	$env{'form.userdom'}  = $udom;
                   4459: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      4460: 	&submission($request,$ctr,$total,$symb);
1.41      ng       4461: 	$ctr++;
                   4462:     }
                   4463:     if ($total < 0) {
1.653     raeburn  4464: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       4465: 	$request->print($the_end);
                   4466:     }
                   4467:     return '';
1.38      ng       4468: }
1.36      ng       4469: 
1.44      ng       4470: #---- Save the score and award for each student, if changed
1.38      ng       4471: sub saveHandGrade {
1.798     raeburn  4472:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable,$needpb,$skip_passback,$pbsave) = @_;
1.342     banghart 4473:     my @version_parts;
1.104     albertel 4474:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 4475: 					   $env{'request.course.id'});
1.104     albertel 4476:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 4477:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 4478:     my @parts_graded;
1.77      ng       4479:     my %newrecord  = ();
1.803     raeburn  4480:     my ($pts,$wgt,$totchg,$sendupdate) = ('','',0,0);
1.269     raeburn  4481:     my %aggregate = ();
                   4482:     my $aggregateflag = 0;
1.726     raeburn  4483:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  4484:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  4485:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  4486:         $totchg += $numchgs;
                   4487:     }
1.798     raeburn  4488:     my (%weights,%awardeds,%excuseds);
1.301     albertel 4489:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   4490:     foreach my $new_part (@parts) {
1.803     raeburn  4491: 	#collaborator ($submitter may vary for different parts)
1.259     banghart 4492: 	if ($submitter && $new_part ne $part) { next; }
                   4493: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.798     raeburn  4494:         if ($env{'form.WGT'.$newflg.'_'.$new_part} eq '') {
                   4495:             $weights{$symb}{$new_part} = 1;
                   4496:         } else {
                   4497:             $weights{$symb}{$new_part} = $env{'form.WGT'.$newflg.'_'.$new_part};
                   4498:         }
1.125     ng       4499: 	if ($dropMenu eq 'excused') {
1.798     raeburn  4500:             $excuseds{$symb}{$new_part} = 1;
                   4501:             $awardeds{$symb}{$new_part} = '';
1.259     banghart 4502: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   4503: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   4504: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   4505: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 4506: 		}
1.364     banghart 4507: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.803     raeburn  4508:                 $sendupdate ++;
1.58      albertel 4509: 	    }
1.125     ng       4510: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 4511: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  4512: 	    foreach my $key (keys(%record)) {
1.259     banghart 4513: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 4514: 	    }
1.259     banghart 4515: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4516: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 4517:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   4518: 
                   4519:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   4520: 					       [$new_part]);
                   4521:             my $aggtries =$totaltries;
1.269     raeburn  4522:             if ($last_resets{$new_part}) {
1.270     albertel 4523:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   4524: 					   $new_part);
1.269     raeburn  4525:             }
1.270     albertel 4526: 
                   4527:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  4528:             if ($aggtries > 0) {
1.327     albertel 4529:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  4530:                 $aggregateflag = 1;
                   4531:             }
1.803     raeburn  4532:             $sendupdate ++;
1.798     raeburn  4533:             $excuseds{$symb}{$new_part} = '';
                   4534:             $awardeds{$symb}{$new_part} = '';
1.125     ng       4535: 	} elsif ($dropMenu eq '') {
1.259     banghart 4536: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   4537: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   4538: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   4539: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 4540: 		next;
                   4541: 	    }
1.259     banghart 4542: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   4543: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       4544: 	    my $partial= $pts/$wgt;
1.798     raeburn  4545:             $awardeds{$symb}{$new_part} = $partial;
                   4546:             $excuseds{$symb}{$new_part} = '';
1.259     banghart 4547: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 4548: 		#do not update score for part if not changed.
1.346     banghart 4549:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 4550: 		next;
1.251     banghart 4551: 	    } else {
1.524     raeburn  4552: 	        push(@parts_graded,$new_part);
1.803     raeburn  4553:                 $sendupdate ++;
1.153     albertel 4554: 	    }
1.259     banghart 4555: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   4556: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 4557: 	    }
1.259     banghart 4558: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       4559: 	    if ($partial == 0) {
1.153     albertel 4560: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   4561: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   4562: 		}
1.41      ng       4563: 	    } else {
1.153     albertel 4564: 		if ($record{$reckey} ne 'correct_by_override') {
                   4565: 		    $newrecord{$reckey} = 'correct_by_override';
                   4566: 		}
                   4567: 	    }	    
                   4568: 	    if ($submitter && 
1.259     banghart 4569: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   4570: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       4571: 	    }
1.259     banghart 4572: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4573: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       4574: 	}
1.259     banghart 4575: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 4576: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   4577: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   4578: 	        $dropMenu eq 'reset status')
                   4579: 	   {
1.524     raeburn  4580: 	    push(@version_parts,$new_part);
1.259     banghart 4581: 	}
1.41      ng       4582:     }
1.301     albertel 4583:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4584:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4585: 
1.344     albertel 4586:     if (%newrecord) {
                   4587:         if (@version_parts) {
1.364     banghart 4588:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   4589:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 4590: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 4591: 	    foreach my $new_part (@version_parts) {
                   4592: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   4593: 				$new_part,\%newrecord);
                   4594: 	    }
1.259     banghart 4595:         }
1.44      ng       4596: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 4597: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 4598: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.786     raeburn  4599: 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       4600:     }
1.269     raeburn  4601:     if ($aggregateflag) {
                   4602:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4603: 			      $cdom,$cnum);
1.269     raeburn  4604:     }
1.803     raeburn  4605:     if (($sendupdate || $totchg) && (!$submitter)) {
1.798     raeburn  4606:         if ((ref($needpb) eq 'HASH') &&
                   4607:             (keys(%{$needpb}))) {
1.802     raeburn  4608:             &process_passbacks('handgrade',[$symb],$cdom,$cnum,$domain,$stuname,$usec,\%weights,
1.798     raeburn  4609:                                \%awardeds,\%excuseds,$needpb,$skip_passback,$pbsave);
                   4610:         }
                   4611:     }
1.803     raeburn  4612:     return ('',$pts,$wgt,$totchg,$sendupdate);
1.726     raeburn  4613: }
                   4614: 
                   4615: sub makehidden {
1.728     raeburn  4616:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  4617:     return unless (ref($record) eq 'HASH');
                   4618:     my %modified;
                   4619:     my $numchanged = 0;
                   4620:     if (exists($record->{$version.':keys'})) {
                   4621:         my $partsregexp = $parts;
                   4622:         $partsregexp =~ s/,/|/g;
                   4623:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   4624:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   4625:                  my $item = $1;
                   4626:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   4627:                      $modified{$key} = $record->{$version.':'.$key};
                   4628:                  }
                   4629:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   4630:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   4631:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   4632:                 $modified{$key} = $record->{$version.':'.$key};
                   4633:             }
                   4634:         }
                   4635:         if (keys(%modified)) {
                   4636:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  4637:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  4638:                 $numchanged ++;
                   4639:             }
                   4640:         }
                   4641:     }
                   4642:     return $numchanged;
1.36      ng       4643: }
1.322     albertel 4644: 
1.380     albertel 4645: sub check_and_remove_from_queue {
1.786     raeburn  4646:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 4647:     my @ungraded_parts;
                   4648:     foreach my $part (@{$parts}) {
                   4649: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   4650: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   4651: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   4652: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   4653: 		) {
1.786     raeburn  4654:             if ($queueable->{$part}) {
                   4655: 	        push(@ungraded_parts, $part);
                   4656:             }
1.380     albertel 4657: 	}
                   4658:     }
                   4659:     if ( !@ungraded_parts ) {
                   4660: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   4661: 					       $cnum,$domain,$stuname);
                   4662:     }
                   4663: }
                   4664: 
1.337     banghart 4665: sub handback_files {
                   4666:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  4667:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  4668:     my $res_error;
                   4669:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4670:     if ($res_error) {
                   4671:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   4672:         return;
                   4673:     }
1.654     raeburn  4674:     my @handedback;
                   4675:     my $file_msg;
1.375     albertel 4676:     my @part_response_id = &flatten_responseType($responseType);
                   4677:     foreach my $part_response_id (@part_response_id) {
                   4678:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   4679: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  4680:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   4681:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   4682:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   4683:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   4684:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 4685:                     my ($directory,$answer_file) = 
1.654     raeburn  4686:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 4687:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  4688: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 4689: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  4690:                     my $getpropath = 1;
1.773     raeburn  4691:                     my ($dir_list,$listerror) =
1.662     raeburn  4692:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   4693:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  4694: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   4695:                     # fix filename
1.355     banghart 4696:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   4697:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  4698:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 4699:             	                                $save_file_name);
1.337     banghart 4700:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  4701:                         $request->print('<br /><span class="LC_error">'.
                   4702:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  4703:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  4704:                                         '</span>');
1.356     banghart 4705:                     } else {
1.360     banghart 4706:                         # mark the file as read only
1.654     raeburn  4707:                         push(@handedback,$save_file_name);
1.367     albertel 4708: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   4709: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   4710: 			}
                   4711:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  4712: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 4713:                     }
1.686     bisitz   4714:                     $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 4715:                 }
                   4716:             }
                   4717:         }
1.654     raeburn  4718:     }
                   4719:     if (@handedback > 0) {
                   4720:         $request->print('<br />');
                   4721:         my @what = ($symb,$env{'request.course.id'},'handback');
                   4722:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   4723:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   4724:         my ($subject,$message);
                   4725:         if (scalar(@handedback) == 1) {
                   4726:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   4727:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   4728:         } else {
                   4729:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   4730:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   4731:         }
                   4732:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   4733:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   4734:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   4735:         my ($feedurl,$showsymb) =
                   4736:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   4737:         my $restitle = &Apache::lonnet::gettitle($symb);
                   4738:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   4739:         my $msgstatus =
                   4740:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   4741:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   4742:                  $restitle);
                   4743:         if ($msgstatus) {
                   4744:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   4745:         }
                   4746:     }
1.338     banghart 4747:     return;
1.337     banghart 4748: }
                   4749: 
1.418     albertel 4750: sub get_feedurl_and_symb {
                   4751:     my ($symb,$uname,$udom) = @_;
                   4752:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   4753:     $url = &Apache::lonnet::clutter($url);
                   4754:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   4755: 					$symb,$udom,$uname);
                   4756:     if ($encrypturl =~ /^yes$/i) {
                   4757: 	&Apache::lonenc::encrypted(\$url,1);
                   4758: 	&Apache::lonenc::encrypted(\$symb,1);
                   4759:     }
                   4760:     return ($url,$symb);
                   4761: }
                   4762: 
1.313     banghart 4763: sub get_submitted_files {
                   4764:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   4765:     my @files;
                   4766:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   4767:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   4768:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   4769:     	    push(@files,$file_url.$file);
                   4770:         }
                   4771:     }
                   4772:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   4773:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   4774:     }
                   4775:     return (\@files);
                   4776: }
1.322     albertel 4777: 
1.269     raeburn  4778: # ----------- Provides number of tries since last reset.
                   4779: sub get_num_tries {
                   4780:     my ($record,$last_reset,$part) = @_;
                   4781:     my $timestamp = '';
                   4782:     my $num_tries = 0;
                   4783:     if ($$record{'version'}) {
                   4784:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   4785:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   4786:                 $timestamp = $$record{$version.':timestamp'};
                   4787:                 if ($timestamp > $last_reset) {
                   4788:                     $num_tries ++;
                   4789:                 } else {
                   4790:                     last;
                   4791:                 }
                   4792:             }
                   4793:         }
                   4794:     }
                   4795:     return $num_tries;
                   4796: }
                   4797: 
                   4798: # ----------- Determine decrements required in aggregate totals 
                   4799: sub decrement_aggs {
                   4800:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   4801:     my %decrement = (
                   4802:                         attempts => 0,
                   4803:                         users => 0,
                   4804:                         correct => 0
                   4805:                     );
                   4806:     $decrement{'attempts'} = $aggtries;
                   4807:     if ($solvedstatus =~ /^correct/) {
                   4808:         $decrement{'correct'} = 1;
                   4809:     }
                   4810:     if ($aggtries == $totaltries) {
                   4811:         $decrement{'users'} = 1;
                   4812:     }
1.524     raeburn  4813:     foreach my $type (keys(%decrement)) {
1.269     raeburn  4814:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   4815:     }
                   4816:     return;
                   4817: }
                   4818: 
                   4819: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   4820: sub get_last_resets {
1.270     albertel 4821:     my ($symb,$courseid,$partids) =@_;
                   4822:     my %last_resets;
1.269     raeburn  4823:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   4824:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 4825:     my @keys;
                   4826:     foreach my $part (@{$partids}) {
                   4827: 	push(@keys,"$symb\0$part\0resettime");
                   4828:     }
                   4829:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   4830: 				     $cdom,$cname);
                   4831:     foreach my $part (@{$partids}) {
                   4832: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  4833:     }
1.270     albertel 4834:     return %last_resets;
1.269     raeburn  4835: }
                   4836: 
1.251     banghart 4837: # ----------- Handles creating versions for portfolio files as answers
                   4838: sub version_portfiles {
1.343     banghart 4839:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 4840:     my $version_parts = join('|',@$v_flag);
1.343     banghart 4841:     my @returned_keys;
1.255     banghart 4842:     my $parts = join('|', @$parts_graded);
1.277     albertel 4843:     foreach my $key (keys(%$record)) {
1.259     banghart 4844:         my $new_portfiles;
1.263     banghart 4845:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 4846:             my @versioned_portfiles;
1.367     albertel 4847:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  4848:             if (@portfiles) {
                   4849:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   4850:                                                       \@versioned_portfiles);
1.252     banghart 4851:             }
1.343     banghart 4852:             $$record{$key} = join(',',@versioned_portfiles);
                   4853:             push(@returned_keys,$key);
1.251     banghart 4854:         }
1.794     raeburn  4855:     }
                   4856:     return (@returned_keys);
1.305     banghart 4857: }
                   4858: 
1.44      ng       4859: #--------------------------------------------------------------------------------------
                   4860: #
                   4861: #-------------------------- Next few routines handles grading by section or whole class
                   4862: #
                   4863: #--- Javascript to handle grading by section or whole class
1.42      ng       4864: sub viewgrades_js {
                   4865:     my ($request) = shift;
                   4866: 
1.539     riegler  4867:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  4868:     &js_escape(\$alertmsg);
1.597     wenzelju 4869:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       4870:    function writePoint(partid,weight,point) {
1.125     ng       4871: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   4872: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       4873: 	if (point == "textval") {
1.125     ng       4874: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  4875: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4876: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       4877: 		var resetbox = false;
                   4878: 		for (var i=0; i<radioButton.length; i++) {
                   4879: 		    if (radioButton[i].checked) {
                   4880: 			textbox.value = i;
                   4881: 			resetbox = true;
                   4882: 		    }
                   4883: 		}
                   4884: 		if (!resetbox) {
                   4885: 		    textbox.value = "";
                   4886: 		}
                   4887: 		return;
                   4888: 	    }
1.109     matthew  4889: 	    if (parseFloat(point) > parseFloat(weight)) {
                   4890: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4891: 				   ") greater than the weight for the part. Accept?");
                   4892: 		if (resp == false) {
                   4893: 		    textbox.value = "";
                   4894: 		    return;
                   4895: 		}
                   4896: 	    }
1.42      ng       4897: 	    for (var i=0; i<radioButton.length; i++) {
                   4898: 		radioButton[i].checked=false;
1.109     matthew  4899: 		if (parseFloat(point) == i) {
1.42      ng       4900: 		    radioButton[i].checked=true;
                   4901: 		}
                   4902: 	    }
1.41      ng       4903: 
1.42      ng       4904: 	} else {
1.125     ng       4905: 	    textbox.value = parseFloat(point);
1.42      ng       4906: 	}
1.41      ng       4907: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4908: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 4909: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4910: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4911: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4912: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4913: 	    if (saveval != "correct") {
                   4914: 		scorename.value = point;
1.43      ng       4915: 		if (selname[0].selected != true) {
                   4916: 		    selname[0].selected = true;
                   4917: 		}
1.42      ng       4918: 	    }
                   4919: 	}
1.125     ng       4920: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       4921:     }
                   4922: 
                   4923:     function writeRadText(partid,weight) {
1.125     ng       4924: 	var selval   = document.classgrade["SELVAL_"+partid];
                   4925: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      4926:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       4927: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   4928: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       4929: 	    for (var i=0; i<radioButton.length; i++) {
                   4930: 		radioButton[i].checked=false;
                   4931: 
                   4932: 	    }
                   4933: 	    textbox.value = "";
                   4934: 
                   4935: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4936: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4937: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4938: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4939: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4940: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4941: 		if ((saveval != "correct") || override) {
1.42      ng       4942: 		    scorename.value = "";
1.125     ng       4943: 		    if (selval[1].selected) {
                   4944: 			selname[1].selected = true;
                   4945: 		    } else {
                   4946: 			selname[2].selected = true;
                   4947: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   4948: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   4949: 		    }
1.42      ng       4950: 		}
                   4951: 	    }
1.43      ng       4952: 	} else {
                   4953: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4954: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4955: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4956: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4957: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4958: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4959: 		if ((saveval != "correct") || override) {
1.125     ng       4960: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       4961: 		    selname[0].selected = true;
                   4962: 		}
                   4963: 	    }
                   4964: 	}	    
1.42      ng       4965:     }
                   4966: 
                   4967:     function changeSelect(partid,user) {
1.125     ng       4968: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4969: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       4970: 	var point  = textbox.value;
1.125     ng       4971: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       4972: 
1.109     matthew  4973: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4974: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       4975: 	    textbox.value = "";
                   4976: 	    return;
                   4977: 	}
1.109     matthew  4978: 	if (parseFloat(point) > parseFloat(weight)) {
                   4979: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4980: 			       ") greater than the weight of the part. Accept?");
                   4981: 	    if (resp == false) {
                   4982: 		textbox.value = "";
                   4983: 		return;
                   4984: 	    }
                   4985: 	}
1.42      ng       4986: 	selval[0].selected = true;
                   4987:     }
                   4988: 
                   4989:     function changeOneScore(partid,user) {
1.125     ng       4990: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4991: 	if (selval[1].selected || selval[2].selected) {
                   4992: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   4993: 	    if (selval[2].selected) {
                   4994: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   4995: 	    }
1.269     raeburn  4996:         }
1.42      ng       4997:     }
                   4998: 
                   4999:     function resetEntry(numpart) {
                   5000: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       5001: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   5002: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   5003: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   5004: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       5005: 	    for (var i=0; i<radioButton.length; i++) {
                   5006: 		radioButton[i].checked=false;
                   5007: 
                   5008: 	    }
                   5009: 	    textbox.value = "";
                   5010: 	    selval[0].selected = true;
                   5011: 
                   5012: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       5013: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 5014: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       5015: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   5016: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   5017: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   5018: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   5019: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   5020: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       5021: 		if (saveselval == "excused") {
1.43      ng       5022: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       5023: 		} else {
1.43      ng       5024: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       5025: 		}
                   5026: 	    }
1.41      ng       5027: 	}
1.42      ng       5028:     }
                   5029: 
1.41      ng       5030: VIEWJAVASCRIPT
1.42      ng       5031: }
                   5032: 
1.44      ng       5033: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       5034: sub viewgrades {
1.608     www      5035:     my ($request,$symb) = @_;
1.745     raeburn  5036:     my ($is_tool,$toolsymb);
                   5037:     if ($symb =~ /ext\.tool$/) {
                   5038:         $is_tool = 1;
                   5039:         $toolsymb = $symb;
                   5040:     }
1.42      ng       5041:     &viewgrades_js($request);
1.41      ng       5042: 
1.168     albertel 5043:     #need to make sure we have the correct data for later EXT calls, 
                   5044:     #thus invalidate the cache
                   5045:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5046:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5047:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5048:     &Apache::lonnet::clear_EXT_cache_status();
                   5049: 
1.398     albertel 5050:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       5051: 
                   5052:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 5053:     $result.=&jscriptNform($symb);
1.41      ng       5054: 
1.44      ng       5055:     #beginning of class grading form
1.442     banghart 5056:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       5057:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 5058: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       5059: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 5060: 	&build_section_inputs().
1.442     banghart 5061: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       5062: 
1.738     raeburn  5063:     #retrieve selected groups
                   5064:     my (@groups,$group_display);
                   5065:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   5066:     if (grep(/^all$/,@groups)) {
                   5067:         @groups = ('all');
                   5068:     } elsif (grep(/^none$/,@groups)) {
                   5069:         @groups = ('none');
                   5070:     } elsif (@groups > 0) {
                   5071:         $group_display = join(', ',@groups);
                   5072:     }
                   5073: 
                   5074:     my ($common_header,$specific_header,@sections,$section_display);
1.780     raeburn  5075:     if ($env{'request.course.sec'} ne '') {
                   5076:         @sections = ($env{'request.course.sec'});
                   5077:     } else {
                   5078:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   5079:     }
                   5080: 
                   5081: # Check if Save button should be usable
                   5082:     my $disabled = ' disabled="disabled"';
                   5083:     if ($perm{'mgr'}) {
                   5084:         if (grep(/^all$/,@sections)) {
                   5085:             undef($disabled);
                   5086:         } else {
                   5087:             foreach my $sec (@sections) {
                   5088:                 if (&canmodify($sec)) {
                   5089:                     undef($disabled);
                   5090:                     last;
                   5091:                 }
                   5092:             }
                   5093:         }
                   5094:     }
1.738     raeburn  5095:     if (grep(/^all$/,@sections)) {
                   5096:         @sections = ('all');
                   5097:         if ($group_display) {
                   5098:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   5099:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   5100:         } elsif (grep(/^none$/,@groups)) {
                   5101:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   5102:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   5103:         } else {
                   5104: 	    $common_header = &mt('Assign Common Grade to Class');
                   5105:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   5106:         }
                   5107:     } elsif (grep(/^none$/,@sections)) {
                   5108:         @sections = ('none');
                   5109:         if ($group_display) {
                   5110:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   5111:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   5112:         } elsif (grep(/^none$/,@groups)) {
                   5113:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   5114:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   5115:         } else {
                   5116:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   5117: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   5118:         }
                   5119:     } else {
                   5120:         $section_display = join (", ",@sections);
                   5121:         if ($group_display) {
                   5122:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   5123:                                  $section_display,$group_display);
                   5124:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   5125:                                    $section_display,$group_display);
                   5126:         } elsif (grep(/^none$/,@groups)) {
                   5127:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   5128:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   5129:         } else {
                   5130:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   5131: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   5132:         }
                   5133:     }
                   5134:     my %submit_types = &substatus_options();
                   5135:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   5136: 
                   5137:     if ($env{'form.submitonly'} eq 'all') {
                   5138:         $result.= '<h3>'.$common_header.'</h3>';
                   5139:     } else {
1.745     raeburn  5140:         my $text;
                   5141:         if ($is_tool) {
                   5142:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5143:         } else {
                   5144:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5145:         }
                   5146:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 5147:     }
1.738     raeburn  5148:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       5149:     #radio buttons/text box for assigning points for a section or class.
                   5150:     #handles different parts of a problem
1.582     raeburn  5151:     my $res_error;
                   5152:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   5153:     if ($res_error) {
                   5154:         return &navmap_errormsg();
                   5155:     }
1.42      ng       5156:     my %weight = ();
                   5157:     my $ctsparts = 0;
1.45      ng       5158:     my %seen = ();
1.745     raeburn  5159:     my @part_response_id;
                   5160:     if ($is_tool) {
                   5161:         @part_response_id = ([0,'']);
                   5162:     } else {
                   5163:         @part_response_id = &flatten_responseType($responseType);
                   5164:     }
1.375     albertel 5165:     foreach my $part_response_id (@part_response_id) {
                   5166:     	my ($partid,$respid) = @{ $part_response_id };
                   5167: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       5168: 	next if $seen{$partid};
                   5169: 	$seen{$partid}++;
1.42      ng       5170: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   5171: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   5172: 
1.324     albertel 5173: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 5174: 	my $radio.='<table border="0"><tr>';  
1.41      ng       5175: 	my $ctr = 0;
1.42      ng       5176: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 5177: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 5178: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 5179: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       5180: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   5181: 	    $ctr++;
                   5182: 	}
1.485     albertel 5183: 	$radio.='</tr></table>';
                   5184: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   5185: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 5186: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  5187: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   5188:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   5189:             '<select name="SELVAL_'.$partid.'" '.
                   5190:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   5191:                 $weight{$partid}.')"> '.
1.401     albertel 5192: 	    '<option selected="selected"> </option>'.
1.485     albertel 5193: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   5194: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   5195: 	    '</select></td>'.
                   5196:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   5197: 	$line.='<input type="hidden" name="partid_'.
                   5198: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   5199: 	$line.='<input type="hidden" name="weight_'.
                   5200: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   5201: 
                   5202: 	$result.=
                   5203: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   5204: 	    '<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 5205: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       5206: 	$ctsparts++;
1.41      ng       5207:     }
1.474     albertel 5208:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 5209: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 5210:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   5211: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       5212: 
1.44      ng       5213:     #table listing all the students in a section/class
                   5214:     #header of table
1.738     raeburn  5215:     if ($env{'form.submitonly'} eq 'all') {
                   5216:         $result.= '<h3>'.$specific_header.'</h3>';
                   5217:     } else {
1.745     raeburn  5218:         my $text;
                   5219:         if ($is_tool) {
                   5220:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5221:         } else {
                   5222:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5223:         }
                   5224:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  5225:     }
                   5226:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  5227: 	      &Apache::loncommon::start_data_table_header_row().
                   5228: 	      '<th>'.&mt('No.').'</th>'.
                   5229: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  5230:     my $partserror;
                   5231:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5232:     if ($partserror) {
                   5233:         return &navmap_errormsg();
                   5234:     }
1.324     albertel 5235:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  5236:     my @partids = ();
1.41      ng       5237:     foreach my $part (@parts) {
1.745     raeburn  5238: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  5239:         my $narrowtext = &mt('Tries');
                   5240: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  5241: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 5242: 	my ($partid) = &split_part_type($part);
1.524     raeburn  5243:         push(@partids,$partid);
1.628     www      5244: #
                   5245: # FIXME: Looks like $display looks at English text
                   5246: #
1.324     albertel 5247: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       5248: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 5249: 	    $result.='<th>'.
1.697     bisitz   5250: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   5251: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       5252: 	    next;
1.485     albertel 5253: 	    
1.207     albertel 5254: 	} else {
1.485     albertel 5255: 	    if ($display =~ /Problem Status/) {
                   5256: 		my $grade_status_mt = &mt('Grade Status');
                   5257: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   5258: 	    }
                   5259: 	    my $part_mt = &mt('Part:');
                   5260: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       5261: 	}
1.485     albertel 5262: 
1.474     albertel 5263: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       5264:     }
1.474     albertel 5265:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       5266: 
1.270     albertel 5267:     my %last_resets = 
                   5268: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  5269: 
1.41      ng       5270:     #get info for each student
1.44      ng       5271:     #list all the students - with points and grade status
1.738     raeburn  5272:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       5273:     my $ctr = 0;
1.294     albertel 5274:     foreach (sort 
                   5275: 	     {
                   5276: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5277: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5278: 		 }
                   5279: 		 return $a cmp $b;
                   5280: 	     } (keys(%$fullname))) {
1.324     albertel 5281: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  5282: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       5283:     }
1.474     albertel 5284:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       5285:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.780     raeburn  5286:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5287: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  5288:     if ($ctr == 0) {
1.442     banghart 5289:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  5290:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   5291:                 '<span class="LC_warning">';
                   5292:         if ($env{'form.submitonly'} eq 'all') {
                   5293:             if (grep(/^all$/,@sections)) {
                   5294:                 if (grep(/^all$/,@groups)) {
                   5295:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   5296:                                    $stu_status);
                   5297:                 } elsif (grep(/^none$/,@groups)) {
                   5298:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   5299:                                    $stu_status); 
                   5300:                 } else {
                   5301:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5302:                                    $group_display,$stu_status);
                   5303:                 }
                   5304:             } elsif (grep(/^none$/,@sections)) {
                   5305:                 if (grep(/^all$/,@groups)) {
                   5306:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   5307:                                    $stu_status);
                   5308:                 } elsif (grep(/^none$/,@groups)) {
                   5309:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   5310:                                    $stu_status);
                   5311:                 } else {
                   5312:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5313:                                    $group_display,$stu_status);
                   5314:                 }
                   5315:             } else {
                   5316:                 if (grep(/^all$/,@groups)) {
                   5317:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   5318:                                    $section_display,$stu_status);
                   5319:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  5320:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  5321:                                    $section_display,$stu_status);
                   5322:                 } else {
                   5323:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   5324:                                    $section_display,$group_display,$stu_status);
                   5325:                 }
                   5326:             }
                   5327:         } else {
                   5328:             if (grep(/^all$/,@sections)) {
                   5329:                 if (grep(/^all$/,@groups)) {
                   5330:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5331:                                    $stu_status,$submission_status);
                   5332:                 } elsif (grep(/^none$/,@groups)) {
                   5333:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5334:                                    $stu_status,$submission_status);
                   5335:                 } else {
                   5336:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5337:                                    $group_display,$stu_status,$submission_status);
                   5338:                 }
                   5339:             } elsif (grep(/^none$/,@sections)) {
                   5340:                 if (grep(/^all$/,@groups)) {
                   5341:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5342:                                    $stu_status,$submission_status);
                   5343:                 } elsif (grep(/^none$/,@groups)) {
                   5344:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5345:                                    $stu_status,$submission_status);
                   5346:                 } else {
                   5347:                     $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.',
                   5348:                                    $group_display,$stu_status,$submission_status);
                   5349:                 }
                   5350:             } else {
                   5351:                 if (grep(/^all$/,@groups)) {
                   5352: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5353: 	                           $section_display,$stu_status,$submission_status);
                   5354:                 } elsif (grep(/^none$/,@groups)) {
                   5355:                     $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.',
                   5356:                                    $section_display,$stu_status,$submission_status);
                   5357:                 } else {
                   5358:                     $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.',
                   5359:                                    $section_display,$group_display,$stu_status,$submission_status);
                   5360:                 }
                   5361:             }
                   5362:         }
                   5363: 	$result .= '</span><br />';
1.96      albertel 5364:     }
1.41      ng       5365:     return $result;
                   5366: }
                   5367: 
1.738     raeburn  5368: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       5369: sub viewstudentgrade {
1.745     raeburn  5370:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       5371:     my ($uname,$udom) = split(/:/,$student);
                   5372:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  5373:     my $submitonly = $env{'form.submitonly'};
                   5374:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   5375:         my %partstatus = ();
                   5376:         if (ref($parts) eq 'ARRAY') {
                   5377:             foreach my $apart (@{$parts}) {
                   5378:                 my ($part,$type) = &split_part_type($apart);
                   5379:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   5380:                 $status = 'nothing' if ($status eq '');
                   5381:                 $partstatus{$part}      = $status;
                   5382:                 my $subkey = "resource.$part.submitted_by";
                   5383:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   5384:             }
                   5385:             my $submitted = 0;
                   5386:             my $graded = 0;
                   5387:             my $incorrect = 0;
                   5388:             foreach my $key (keys(%partstatus)) {
                   5389:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   5390:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   5391:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   5392: 
                   5393:                 my $partid = (split(/\./,$key))[1];
                   5394:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   5395:                     $submitted = 0;
                   5396:                 }
                   5397:             }
                   5398:             return if (!$submitted && ($submitonly eq 'yes' ||
                   5399:                                        $submitonly eq 'incorrect' ||
                   5400:                                        $submitonly eq 'graded'));
                   5401:             return if (!$graded && ($submitonly eq 'graded'));
                   5402:             return if (!$incorrect && $submitonly eq 'incorrect');
                   5403:         }
                   5404:     }
                   5405:     if ($submitonly eq 'queued') {
                   5406:         my ($cdom,$cnum) = split(/_/,$courseid);
                   5407:         my %queue_status =
                   5408:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   5409:                                                     $udom,$uname);
                   5410:         return if (!defined($queue_status{'gradingqueue'}));
                   5411:     }
                   5412:     $$ctr++;
                   5413:     my %aggregates = ();
1.474     albertel 5414:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  5415: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   5416: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       5417: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 5418: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 5419: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 5420:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 5421:     foreach my $apart (@$parts) {
                   5422: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       5423: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 5424:         $result.='<td align="center">';
1.269     raeburn  5425:         my ($aggtries,$totaltries);
                   5426:         unless (exists($aggregates{$part})) {
1.270     albertel 5427: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   5428: 	    $aggtries = $totaltries;
1.269     raeburn  5429:             if ($$last_resets{$part}) {  
1.270     albertel 5430:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   5431: 					   $part);
                   5432:             }
1.269     raeburn  5433:             $result.='<input type="hidden" name="'.
                   5434:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   5435:             $result.='<input type="hidden" name="'.
                   5436:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   5437:             $aggregates{$part} = 1;
                   5438:         }
1.41      ng       5439: 	if ($type eq 'awarded') {
1.320     albertel 5440: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       5441: 	    $result.='<input type="hidden" name="'.
1.89      albertel 5442: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 5443: 	    $result.='<input type="text" name="'.
1.89      albertel 5444: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   5445:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       5446: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       5447: 	} elsif ($type eq 'solved') {
                   5448: 	    my ($status,$foo)=split(/_/,$score,2);
                   5449: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 5450: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 5451: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 5452: 	    $result.='&nbsp;<select name="'.
1.89      albertel 5453: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   5454:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 5455: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   5456: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   5457: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       5458: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       5459: 	} else {
                   5460: 	    $result.='<input type="hidden" name="'.
                   5461: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   5462: 		    "\n";
1.233     albertel 5463: 	    $result.='<input type="text" name="'.
1.122     ng       5464: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   5465: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       5466: 	}
                   5467:     }
1.474     albertel 5468:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       5469:     return $result;
1.38      ng       5470: }
                   5471: 
1.44      ng       5472: #--- change scores for all the students in a section/class
                   5473: #    record does not get update if unchanged
1.38      ng       5474: sub editgrades {
1.608     www      5475:     my ($request,$symb) = @_;
1.745     raeburn  5476:     my $toolsymb;
                   5477:     if ($symb =~ /ext\.tool$/) {
                   5478:         $toolsymb = $symb;
                   5479:     }
1.41      ng       5480: 
1.433     banghart 5481:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 5482:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  5483:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       5484: 
1.477     albertel 5485:     my $result= &Apache::loncommon::start_data_table().
                   5486: 	&Apache::loncommon::start_data_table_header_row().
                   5487: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   5488: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       5489:     my %scoreptr = (
                   5490: 		    'correct'  =>'correct_by_override',
                   5491: 		    'incorrect'=>'incorrect_by_override',
                   5492: 		    'excused'  =>'excused',
                   5493: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  5494:                     'credited' =>'credit_attempted',
1.43      ng       5495: 		    'nothing'  => '',
                   5496: 		    );
1.257     albertel 5497:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       5498: 
1.798     raeburn  5499:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5500:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5501:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   5502: 
1.44      ng       5503:     my (@partid);
                   5504:     my %weight = ();
1.54      albertel 5505:     my %columns = ();
1.44      ng       5506:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 5507: 
1.582     raeburn  5508:     my $partserror;
                   5509:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5510:     if ($partserror) {
                   5511:         return &navmap_errormsg();
                   5512:     }
1.54      albertel 5513:     my $header;
1.257     albertel 5514:     while ($ctr < $env{'form.totalparts'}) {
                   5515: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  5516: 	push(@partid,$partid);
1.257     albertel 5517: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       5518: 	$ctr++;
1.54      albertel 5519:     }
1.324     albertel 5520:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  5521:     my $totcolspan = 0;
1.54      albertel 5522:     foreach my $partid (@partid) {
1.478     albertel 5523: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   5524: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 5525: 	$columns{$partid}=2;
                   5526: 	foreach my $stores (@parts) {
                   5527: 	    my ($part,$type) = &split_part_type($stores);
                   5528: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   5529: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  5530: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  5531: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  5532:             my $narrowtext = &mt('Tries');
                   5533: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   5534: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   5535: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 5536: 	    $columns{$partid}+=2;
                   5537: 	}
1.748     raeburn  5538:         $totcolspan += $columns{$partid};
1.54      albertel 5539:     }
                   5540:     foreach my $partid (@partid) {
1.324     albertel 5541: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 5542: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   5543: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   5544: 	    '</th>';
1.54      albertel 5545: 
1.44      ng       5546:     }
1.477     albertel 5547:     $result .= &Apache::loncommon::end_data_table_header_row().
                   5548: 	&Apache::loncommon::start_data_table_header_row().
                   5549: 	$header.
                   5550: 	&Apache::loncommon::end_data_table_header_row();
                   5551:     my @noupdate;
1.126     ng       5552:     my ($updateCtr,$noupdateCtr) = (1,1);
1.798     raeburn  5553:     my ($got_types,%queueable,%pbsave,%skip_passback);
1.257     albertel 5554:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   5555: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 5556: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       5557: 	my %newrecord;
                   5558: 	my $updateflag = 0;
1.108     albertel 5559: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  5560: 	my $canmodify = &canmodify($usec);
                   5561: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   5562: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   5563: 	if (!$canmodify) {
1.477     albertel 5564: 	    push(@noupdate,
1.748     raeburn  5565: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   5566: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 5567: 	    next;
                   5568: 	}
1.269     raeburn  5569:         my %aggregate = ();
                   5570:         my $aggregateflag = 0;
1.281     albertel 5571: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.798     raeburn  5572:         my (%weights,%awardeds,%excuseds);
1.44      ng       5573: 	foreach (@partid) {
1.257     albertel 5574: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 5575: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   5576: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 5577: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   5578: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 5579: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   5580: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.798     raeburn  5581:             $awardeds{$symb}{$_} = $partial;
1.44      ng       5582: 	    my $score;
                   5583: 	    if ($partial eq '') {
1.257     albertel 5584: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       5585: 	    } elsif ($partial > 0) {
                   5586: 		$score = 'correct_by_override';
                   5587: 	    } elsif ($partial == 0) {
                   5588: 		$score = 'incorrect_by_override';
                   5589: 	    }
1.257     albertel 5590: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       5591: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   5592: 
1.292     albertel 5593: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   5594: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5595: 	    if ($dropMenu eq 'reset status' &&
                   5596: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 5597: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       5598: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   5599: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 5600: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       5601: 		$updateflag = 1;
1.269     raeburn  5602:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   5603:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   5604:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   5605:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   5606:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5607:                     $aggregateflag = 1;
                   5608:                 }
1.139     albertel 5609: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   5610: 		$updateflag = 1;
                   5611: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   5612: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   5613: 		$rec_update++;
1.125     ng       5614: 	    }
                   5615: 
1.93      albertel 5616: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       5617: 		'<td align="center">'.$awarded.
                   5618: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 5619: 
1.54      albertel 5620: 
                   5621: 	    my $partid=$_;
1.798     raeburn  5622:             if ($score eq 'excused') {
                   5623:                 $excuseds{$symb}{$partid} = 1;
                   5624:             } else {
                   5625:                 $excuseds{$symb}{$partid} = '';
                   5626:             }
1.54      albertel 5627: 	    foreach my $stores (@parts) {
                   5628: 		my ($part,$type) = &split_part_type($stores);
                   5629: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   5630: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 5631: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   5632: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 5633: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   5634: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 5635: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 5636: 		    $updateflag=1;
                   5637: 		}
1.93      albertel 5638: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 5639: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   5640: 	    }
1.44      ng       5641: 	}
1.477     albertel 5642: 	$line.="\n";
1.301     albertel 5643: 
1.44      ng       5644: 	if ($updateflag) {
                   5645: 	    $count++;
1.257     albertel 5646: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 5647: 				    $udom,$uname);
1.301     albertel 5648: 
                   5649: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   5650: 					      $cnum,$udom,$uname)) {
                   5651: 		# need to figure out if should be in queue.
                   5652: 		my %record =  
                   5653: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   5654: 					     $udom,$uname);
                   5655: 		my $all_graded = 1;
                   5656: 		my $none_graded = 1;
1.786     raeburn  5657:                 unless ($got_types) {
                   5658:                     my $error;
                   5659:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   5660:                     unless ($error) {
                   5661:                         foreach my $part (@parts) {
                   5662:                             if (ref($resptype->{$part}) eq 'HASH') {
                   5663:                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   5664:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   5665:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   5666:                                         $queueable{$part} = 1;
                   5667:                                         last;
                   5668:                                     }
                   5669:                                 }
                   5670:                             }
                   5671:                         }
                   5672:                     }
                   5673:                     $got_types = 1;
                   5674:                 }
1.301     albertel 5675: 		foreach my $part (@parts) {
1.786     raeburn  5676:                     if ($queueable{$part}) {
                   5677: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   5678: 			    $all_graded = 0;
                   5679: 		        } else {
                   5680: 			    $none_graded = 0;
                   5681: 		        }
1.301     albertel 5682: 		    }
1.786     raeburn  5683:                 }
1.301     albertel 5684: 		if ($all_graded || $none_graded) {
                   5685: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   5686: 							   $symb,$cdom,$cnum,
                   5687: 							   $udom,$uname);
                   5688: 		}
                   5689: 	    }
                   5690: 
1.477     albertel 5691: 	    $result.=&Apache::loncommon::start_data_table_row().
                   5692: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   5693: 		&Apache::loncommon::end_data_table_row();
1.126     ng       5694: 	    $updateCtr++;
1.798     raeburn  5695:             if (keys(%needpb)) {
                   5696:                 $weights{$symb} = \%weight;
1.802     raeburn  5697:                 &process_passbacks('editgrades',[$symb],$cdom,$cnum,$udom,$uname,$usec,\%weights,
1.798     raeburn  5698:                                    \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   5699:             }
1.93      albertel 5700: 	} else {
1.477     albertel 5701: 	    push(@noupdate,
                   5702: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       5703: 	    $noupdateCtr++;
1.44      ng       5704: 	}
1.269     raeburn  5705:         if ($aggregateflag) {
                   5706:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 5707: 				  $cdom,$cnum);
1.269     raeburn  5708:         }
1.93      albertel 5709:     }
1.477     albertel 5710:     if (@noupdate) {
1.748     raeburn  5711:         my $numcols=$totcolspan+2;
1.477     albertel 5712: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 5713: 	    '<td align="center" colspan="'.$numcols.'">'.
                   5714: 	    &mt('No Changes Occurred For the Students Below').
                   5715: 	    '</td>'.
1.477     albertel 5716: 	    &Apache::loncommon::end_data_table_row();
                   5717: 	foreach my $line (@noupdate) {
                   5718: 	    $result.=
                   5719: 		&Apache::loncommon::start_data_table_row().
                   5720: 		$line.
                   5721: 		&Apache::loncommon::end_data_table_row();
                   5722: 	}
1.44      ng       5723:     }
1.614     www      5724:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 5725:     my $msg = '<p><b>'.
                   5726: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   5727: 	    $rec_update,$count).'</b><br />'.
                   5728: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   5729: 	'</b></p>';
1.44      ng       5730:     return $title.$msg.$result;
1.5       albertel 5731: }
1.54      albertel 5732: 
                   5733: sub split_part_type {
                   5734:     my ($partstr) = @_;
                   5735:     my ($temp,@allparts)=split(/_/,$partstr);
                   5736:     my $type=pop(@allparts);
1.439     albertel 5737:     my $part=join('_',@allparts);
1.54      albertel 5738:     return ($part,$type);
                   5739: }
                   5740: 
1.44      ng       5741: #------------- end of section for handling grading by section/class ---------
                   5742: #
                   5743: #----------------------------------------------------------------------------
                   5744: 
1.5       albertel 5745: 
1.44      ng       5746: #----------------------------------------------------------------------------
                   5747: #
                   5748: #-------------------------- Next few routines handles grading by csv upload
                   5749: #
                   5750: #--- Javascript to handle csv upload
1.27      albertel 5751: sub csvupload_javascript_reverse_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 (i==0 && tw!=0) { foundID=1; }
                   5765:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  5766:       if (i==2 && tw!=0) { foundclicker=1; }
                   5767:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 5768:     }
1.743     raeburn  5769:     if (founduname==0 && foundID==0 && foundclicker==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:     for (i=0;i<=vf.nfields.value;i++) {
                   5783:       //can not pick the same destination field for both name and domain
                   5784:       if (((i ==0)||(i ==1)) && 
                   5785:           ((tf==0)||(tf==1)) && 
                   5786:           (i!=tf) &&
                   5787:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5788:         eval('vf.f'+i+'.selectedIndex=0;')
                   5789:       }
                   5790:     }
                   5791:   }
                   5792: ENDPICK
                   5793: }
                   5794: 
                   5795: sub csvupload_javascript_forward_associate {
1.743     raeburn  5796:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5797:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5798:   &js_escape(\$error1);
                   5799:   &js_escape(\$error2);
1.27      albertel 5800:   return(<<ENDPICK);
                   5801:   function verify(vf) {
                   5802:     var foundsomething=0;
                   5803:     var founduname=0;
1.243     albertel 5804:     var foundID=0;
1.743     raeburn  5805:     var foundclicker=0;
1.27      albertel 5806:     for (i=0;i<=vf.nfields.value;i++) {
                   5807:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5808:       if (tw==1) { foundID=1; }
                   5809:       if (tw==2) { founduname=1; }
1.745     raeburn  5810:       if (tw==3) { foundclicker=1; }
1.743     raeburn  5811:       if (tw>4) { foundsomething=1; }
1.27      albertel 5812:     }
1.743     raeburn  5813:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 5814: 	alert('$error1');
                   5815: 	return;
1.27      albertel 5816:     }
                   5817:     if (foundsomething==0) {
1.246     albertel 5818: 	alert('$error2');
                   5819: 	return;
1.27      albertel 5820:     }
                   5821:     vf.submit();
                   5822:   }
                   5823:   function flip(vf,tf) {
                   5824:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5825:     var i;
                   5826:     //can not pick the same destination field twice
                   5827:     for (i=0;i<=vf.nfields.value;i++) {
                   5828:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5829:         eval('vf.f'+i+'.selectedIndex=0;')
                   5830:       }
                   5831:     }
                   5832:   }
                   5833: ENDPICK
                   5834: }
                   5835: 
1.26      albertel 5836: sub csvuploadmap_header {
1.324     albertel 5837:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       5838:     my $javascript;
1.257     albertel 5839:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       5840: 	$javascript=&csvupload_javascript_reverse_associate();
                   5841:     } else {
                   5842: 	$javascript=&csvupload_javascript_forward_associate();
                   5843:     }
1.45      ng       5844: 
1.418     albertel 5845:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      5846:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   5847:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   5848:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   5849:     my $reverse=&mt("Reverse Association");
1.41      ng       5850:     $request->print(<<ENDPICK);
1.632     www      5851: <br />
                   5852: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 5853: <input type="hidden" name="associate"  value="" />
                   5854: <input type="hidden" name="phase"      value="three" />
                   5855: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 5856: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   5857: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 5858: <input type="hidden" name="upfile_associate" 
1.257     albertel 5859:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 5860: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 5861: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 5862: <hr />
                   5863: ENDPICK
1.597     wenzelju 5864:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       5865:     return '';
1.26      albertel 5866: 
                   5867: }
                   5868: 
                   5869: sub csvupload_fields {
1.582     raeburn  5870:     my ($symb,$errorref) = @_;
1.745     raeburn  5871:     my $toolsymb;
                   5872:     if ($symb =~ /ext\.tool$/) {
                   5873:         $toolsymb = $symb;
                   5874:     }
1.582     raeburn  5875:     my (@parts) = &getpartlist($symb,$errorref);
                   5876:     if (ref($errorref)) {
                   5877:         if ($$errorref) {
                   5878:             return;
                   5879:         }
                   5880:     }
                   5881: 
1.556     weissno  5882:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 5883: 		['username','Student Username'],
1.743     raeburn  5884: 		['clicker','Clicker ID'],
1.243     albertel 5885: 		['domain','Student Domain']);
1.324     albertel 5886:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       5887:     foreach my $part (sort(@parts)) {
                   5888: 	my @datum;
1.745     raeburn  5889: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       5890: 	my $name=$part;
1.745     raeburn  5891: 	if (!$display) { $display = $name; }
1.41      ng       5892: 	@datum=($name,$display);
1.244     albertel 5893: 	if ($name=~/^stores_(.*)_awarded/) {
                   5894: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   5895: 	}
1.41      ng       5896: 	push(@fields,\@datum);
                   5897:     }
                   5898:     return (@fields);
1.26      albertel 5899: }
                   5900: 
                   5901: sub csvuploadmap_footer {
1.41      ng       5902:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   5903:     my $buttontext = &mt('Assign Grades');
1.41      ng       5904:     $request->print(<<ENDPICK);
1.26      albertel 5905: </table>
                   5906: <input type="hidden" name="nfields" value="$i" />
                   5907: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   5908: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 5909: </form>
                   5910: ENDPICK
                   5911: }
                   5912: 
1.283     albertel 5913: sub checkforfile_js {
1.638     www      5914:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  5915:     &js_escape(\$alertmsg);
1.597     wenzelju 5916:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       5917:     function checkUpload(formname) {
                   5918: 	if (formname.upfile.value == "") {
1.539     riegler  5919: 	    alert("$alertmsg");
1.86      ng       5920: 	    return false;
                   5921: 	}
                   5922: 	formname.submit();
                   5923:     }
                   5924: CSVFORMJS
1.283     albertel 5925:     return $result;
                   5926: }
                   5927: 
                   5928: sub upcsvScores_form {
1.608     www      5929:     my ($request,$symb) = @_;
1.283     albertel 5930:     if (!$symb) {return '';}
                   5931:     my $result=&checkforfile_js();
1.632     www      5932:     $result.=&Apache::loncommon::start_data_table().
                   5933:              &Apache::loncommon::start_data_table_header_row().
                   5934:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   5935:              &Apache::loncommon::end_data_table_header_row().
                   5936:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      5937:     my $upload=&mt("Upload Scores");
1.86      ng       5938:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 5939:     my $ignore=&mt('Ignore First Line');
1.418     albertel 5940:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       5941:     $result.=<<ENDUPFORM;
1.106     albertel 5942: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       5943: <input type="hidden" name="symb" value="$symb" />
                   5944: <input type="hidden" name="command" value="csvuploadmap" />
                   5945: $upfile_select
1.589     bisitz   5946: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       5947: </form>
                   5948: ENDUPFORM
1.370     www      5949:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      5950:                            &mt("How do I create a CSV file from a spreadsheet")).
                   5951:              '</td>'.
                   5952:             &Apache::loncommon::end_data_table_row().
                   5953:             &Apache::loncommon::end_data_table();
1.86      ng       5954:     return $result;
                   5955: }
                   5956: 
                   5957: 
1.26      albertel 5958: sub csvuploadmap {
1.768     raeburn  5959:     my ($request,$symb) = @_;
1.41      ng       5960:     if (!$symb) {return '';}
1.72      ng       5961: 
1.41      ng       5962:     my $datatoken;
1.257     albertel 5963:     if (!$env{'form.datatoken'}) {
1.41      ng       5964: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 5965:     } else {
1.742     raeburn  5966: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5967:         if ($datatoken ne '') {
                   5968: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5969:         }
1.26      albertel 5970:     }
1.41      ng       5971:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 5972:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       5973:     my ($i,$keyfields);
                   5974:     if (@records) {
1.582     raeburn  5975:         my $fieldserror;
                   5976: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   5977:         if ($fieldserror) {
                   5978:             $request->print(&navmap_errormsg());
                   5979:             return;
                   5980:         }
1.257     albertel 5981: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       5982: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   5983: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   5984: 							  \@fields);
                   5985: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   5986: 	    chop($keyfields);
                   5987: 	} else {
                   5988: 	    unshift(@fields,['none','']);
                   5989: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   5990: 							    \@fields);
1.311     banghart 5991:             foreach my $rec (@records) {
                   5992:                 my %temp = &Apache::loncommon::record_sep($rec);
                   5993:                 if (%temp) {
                   5994:                     $keyfields=join(',',sort(keys(%temp)));
                   5995:                     last;
                   5996:                 }
                   5997:             }
1.41      ng       5998: 	}
                   5999:     }
                   6000:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       6001: 
1.41      ng       6002:     return '';
1.27      albertel 6003: }
                   6004: 
1.246     albertel 6005: sub csvuploadoptions {
1.608     www      6006:     my ($request,$symb)= @_;
1.632     www      6007:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 6008:     $request->print(<<ENDPICK);
                   6009: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   6010: <input type="hidden" name="command"    value="csvuploadassign" />
                   6011: <p>
                   6012: <label>
                   6013:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      6014:    $overwrite
1.246     albertel 6015: </label>
                   6016: </p>
                   6017: ENDPICK
                   6018:     my %fields=&get_fields();
                   6019:     if (!defined($fields{'domain'})) {
1.257     albertel 6020: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      6021: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 6022:     }
1.257     albertel 6023:     foreach my $key (sort(keys(%env))) {
1.246     albertel 6024: 	if ($key !~ /^form\.(.*)$/) { next; }
                   6025: 	my $cleankey=$1;
                   6026: 	if ($cleankey eq 'command') { next; }
                   6027: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 6028: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 6029:     }
                   6030:     # FIXME do a check for any duplicated user ids...
                   6031:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   6032:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 6033: <hr /></form>'."\n");
1.246     albertel 6034:     return '';
                   6035: }
                   6036: 
                   6037: sub get_fields {
                   6038:     my %fields;
1.257     albertel 6039:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   6040:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   6041: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   6042: 	    if ($env{'form.f'.$i} ne 'none') {
                   6043: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       6044: 	    }
                   6045: 	} else {
1.257     albertel 6046: 	    if ($env{'form.f'.$i} ne 'none') {
                   6047: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       6048: 	    }
                   6049: 	}
1.27      albertel 6050:     }
1.246     albertel 6051:     return %fields;
                   6052: }
                   6053: 
                   6054: sub csvuploadassign {
1.766     raeburn  6055:     my ($request,$symb) = @_;
1.246     albertel 6056:     if (!$symb) {return '';}
1.345     bowersj2 6057:     my $error_msg = '';
1.742     raeburn  6058:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   6059:     if ($datatoken ne '') { 
                   6060:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   6061:     }
1.246     albertel 6062:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   6063:     my %fields=&get_fields();
1.257     albertel 6064:     my $courseid=$env{'request.course.id'};
1.798     raeburn  6065:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6066:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.97      albertel 6067:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 6068:     my @notallowed;
1.41      ng       6069:     my @skipped;
1.657     raeburn  6070:     my @warnings;
1.41      ng       6071:     my $countdone=0;
1.798     raeburn  6072:     my @parts;
                   6073:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   6074:     my $passback;
                   6075:     if (keys(%needpb)) {
                   6076:         $passback = 1;
                   6077:         my $navmap = Apache::lonnavmaps::navmap->new();
                   6078:         if (ref($navmap)) {
                   6079:             my $res = $navmap->getBySymb($symb);
                   6080:             if (ref($res)) {
                   6081:                 my $partlist = $res->parts();
                   6082:                 if (ref($partlist) eq 'ARRAY') {
                   6083:                     @parts = sort(@{$partlist});
                   6084:                 }
                   6085:             }
                   6086:         } else {
                   6087:             return &navmap_errormsg();
                   6088:         }
                   6089:     }
                   6090:     my (%skip_passback,%pbsave,%weights,%awardeds,%excuseds);
                   6091: 
1.41      ng       6092:     foreach my $grade (@gradedata) {
                   6093: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 6094: 	my $domain;
                   6095: 	if ($entries{$fields{'domain'}}) {
                   6096: 	    $domain=$entries{$fields{'domain'}};
                   6097: 	} else {
1.257     albertel 6098: 	    $domain=$env{'form.default_domain'};
1.246     albertel 6099: 	}
1.243     albertel 6100: 	$domain=~s/\s//g;
1.41      ng       6101: 	my $username=$entries{$fields{'username'}};
1.160     albertel 6102: 	$username=~s/\s//g;
1.243     albertel 6103: 	if (!$username) {
                   6104: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 6105: 	    $id=~s/\s//g;
1.737     raeburn  6106:             if ($id ne '') {
                   6107: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   6108: 	        $username=$ids{$id};
                   6109:             } else {
                   6110:                 if ($entries{$fields{'clicker'}}) {
                   6111:                     my $clicker = $entries{$fields{'clicker'}};
                   6112:                     $clicker=~s/\s//g;
                   6113:                     if ($clicker ne '') {
                   6114:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   6115:                         if ($clickers{$clicker} ne '') {  
                   6116:                             my $match = 0;
                   6117:                             my @inclass;
                   6118:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   6119:                                 if (exists($$classlist{"$poss:$domain"})) {
                   6120:                                     $username = $poss;
                   6121:                                     push(@inclass,$poss);
                   6122:                                     $match ++;
                   6123:                                     
                   6124:                                 }
                   6125:                             }
                   6126:                             if ($match > 1) {
                   6127:                                 undef($username); 
                   6128:                                 $request->print('<p class="LC_warning">'.
                   6129:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   6130:                                                 $clicker,join(', ',@inclass)).'</p>');
                   6131:                             }
                   6132:                         }
                   6133:                     }
                   6134:                 }
                   6135:             }
1.243     albertel 6136: 	}
1.41      ng       6137: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 6138: 	    my $id=$entries{$fields{'ID'}};
                   6139: 	    $id=~s/\s//g;
1.737     raeburn  6140:             my $clicker = $entries{$fields{'clicker'}};
                   6141:             $clicker=~s/\s//g;
                   6142:             if ($clicker) {
                   6143:                 push(@skipped,"$clicker:$domain");
                   6144: 	    } elsif ($id) {
1.247     albertel 6145: 		push(@skipped,"$id:$domain");
                   6146: 	    } else {
                   6147: 		push(@skipped,"$username:$domain");
                   6148: 	    }
1.41      ng       6149: 	    next;
                   6150: 	}
1.108     albertel 6151: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 6152: 	if (!&canmodify($usec)) {
                   6153: 	    push(@notallowed,"$username:$domain");
                   6154: 	    next;
                   6155: 	}
1.244     albertel 6156: 	my %points;
1.41      ng       6157: 	my %grades;
                   6158: 	foreach my $dest (keys(%fields)) {
1.244     albertel 6159: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   6160: 		$dest eq 'domain') { next; }
                   6161: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   6162: 	    if ($dest=~/stores_(.*)_points/) {
                   6163: 		my $part=$1;
                   6164: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6165: 					      $symb,$domain,$username);
1.798     raeburn  6166:                 $weights{$symb}{$part} = $wgt;
1.345     bowersj2 6167:                 if ($wgt) {
                   6168:                     $entries{$fields{$dest}}=~s/\s//g;
                   6169:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.798     raeburn  6170:                     if ($passback) {
                   6171:                         $awardeds{$symb}{$part} = $pcr;
                   6172:                         $excuseds{$symb}{$part} = '';
                   6173:                     }
1.463     albertel 6174:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   6175:                                           : 'correct_by_override';
1.638     www      6176:                     if ($pcr>1) {
1.657     raeburn  6177:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      6178:                     }
1.345     bowersj2 6179:                     $grades{"resource.$part.awarded"}=$pcr;
                   6180:                     $grades{"resource.$part.solved"}=$award;
                   6181:                     $points{$part}=1;
                   6182:                 } else {
                   6183:                     $error_msg = "<br />" .
                   6184:                         &mt("Some point values were assigned"
                   6185:                             ." for problems with a weight "
                   6186:                             ."of zero. These values were "
                   6187:                             ."ignored.");
                   6188:                 }
1.244     albertel 6189: 	    } else {
                   6190: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   6191: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   6192: 		my $store_key=$dest;
1.798     raeburn  6193:                 if ($passback) {
                   6194:                     if ($store_key=~/stores_(.*)_(awarded|solved)/) {
                   6195:                         my ($part,$key) = ($1,$2);
                   6196:                         unless ((ref($weights{$symb}) eq 'HASH') && (exists($weights{$symb}{$part}))) {
                   6197:                             $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6198:                                                                           $symb,$domain,$username);
                   6199:                         }
                   6200:                         if ($key eq 'awarded') {
                   6201:                             $awardeds{$symb}{$part} = $entries{$fields{$dest}};
                   6202:                         } elsif ($key eq 'solved') {
                   6203:                             if ($entries{$fields{$dest}} =~ /^excused/) {
                   6204:                                 $excuseds{$symb}{$part} = 1;
                   6205:                             }
                   6206:                         }
                   6207:                     }
                   6208:                 }
1.244     albertel 6209: 		$store_key=~s/^stores/resource/;
                   6210: 		$store_key=~s/_/\./g;
                   6211: 		$grades{$store_key}=$entries{$fields{$dest}};
                   6212: 	    }
1.41      ng       6213: 	}
1.766     raeburn  6214: 	if (! %grades) {
1.508     www      6215:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   6216:         } else {
                   6217: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   6218: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 6219: 					   $env{'request.course.id'},
                   6220: 					   $domain,$username);
1.508     www      6221: 	   if ($result eq 'ok') {
1.627     www      6222: # Successfully stored
1.508     www      6223: 	      $request->print('.');
1.627     www      6224: # Remove from grading queue
1.798     raeburn  6225:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,$cnum,
1.801     raeburn  6226: 						     $domain,$username);
1.627     www      6227:               $countdone++;
1.798     raeburn  6228:               if ($passback) {
                   6229:                   my @parts_in_upload;
                   6230:                   if (ref($weights{$symb}) eq 'HASH') {
                   6231:                       @parts_in_upload = sort(keys(%{$weights{$symb}}));
                   6232:                   }
                   6233:                   my @diffs = &Apache::loncommon::compare_arrays(\@parts_in_upload,\@parts);
                   6234:                   if (@diffs > 0) {
                   6235:                       my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$username);
                   6236:                       foreach my $part (@parts) {
                   6237:                           next if (grep(/^\Q$part\E$/,@parts_in_upload));
                   6238:                           $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6239:                                                                         $symb,$domain,$username);
                   6240:                           if ($record{"resource.$part.solved"} =~/^excused/) {
                   6241:                               $excuseds{$symb}{$part} = 1;
                   6242:                           } else {
                   6243:                               $excuseds{$symb}{$part} = '';
                   6244:                           }
                   6245:                           $awardeds{$symb}{$part} = $record{"resource.$part.awarded"};
                   6246:                       }
                   6247:                   }
1.802     raeburn  6248:                   &process_passbacks('csvupload',[$symb],$cdom,$cnum,$domain,$username,$usec,\%weights,
1.798     raeburn  6249:                                      \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   6250:               }
1.627     www      6251:            } else {
1.508     www      6252: 	      $request->print("<p><span class=\"LC_error\">".
                   6253:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   6254:                                   "$username:$domain",$result)."</span></p>");
                   6255: 	   }
                   6256: 	   $request->rflush();
                   6257:         }
1.41      ng       6258:     }
1.570     www      6259:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  6260:     if (@warnings) {
                   6261:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   6262:         $request->print(join(', ',@warnings));
                   6263:     }
1.41      ng       6264:     if (@skipped) {
1.571     www      6265: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   6266:         $request->print(join(', ',@skipped));
1.106     albertel 6267:     }
                   6268:     if (@notallowed) {
1.571     www      6269: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   6270: 	$request->print(join(', ',@notallowed));
1.41      ng       6271:     }
1.106     albertel 6272:     $request->print("<br />\n");
1.345     bowersj2 6273:     return $error_msg;
1.26      albertel 6274: }
1.44      ng       6275: #------------- end of section for handling csv file upload ---------
                   6276: #
                   6277: #-------------------------------------------------------------------
                   6278: #
1.122     ng       6279: #-------------- Next few routines handle grading by page/sequence
1.72      ng       6280: #
                   6281: #--- Select a page/sequence and a student to grade
1.68      ng       6282: sub pickStudentPage {
1.608     www      6283:     my ($request,$symb) = @_;
1.68      ng       6284: 
1.539     riegler  6285:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  6286:     &js_escape(\$alertmsg);
1.597     wenzelju 6287:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       6288: 
                   6289: function checkPickOne(formname) {
1.76      ng       6290:     if (radioSelection(formname.student) == null) {
1.539     riegler  6291: 	alert("$alertmsg");
1.68      ng       6292: 	return;
                   6293:     }
1.125     ng       6294:     ptr = pullDownSelection(formname.selectpage);
                   6295:     formname.page.value = formname["page"+ptr].value;
                   6296:     formname.title.value = formname["title"+ptr].value;
1.68      ng       6297:     formname.submit();
                   6298: }
                   6299: 
                   6300: LISTJAVASCRIPT
1.118     ng       6301:     &commonJSfunctions($request);
1.608     www      6302: 
1.257     albertel 6303:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6304:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6305:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  6306:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       6307: 
1.398     albertel 6308:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 6309: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       6310: 
1.80      ng       6311:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  6312:     my $map_error;
                   6313:     my ($titles,$symbx) = &getSymbMap($map_error);
                   6314:     if ($map_error) {
                   6315:         $request->print(&navmap_errormsg());
                   6316:         return; 
                   6317:     }
1.137     albertel 6318:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   6319: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   6320: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   6321: 
                   6322:     # Collection of hidden fields
1.70      ng       6323:     my $ctr=0;
1.68      ng       6324:     foreach (@$titles) {
1.700     bisitz   6325:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   6326:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   6327:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   6328:         $ctr++;
1.68      ng       6329:     }
1.700     bisitz   6330:     $result.='<input type="hidden" name="page" />'."\n".
                   6331:         '<input type="hidden" name="title" />'."\n";
                   6332: 
                   6333:     $result.=&build_section_inputs();
                   6334:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   6335:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   6336: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   6337: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 6338: 
1.700     bisitz   6339:     # Show grading options
                   6340:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   6341:     my $select = '<select name="selectpage">'."\n";
1.70      ng       6342:     $ctr=0;
                   6343:     foreach (@$titles) {
                   6344: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   6345: 	$select.='<option value="'.$ctr.'"'.
                   6346: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   6347: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       6348: 	$ctr++;
                   6349:     }
1.700     bisitz   6350:     $select.= '</select>';
1.68      ng       6351: 
1.700     bisitz   6352:     $result.=
                   6353:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   6354:        .$select
                   6355:        .&Apache::lonhtmlcommon::row_closure();
                   6356: 
                   6357:     $result.=
                   6358:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   6359:        .'<label><input type="radio" name="vProb" value="no"'
                   6360:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   6361:        .'<label><input type="radio" name="vProb" value="yes" />'
                   6362:            .&mt('yes').'</label>'."\n"
                   6363:        .&Apache::lonhtmlcommon::row_closure();
                   6364: 
                   6365:     $result.=
                   6366:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   6367:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   6368:            .&mt('none').' </label>'."\n"
                   6369:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   6370:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   6371:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   6372:            .&mt('all submissions with details').' </label>'
                   6373:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 6374:     
1.700     bisitz   6375:     $result.=
                   6376:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   6377:        .'<input type="text" name="CODE" value="" />'
                   6378:        .&Apache::lonhtmlcommon::row_closure(1)
                   6379:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 6380: 
1.700     bisitz   6381:     # Show list of students to select for grading
                   6382:     $result.='<br /><input type="button" '.
1.589     bisitz   6383:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       6384: 
1.68      ng       6385:     $request->print($result);
                   6386: 
1.485     albertel 6387:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 6388: 	&Apache::loncommon::start_data_table().
                   6389: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6390: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6391: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 6392: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6393: 	'<th>'.&nameUserString('header').'</th>'.
                   6394: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       6395:  
1.761     raeburn  6396:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       6397:     my $ptr = 1;
1.294     albertel 6398:     foreach my $student (sort 
                   6399: 			 {
                   6400: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   6401: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   6402: 			     }
                   6403: 			     return $a cmp $b;
                   6404: 			 } (keys(%$fullname))) {
1.68      ng       6405: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 6406: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   6407:                                   : '</td>');
1.126     ng       6408: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 6409: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   6410: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 6411: 	$studentTable.=
                   6412: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   6413:                          : '');
1.68      ng       6414: 	$ptr++;
                   6415:     }
1.484     albertel 6416:     if ($ptr%2 == 0) {
                   6417: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   6418: 	    &Apache::loncommon::end_data_table_row();
                   6419:     }
                   6420:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       6421:     $studentTable.='<input type="button" '.
1.589     bisitz   6422:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       6423: 
                   6424:     $request->print($studentTable);
                   6425: 
                   6426:     return '';
                   6427: }
                   6428: 
                   6429: sub getSymbMap {
1.582     raeburn  6430:     my ($map_error) = @_;
1.132     bowersj2 6431:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6432:     unless (ref($navmap)) {
                   6433:         if (ref($map_error)) {
                   6434:             $$map_error = 'navmap';
                   6435:         }
                   6436:         return;
                   6437:     }
1.68      ng       6438:     my %symbx = ();
                   6439:     my @titles = ();
1.117     bowersj2 6440:     my $minder = 0;
                   6441: 
                   6442:     # Gather every sequence that has problems.
1.240     albertel 6443:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   6444: 					       1,0,1);
1.117     bowersj2 6445:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  6446: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 6447: 	    my $title = $minder.'.'.
                   6448: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   6449: 	    push(@titles, $title); # minder in case two titles are identical
                   6450: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 6451: 	    $minder++;
1.241     albertel 6452: 	}
1.68      ng       6453:     }
                   6454:     return \@titles,\%symbx;
                   6455: }
                   6456: 
1.72      ng       6457: #
                   6458: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       6459: sub displayPage {
1.608     www      6460:     my ($request,$symb) = @_;
1.257     albertel 6461:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6462:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6463:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6464:     my $pageTitle = $env{'form.page'};
1.103     albertel 6465:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6466:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6467:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 6468: 
                   6469:     #need to make sure we have the correct data for later EXT calls, 
                   6470:     #thus invalidate the cache
                   6471:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 6472:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   6473:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 6474:     &Apache::lonnet::clear_EXT_cache_status();
                   6475: 
1.103     albertel 6476:     if (!&canview($usec)) {
1.712     bisitz   6477:         $request->print(
                   6478:             '<span class="LC_warning">'.
                   6479:             &mt('Unable to view requested student. ([_1])',
                   6480:                     $env{'form.student'}).
                   6481:             '</span>');
                   6482:         return;
1.103     albertel 6483:     }
1.398     albertel 6484:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 6485:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       6486: 	'</h3>'."\n";
1.500     albertel 6487:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     6488:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 6489: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 6490:     } else {
                   6491: 	delete($env{'form.CODE'});
                   6492:     }
1.71      ng       6493:     &sub_page_js($request);
                   6494:     $request->print($result);
                   6495: 
1.132     bowersj2 6496:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6497:     unless (ref($navmap)) {
                   6498:         $request->print(&navmap_errormsg());
                   6499:         return;
                   6500:     }
1.257     albertel 6501:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       6502:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6503:     if (!$map) {
1.485     albertel 6504: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 6505: 	return; 
                   6506:     }
1.68      ng       6507:     my $iterator = $navmap->getIterator($map->map_start(),
                   6508: 					$map->map_finish());
                   6509: 
1.71      ng       6510:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       6511: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 6512: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   6513: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       6514: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 6515: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 6516: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      6517: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       6518: 
1.382     albertel 6519:     if (defined($env{'form.CODE'})) {
                   6520: 	$studentTable.=
                   6521: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   6522:     }
1.381     albertel 6523:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 6524: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       6525: 
1.594     bisitz   6526:     $studentTable.='&nbsp;<span class="LC_info">'.
                   6527:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   6528:         '</span>'."\n".
1.484     albertel 6529: 	&Apache::loncommon::start_data_table().
                   6530: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   6531: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 6532: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 6533: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6534: 
1.329     albertel 6535:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 6536:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       6537:     $iterator->next(); # skip the first BEGIN_MAP
                   6538:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 6539:     while ($depth > 0) {
1.68      ng       6540:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6541:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       6542: 
1.745     raeburn  6543:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 6544: 	    my $parts = $curRes->parts();
1.68      ng       6545:             my $title = $curRes->compTitle();
1.71      ng       6546: 	    my $symbx = $curRes->symb();
1.746     raeburn  6547:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 6548: 	    $studentTable.=
                   6549: 		&Apache::loncommon::start_data_table_row().
                   6550: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6551: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  6552: 		                        : '<br />('.&mt('[_1]parts',
                   6553: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 6554: 		 ).
                   6555: 		 '</td>';
1.71      ng       6556: 	    $studentTable.='<td valign="top">';
1.382     albertel 6557: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  6558:             if ($is_tool) {
                   6559:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   6560:             } else {
1.745     raeburn  6561: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   6562: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   6563: 					         undef,'both',\%form);
                   6564: 	        } else {
                   6565: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   6566: 		    $companswer =~ s|<form(.*?)>||g;
                   6567: 		    $companswer =~ s|</form>||g;
                   6568: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   6569: #		        $companswer =~ s/$1/ /ms;
                   6570: #		        $request->print('match='.$1."<br />\n");
                   6571: #		    }
                   6572: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   6573: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   6574: 		}
1.71      ng       6575: 	    }
                   6576: 
1.257     albertel 6577: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       6578: 
1.257     albertel 6579: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       6580: 		if ($record{'version'} eq '') {
1.745     raeburn  6581:                     my $msg = &mt('No recorded submission for this problem.');
                   6582:                     if ($is_tool) {
                   6583:                         $msg = &mt('No recorded transactions for this external tool');
                   6584:                     }
                   6585: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       6586: 		} else {
1.116     ng       6587: 		    my %responseType = ();
                   6588: 		    foreach my $partid (@{$parts}) {
1.147     albertel 6589: 			my @responseIds =$curRes->responseIds($partid);
                   6590: 			my @responseType =$curRes->responseType($partid);
                   6591: 			my %responseIds;
                   6592: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   6593: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   6594: 			}
                   6595: 			$responseType{$partid} = \%responseIds;
1.116     ng       6596: 		    }
1.148     albertel 6597: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       6598: 		}
1.257     albertel 6599: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   6600: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  6601:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       6602: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 6603: 									$env{'request.course.id'},
1.726     raeburn  6604: 									'','.submission',undef,
                   6605:                                                                         $usec,$identifier);
1.71      ng       6606:  
                   6607: 	    }
1.103     albertel 6608: 	    if (&canmodify($usec)) {
1.585     bisitz   6609:             $studentTable.=&gradeBox_start();
1.103     albertel 6610: 		foreach my $partid (@{$parts}) {
                   6611: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   6612: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   6613: 		    $question++;
                   6614: 		}
1.585     bisitz   6615:             $studentTable.=&gradeBox_end();
1.196     albertel 6616: 		$prob++;
1.71      ng       6617: 	    }
                   6618: 	    $studentTable.='</td></tr>';
1.68      ng       6619: 
1.103     albertel 6620: 	}
1.68      ng       6621:         $curRes = $iterator->next();
                   6622:     }
1.780     raeburn  6623:     my $disabled;
                   6624:     unless (&canmodify($usec)) {
                   6625:         $disabled = ' disabled="disabled"';
                   6626:     }
1.68      ng       6627: 
1.589     bisitz   6628:     $studentTable.=
                   6629:         '</table>'."\n".
1.780     raeburn  6630:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   6631:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   6632:         '</form>'."\n";
1.71      ng       6633:     $request->print($studentTable);
                   6634: 
                   6635:     return '';
1.119     ng       6636: }
                   6637: 
                   6638: sub displaySubByDates {
1.148     albertel 6639:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 6640:     my $isCODE=0;
1.335     albertel 6641:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  6642:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 6643:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 6644:     my $studentTable=&Apache::loncommon::start_data_table().
                   6645: 	&Apache::loncommon::start_data_table_header_row().
                   6646: 	'<th>'.&mt('Date/Time').'</th>'.
                   6647: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  6648:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  6649: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 6650: 	'<th>'.&mt('Status').'</th>'.
                   6651: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       6652:     my ($version);
                   6653:     my %mark;
1.148     albertel 6654:     my %orders;
1.119     ng       6655:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 6656:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  6657:         if ($is_tool) {
                   6658:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   6659:         } else {
                   6660:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   6661:         }
1.147     albertel 6662:     }
1.335     albertel 6663: 
                   6664:     my $interaction;
1.525     raeburn  6665:     my $no_increment = 1;
1.735     raeburn  6666:     my (%lastrndseed,%lasttype);
1.119     ng       6667:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 6668: 	my $timestamp = 
                   6669: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 6670: 	if (exists($$record{$version.':resource.0.version'})) {
                   6671: 	    $interaction = $$record{$version.':resource.0.version'};
                   6672: 	}
1.671     raeburn  6673:         if ($isTask && $env{'form.previousversion'}) {
                   6674:             next unless ($interaction == $env{'form.previousversion'});
                   6675:         }
1.335     albertel 6676: 	my $where = ($isTask ? "$version:resource.$interaction"
                   6677: 		             : "$version:resource");
1.467     albertel 6678: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   6679: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 6680: 	if ($isCODE) {
                   6681: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   6682: 	}
1.671     raeburn  6683:         if ($isTask) {
                   6684:             $studentTable.='<td>'.$interaction.'</td>';
                   6685:         }
1.119     ng       6686: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   6687: 	my @displaySub = ();
                   6688: 	foreach my $partid (@{$parts}) {
1.640     raeburn  6689:             my ($hidden,$type);
                   6690:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   6691:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  6692:                 $hidden = 1;
                   6693:             }
1.749     raeburn  6694:             my @matchKey;
                   6695:             if ($isTask) {
1.769     raeburn  6696:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  6697:             } elsif ($is_tool) {
1.769     raeburn  6698:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  6699:             } else {
1.769     raeburn  6700:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  6701:             }
1.122     ng       6702: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 6703: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 6704: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 6705: 		if (exists($$record{$version.':'.$matchKey}) &&
                   6706: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  6707:                     if ($is_tool) {
                   6708:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  6709:                     } else {
1.749     raeburn  6710: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   6711: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   6712:                         $displaySub[0].='<span class="LC_nobreak">';
                   6713:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   6714:                                        .' <span class="LC_internal_info">'
                   6715:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   6716:                                        .'</span>'
                   6717:                                        .' <b>';
                   6718:                         if ($hidden) {
                   6719:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   6720:                         } else {
                   6721:                             my ($trial,$rndseed,$newvariation);
                   6722:                             if ($type eq 'randomizetry') {
                   6723:                                 $trial = $$record{"$where.$partid.tries"};
                   6724:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   6725:                             }
                   6726: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   6727: 			        $displaySub[0].=&mt('Trial not counted');
                   6728: 		            } else {
                   6729: 			        $displaySub[0].=&mt('Trial: [_1]',
                   6730: 					        $$record{"$where.$partid.tries"});
                   6731:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   6732:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   6733:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   6734:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   6735:                                     }
1.640     raeburn  6736:                                 }
1.749     raeburn  6737:                                 $lastrndseed{$partid} = $rndseed;
                   6738:                                 $lasttype{$partid} = $type;
                   6739: 		            }
                   6740: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 6741:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  6742: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   6743: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   6744: 			        $orders{$partid}->{$responseId}=
                   6745: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   6746:                                                $no_increment,$type,$trial,$rndseed);
                   6747: 		            }
                   6748: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   6749: 		            $displaySub[0].='&nbsp; '.
                   6750: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   6751:                         }
1.596     raeburn  6752:                     }
1.147     albertel 6753: 		}
                   6754: 	    }
1.335     albertel 6755: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 6756: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   6757: 				    $$record{"$where.$partid.checkedin"},
                   6758: 				    $$record{"$where.$partid.checkedin.slot"}).
                   6759: 					'<br />';
1.335     albertel 6760: 	    }
                   6761: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 6762: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 6763: 		    lc($$record{"$where.$partid.award"}).' '.
                   6764: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 6765: 		    '<br />';
1.749     raeburn  6766: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   6767: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   6768: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   6769: 		}
1.147     albertel 6770: 	    }
1.335     albertel 6771: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  6772: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   6773: 		unless ($is_tool) {
                   6774: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6775: 		}
1.335     albertel 6776: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   6777: 		$displaySub[2].=
1.749     raeburn  6778: 		    $$record{"$version:resource.$partid.regrader"};
                   6779:                 unless ($is_tool) {
                   6780: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6781:                 }
1.147     albertel 6782: 	    }
                   6783: 	}
                   6784: 	# needed because old essay regrader has not parts info
                   6785: 	if (exists $$record{"$version:resource.regrader"}) {
                   6786: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   6787: 	}
                   6788: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   6789: 	if ($displaySub[2]) {
1.467     albertel 6790: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 6791: 	}
1.467     albertel 6792: 	$studentTable.='&nbsp;</td>'.
                   6793: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       6794:     }
1.467     albertel 6795:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       6796:     return $studentTable;
1.71      ng       6797: }
                   6798: 
                   6799: sub updateGradeByPage {
1.608     www      6800:     my ($request,$symb) = @_;
1.71      ng       6801: 
1.257     albertel 6802:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6803:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6804:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6805:     my $pageTitle = $env{'form.page'};
1.103     albertel 6806:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6807:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6808:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 6809:     if (!&canmodify($usec)) {
1.526     raeburn  6810: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 6811: 	return;
                   6812:     }
1.398     albertel 6813:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  6814:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       6815: 	'</h3>'."\n";
1.70      ng       6816: 
1.68      ng       6817:     $request->print($result);
                   6818: 
1.582     raeburn  6819: 
1.132     bowersj2 6820:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6821:     unless (ref($navmap)) {
                   6822:         $request->print(&navmap_errormsg());
                   6823:         return;
                   6824:     }
1.257     albertel 6825:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       6826:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6827:     if (!$map) {
1.527     raeburn  6828: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 6829: 	return; 
                   6830:     }
1.71      ng       6831:     my $iterator = $navmap->getIterator($map->map_start(),
                   6832: 					$map->map_finish());
1.70      ng       6833: 
1.484     albertel 6834:     my $studentTable=
                   6835: 	&Apache::loncommon::start_data_table().
                   6836: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6837: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   6838: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   6839: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   6840: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 6841: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6842: 
                   6843:     $iterator->next(); # skip the first BEGIN_MAP
                   6844:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  6845:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.798     raeburn  6846:     my (@updates,%weights,%excuseds,%awardeds,@symbs_in_map);
1.101     albertel 6847:     while ($depth > 0) {
1.71      ng       6848:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6849:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       6850: 
1.385     albertel 6851:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 6852: 	    my $parts = $curRes->parts();
1.71      ng       6853:             my $title = $curRes->compTitle();
                   6854: 	    my $symbx = $curRes->symb();
1.798     raeburn  6855:             push(@symbs_in_map,$symbx);
1.484     albertel 6856: 	    $studentTable.=
                   6857: 		&Apache::loncommon::start_data_table_row().
                   6858: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6859: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  6860:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  6861: 		.')').'</td>';
1.71      ng       6862: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   6863: 
                   6864: 	    my %newrecord=();
                   6865: 	    my @displayPts=();
1.269     raeburn  6866:             my %aggregate = ();
                   6867:             my $aggregateflag = 0;
1.787     raeburn  6868:             my %queueable;
1.726     raeburn  6869:             if ($env{'form.HIDE'.$prob}) {
                   6870:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  6871:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  6872:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.798     raeburn  6873:                 if ($numchgs) {
                   6874:                     push(@updates,$symbx);
                   6875:                 }
1.726     raeburn  6876:                 $hideflag += $numchgs;
                   6877:             }
1.71      ng       6878: 	    foreach my $partid (@{$parts}) {
1.257     albertel 6879: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   6880: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.787     raeburn  6881:                 my @types = $curRes->responseType($partid);
1.786     raeburn  6882:                 if (grep(/^essay$/,@types)) {
                   6883:                     $queueable{$partid} = 1;
                   6884:                 } else {
1.787     raeburn  6885:                     my @ids = $curRes->responseIds($partid);
1.786     raeburn  6886:                     for (my $i=0; $i < scalar(@ids); $i++) {
1.787     raeburn  6887:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
1.786     raeburn  6888:                                                           '.handgrade',$symb);
                   6889:                         if (lc($hndgrd) eq 'yes') {
                   6890:                             $queueable{$partid} = 1;
                   6891:                             last;
                   6892:                         }
                   6893:                     }
                   6894:                 }
1.257     albertel 6895: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   6896: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.798     raeburn  6897:                 $weights{$symbx}{$partid} = $wgt;
                   6898:                 $excuseds{$symbx}{$partid} = '';
1.71      ng       6899: 		my $partial = $newpts/$wgt;
                   6900: 		my $score;
                   6901: 		if ($partial > 0) {
                   6902: 		    $score = 'correct_by_override';
1.125     ng       6903: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       6904: 		    $score = 'incorrect_by_override';
                   6905: 		}
1.257     albertel 6906: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       6907: 		if ($dropMenu eq 'excused') {
1.71      ng       6908: 		    $partial = '';
                   6909: 		    $score = 'excused';
1.798     raeburn  6910:                     $excuseds{$symbx}{$partid} = 1;
1.125     ng       6911: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 6912: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       6913: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   6914: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   6915: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   6916: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 6917: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       6918: 		    $changeflag++;
                   6919: 		    $newpts = '';
1.269     raeburn  6920:                     
                   6921:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   6922:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   6923:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   6924:                     if ($aggtries > 0) {
                   6925:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   6926:                         $aggregateflag = 1;
                   6927:                     }
1.71      ng       6928: 		}
1.324     albertel 6929: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 6930: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  6931: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       6932: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 6933: 		    '&nbsp;<br />';
1.526     raeburn  6934: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       6935: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 6936: 		    '&nbsp;<br />';
1.71      ng       6937: 		$question++;
1.798     raeburn  6938:                 if (($newpts eq '') || ($partial eq '')) {
                   6939:                     $awardeds{$symbx}{$partid} = 0;
                   6940:                 } else {
                   6941:                     $awardeds{$symbx}{$partid} = $partial;
                   6942:                 }
1.380     albertel 6943: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       6944: 
1.71      ng       6945: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       6946: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 6947: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       6948: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       6949: 
                   6950: 		$changeflag++;
                   6951: 	    }
                   6952: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 6953: 		my %record = 
                   6954: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   6955: 					     $udom,$uname);
                   6956: 
                   6957: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   6958: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   6959: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   6960: 		    $newrecord{'resource.CODE'} = '';
                   6961: 		}
1.257     albertel 6962: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       6963: 					$udom,$uname);
1.382     albertel 6964: 		%record = &Apache::lonnet::restore($symbx,
                   6965: 						   $env{'request.course.id'},
                   6966: 						   $udom,$uname);
1.380     albertel 6967: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.786     raeburn  6968: 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       6969: 	    }
1.380     albertel 6970: 	    
1.269     raeburn  6971:             if ($aggregateflag) {
                   6972:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   6973:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   6974:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   6975:             }
1.125     ng       6976: 
1.71      ng       6977: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   6978: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 6979: 		&Apache::loncommon::end_data_table_row();
1.68      ng       6980: 
1.196     albertel 6981: 	    $prob++;
1.798     raeburn  6982:             if ($changeflag) {
                   6983:                 push(@updates,$symbx);
                   6984:             }
1.68      ng       6985: 	}
1.71      ng       6986:         $curRes = $iterator->next();
1.68      ng       6987:     }
1.98      albertel 6988: 
1.484     albertel 6989:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  6990:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   6991: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  6992: 		  $changeflag).'<br />');
                   6993:     my $hidemsg=($hideflag == 0 ? '' :
                   6994:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   6995:                      $hideflag).'<br />');
                   6996:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       6997: 
1.798     raeburn  6998:     if (@updates) {
                   6999:         my (@allsymbs,$mapsymb,@recurseup,%parentmapsymbs,%possmappb,%possrespb);
                   7000:         @allsymbs = @updates;
                   7001:         if (ref($map)) {
                   7002:             $mapsymb = $map->symb();
                   7003:             push(@allsymbs,$mapsymb);
                   7004:             @recurseup = $navmap->recurseup_maps($map->src,1);
                   7005:         }
                   7006:         if (@recurseup) {
                   7007:             push(@allsymbs,@recurseup);
                   7008:             map { $parentmapsymbs{$_} = 1; } @recurseup;
                   7009:         }
                   7010:         my %passback = &Apache::lonnet::get('nohist_linkprot_passback',\@allsymbs,$cdom,$cnum);
                   7011:         my (%uniqsymbs,$use_symbs_in_map);
                   7012:         if (keys(%passback)) {
                   7013:             foreach my $possible (keys(%passback)) {
                   7014:                 if (ref($passback{$possible}) eq 'HASH') {
                   7015:                     if ($possible eq $mapsymb) {
                   7016:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7017:                             $possmappb{$launcher} = 1;
                   7018:                         }
                   7019:                         $use_symbs_in_map = 1;
                   7020:                     } elsif (exists($parentmapsymbs{$possible})) {
                   7021:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7022:                             my ($linkuri,$linkprotector,$scope) = split(/\0/,$launcher);
                   7023:                             if ($scope eq 'rec') {
                   7024:                                 $possmappb{$launcher} = 1;
                   7025:                                 $use_symbs_in_map = 1;
                   7026:                             }
                   7027:                         }
                   7028:                     } elsif (grep(/^\Q$possible$\E$/,@updates)) {
                   7029:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7030:                             $possrespb{$launcher} = 1;
                   7031:                         }
                   7032:                         $uniqsymbs{$possible} = 1;
                   7033:                     }
                   7034:                 }
                   7035:             }
                   7036:         }
                   7037:         if ($use_symbs_in_map) {
                   7038:             map { $uniqsymbs{$_} = 1; } @symbs_in_map;
                   7039:         }
                   7040:         my @posslaunchers;
                   7041:         if (keys(%possmappb)) {
                   7042:             push(@posslaunchers,keys(%possmappb));
                   7043:         }
                   7044:         if (keys(%possrespb)) {
                   7045:             push(@posslaunchers,keys(%possrespb));
                   7046:         }
                   7047:         if (@posslaunchers) {
                   7048:             my (%pbsave,%skip_passback,%needpb);
                   7049:             my %pbids = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@posslaunchers,$udom,$uname);
                   7050:             foreach my $key (keys(%pbids)) {
                   7051:                 if (ref($pbids{$key}) eq 'ARRAY') {
                   7052:                     $needpb{$key} = 1;
                   7053:                 }
                   7054:             }
                   7055:             my @symbs = keys(%uniqsymbs);
1.802     raeburn  7056:             &process_passbacks('updatebypage',\@symbs,$cdom,$cnum,$udom,$uname,$usec,\%weights,
1.798     raeburn  7057:                                \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave,\%pbids);
1.801     raeburn  7058:             if (@Apache::grades::ltipassback) {
1.798     raeburn  7059:                 unless ($registered_cleanup) {
                   7060:                     my $handlers = $request->get_handlers('PerlCleanupHandler');
                   7061:                     $request->set_handlers('PerlCleanupHandler' =>
1.801     raeburn  7062:                                            [\&Apache::grades::make_passback,@{$handlers}]);
                   7063:                     $registered_cleanup=1;
1.798     raeburn  7064:                 }
                   7065:             }
                   7066:         }
                   7067:     }
1.70      ng       7068:     return '';
                   7069: }
                   7070: 
1.801     raeburn  7071: sub make_passback {
                   7072:     if (@Apache::grades::ltipassback) {
                   7073:         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7074:         my $ip = &Apache::lonnet::get_host_ip($lonhost);
                   7075:         foreach my $item (@Apache::grades::ltipassback) {
                   7076:             &Apache::lonhomework::run_passback($item,$lonhost,$ip);
                   7077:         }
                   7078:         undef(@Apache::grades::ltipassback);
                   7079:     }
                   7080: }
                   7081: 
1.72      ng       7082: #-------- end of section for handling grading by page/sequence ---------
                   7083: #
                   7084: #-------------------------------------------------------------------
                   7085: 
1.581     www      7086: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 7087: #
                   7088: #------ start of section for handling grading by page/sequence ---------
                   7089: 
1.423     albertel 7090: =pod
                   7091: 
                   7092: =head1 Bubble sheet grading routines
                   7093: 
1.424     albertel 7094:   For this documentation:
                   7095: 
                   7096:    'scanline' refers to the full line of characters
                   7097:    from the file that we are parsing that represents one entire sheet
                   7098: 
                   7099:    'bubble line' refers to the data
1.659     raeburn  7100:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 7101: 
                   7102: 
1.659     raeburn  7103: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 7104: into a course. When a user wants to grade, they select a
1.659     raeburn  7105: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 7106: one of the predefined configurations for what each scanline looks
                   7107: like.
                   7108: 
                   7109: Next each scanline is checked for any errors of either 'missing
1.435     foxr     7110: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 7111: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   7112: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  7113: invalid student/employee ID
1.424     albertel 7114: 
                   7115: If the CODE option is used that determines the randomization of the
1.556     weissno  7116: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 7117: username:domain.
                   7118: 
                   7119: During the validation phase the instructor can choose to skip scanlines. 
                   7120: 
1.659     raeburn  7121: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 7122: 
                   7123:   scantron_original_filename (unmodified original file)
                   7124:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   7125:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   7126: 
                   7127: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  7128: correction information that isn't representable in the bubblesheet
1.424     albertel 7129: file (see &scantron_getfile() for more information)
                   7130: 
                   7131: After all scanlines are either valid, marked as valid or skipped, then
                   7132: foreach line foreach problem in the picked sequence, an ssi request is
                   7133: made that simulates a user submitting their selected letter(s) against
                   7134: the homework problem.
1.423     albertel 7135: 
                   7136: =over 4
                   7137: 
                   7138: 
                   7139: 
                   7140: =item defaultFormData
                   7141: 
                   7142:   Returns html hidden inputs used to hold context/default values.
                   7143: 
                   7144:  Arguments:
                   7145:   $symb - $symb of the current resource 
                   7146: 
                   7147: =cut
1.422     foxr     7148: 
1.81      albertel 7149: sub defaultFormData {
1.324     albertel 7150:     my ($symb)=@_;
1.766     raeburn  7151:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 7152: }
                   7153: 
1.447     foxr     7154: 
1.423     albertel 7155: =pod 
                   7156: 
                   7157: =item getSequenceDropDown
                   7158: 
                   7159:    Return html dropdown of possible sequences to grade
                   7160:  
                   7161:  Arguments:
1.582     raeburn  7162:    $symb - $symb of the current resource
                   7163:    $map_error - ref to scalar which will container error if
                   7164:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 7165: 
                   7166: =cut
1.422     foxr     7167: 
1.75      albertel 7168: sub getSequenceDropDown {
1.582     raeburn  7169:     my ($symb,$map_error)=@_;
1.75      albertel 7170:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  7171:     my ($titles,$symbx) = &getSymbMap($map_error);
                   7172:     if (ref($map_error)) {
                   7173:         return if ($$map_error);
                   7174:     }
1.137     albertel 7175:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 7176:     my $ctr=0;
                   7177:     foreach (@$titles) {
                   7178: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   7179: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 7180: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 7181: 	    '>'.$showtitle.'</option>'."\n";
                   7182: 	$ctr++;
                   7183:     }
                   7184:     $result.= '</select>';
                   7185:     return $result;
                   7186: }
                   7187: 
1.495     albertel 7188: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  7189:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 7190: 
                   7191: my %first_bubble_line;             # First bubble line no. for each bubble.
                   7192: 
1.509     raeburn  7193: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   7194:                                    # matchresponse or rankresponse, where 
                   7195:                                    # an individual response can have multiple 
                   7196:                                    # lines
1.503     raeburn  7197: 
                   7198: my %responsetype_per_response;     # responsetype for each response
                   7199: 
1.691     raeburn  7200: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   7201:                                    # numbered response. Needed when randomorder
                   7202:                                    # or randompick are in use. Key is ID, value 
                   7203:                                    # is response number.
                   7204: 
1.495     albertel 7205: # Save and restore the bubble lines array to the form env.
                   7206: 
                   7207: 
                   7208: sub save_bubble_lines {
                   7209:     foreach my $line (keys(%bubble_lines_per_response)) {
                   7210: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   7211: 	$env{"form.scantron.first_bubble_line.$line"} =
                   7212: 	    $first_bubble_line{$line};
1.503     raeburn  7213:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   7214:             $subdivided_bubble_lines{$line};
                   7215:         $env{"form.scantron.responsetype.$line"} =
                   7216:             $responsetype_per_response{$line};
1.495     albertel 7217:     }
1.691     raeburn  7218:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   7219:         my $line = $masterseq_id_responsenum{$resid};
                   7220:         $env{"form.scantron.residpart.$line"} = $resid;
                   7221:     }
1.495     albertel 7222: }
                   7223: 
                   7224: 
                   7225: sub restore_bubble_lines {
                   7226:     my $line = 0;
                   7227:     %bubble_lines_per_response = ();
1.691     raeburn  7228:     %masterseq_id_responsenum = ();
1.495     albertel 7229:     while ($env{"form.scantron.bubblelines.$line"}) {
                   7230: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   7231: 	$bubble_lines_per_response{$line} = $value;
                   7232: 	$first_bubble_line{$line}  =
                   7233: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  7234:         $subdivided_bubble_lines{$line} =
                   7235:             $env{"form.scantron.sub_bubblelines.$line"};
                   7236:         $responsetype_per_response{$line} =
                   7237:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  7238:         my $id = $env{"form.scantron.residpart.$line"};
                   7239:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 7240: 	$line++;
                   7241:     }
                   7242: }
                   7243: 
1.423     albertel 7244: =pod 
                   7245: 
                   7246: =item scantron_filenames
                   7247: 
                   7248:    Returns a list of the scantron files in the current course 
                   7249: 
                   7250: =cut
1.422     foxr     7251: 
1.202     albertel 7252: sub scantron_filenames {
1.257     albertel 7253:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7254:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  7255:     my $getpropath = 1;
1.662     raeburn  7256:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   7257:                                                         $cname,$getpropath);
1.202     albertel 7258:     my @possiblenames;
1.662     raeburn  7259:     if (ref($dirlist) eq 'ARRAY') {
                   7260:         foreach my $filename (sort(@{$dirlist})) {
                   7261: 	    ($filename)=split(/&/,$filename);
                   7262: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   7263: 	    $filename=~s/^scantron_orig_//;
                   7264: 	    push(@possiblenames,$filename);
                   7265:         }
1.202     albertel 7266:     }
                   7267:     return @possiblenames;
                   7268: }
                   7269: 
1.423     albertel 7270: =pod 
                   7271: 
                   7272: =item scantron_uploads
                   7273: 
                   7274:    Returns  html drop-down list of scantron files in current course.
                   7275: 
                   7276:  Arguments:
                   7277:    $file2grade - filename to set as selected in the dropdown
                   7278: 
                   7279: =cut
1.422     foxr     7280: 
1.202     albertel 7281: sub scantron_uploads {
1.209     ng       7282:     my ($file2grade) = @_;
1.202     albertel 7283:     my $result=	'<select name="scantron_selectfile">';
                   7284:     $result.="<option></option>";
                   7285:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 7286: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 7287:     }
                   7288:     $result.="</select>";
                   7289:     return $result;
                   7290: }
                   7291: 
1.423     albertel 7292: =pod 
                   7293: 
                   7294: =item scantron_scantab
                   7295: 
                   7296:   Returns html drop down of the scantron formats in the scantronformat.tab
                   7297:   file.
                   7298: 
                   7299: =cut
1.422     foxr     7300: 
1.82      albertel 7301: sub scantron_scantab {
                   7302:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 7303:     $result.='<option></option>'."\n";
1.754     raeburn  7304:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  7305:     if (@lines > 0) {
                   7306:         foreach my $line (@lines) {
                   7307:             next if (($line =~ /^\#/) || ($line eq ''));
                   7308: 	    my ($name,$descrip)=split(/:/,$line);
                   7309: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   7310:         }
1.82      albertel 7311:     }
                   7312:     $result.='</select>'."\n";
1.518     raeburn  7313:     return $result;
                   7314: }
                   7315: 
1.423     albertel 7316: =pod 
                   7317: 
                   7318: =item scantron_CODElist
                   7319: 
                   7320:   Returns html drop down of the saved CODE lists from current course,
                   7321:   generated from earlier printings.
                   7322: 
                   7323: =cut
1.422     foxr     7324: 
1.186     albertel 7325: sub scantron_CODElist {
1.257     albertel 7326:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7327:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 7328:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   7329:     my $namechoice='<option></option>';
1.225     albertel 7330:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 7331: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 7332: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 7333: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   7334:     }
                   7335:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   7336:     return $namechoice;
                   7337: }
                   7338: 
1.423     albertel 7339: =pod 
                   7340: 
                   7341: =item scantron_CODEunique
                   7342: 
                   7343:   Returns the html for "Each CODE to be used once" radio.
                   7344: 
                   7345: =cut
1.422     foxr     7346: 
1.186     albertel 7347: sub scantron_CODEunique {
1.532     bisitz   7348:     my $result='<span class="LC_nobreak">
1.272     albertel 7349:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7350:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 7351:                 </span>
1.532     bisitz   7352:                 <span class="LC_nobreak">
1.272     albertel 7353:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7354:                         value="no" />'.&mt('No').' </label>
1.381     albertel 7355:                 </span>';
1.186     albertel 7356:     return $result;
                   7357: }
1.423     albertel 7358: 
                   7359: =pod 
                   7360: 
                   7361: =item scantron_selectphase
                   7362: 
1.659     raeburn  7363:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 7364:   Allows for - starting a grading run.
1.424     albertel 7365:              - downloading existing scan data (original, corrected
1.423     albertel 7366:                                                 or skipped info)
                   7367: 
                   7368:              - uploading new scan data
                   7369: 
                   7370:  Arguments:
                   7371:   $r          - The Apache request object
                   7372:   $file2grade - name of the file that contain the scanned data to score
                   7373: 
                   7374: =cut
1.186     albertel 7375: 
1.75      albertel 7376: sub scantron_selectphase {
1.608     www      7377:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 7378:     if (!$symb) {return '';}
1.582     raeburn  7379:     my $map_error;
                   7380:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   7381:     if ($map_error) {
                   7382:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   7383:         return;
                   7384:     }
1.324     albertel 7385:     my $default_form_data=&defaultFormData($symb);
1.209     ng       7386:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 7387:     my $format_selector=&scantron_scantab();
1.186     albertel 7388:     my $CODE_selector=&scantron_CODElist();
                   7389:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 7390:     my $result;
1.422     foxr     7391: 
1.513     foxr     7392:     $ssi_error = 0;
                   7393: 
1.770     raeburn  7394:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 7395: 
                   7396: 	# Chunk of form to prompt for a scantron file upload.
                   7397: 
                   7398:         $r->print('
1.754     raeburn  7399:     <br />');
1.606     wenzelju 7400:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7401:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  7402:     my $csec= $env{'request.course.sec'};
1.736     damieng  7403:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   7404:     &js_escape(\$alertmsg);
1.754     raeburn  7405:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 7406:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   7407:     function checkUpload(formname) {
                   7408: 	if (formname.upfile.value == "") {
1.736     damieng  7409: 	    alert("'.$alertmsg.'");
1.606     wenzelju 7410: 	    return false;
                   7411: 	}
                   7412: 	formname.submit();
1.756     raeburn  7413:     }'."\n".$formatjs));
1.606     wenzelju 7414:     $r->print('
                   7415:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7416:                 '.$default_form_data.'
                   7417:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  7418:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 7419:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   7420:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  7421:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7422:               '.&Apache::loncommon::start_data_table_header_row().'
                   7423:                 <th>
                   7424:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   7425:                 </th>
                   7426:               '.&Apache::loncommon::end_data_table_header_row().'
                   7427:               '.&Apache::loncommon::start_data_table_row().'
                   7428:             <td>
                   7429:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   7430:     if ($formatoptions) {
                   7431:         $r->print('</td>
                   7432:                  '.&Apache::loncommon::end_data_table_row().'
                   7433:                  '.&Apache::loncommon::start_data_table_row().'
                   7434:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   7435:                  </td>
                   7436:                  '.&Apache::loncommon::end_data_table_row().'
                   7437:                  '.&Apache::loncommon::start_data_table_row().'
                   7438:                  <td>'
                   7439:         );
                   7440:     } else {
                   7441:         $r->print(' <br />');
                   7442:     }
                   7443:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   7444:               </td>
                   7445:              '.&Apache::loncommon::end_data_table_row().'
                   7446:              '.&Apache::loncommon::end_data_table().'
                   7447:              </form>'
                   7448:     );
1.606     wenzelju 7449: 
                   7450:     }
                   7451: 
1.422     foxr     7452:     # Chunk of form to prompt for a file to grade and how:
                   7453: 
1.489     albertel 7454:     $result.= '
                   7455:     <br />
                   7456:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   7457:     <input type="hidden" name="command" value="scantron_warning" />
                   7458:     '.$default_form_data.'
                   7459:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7460:        '.&Apache::loncommon::start_data_table_header_row().'
                   7461:             <th colspan="2">
1.492     albertel 7462:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 7463:             </th>
                   7464:        '.&Apache::loncommon::end_data_table_header_row().'
                   7465:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7466:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 7467:        '.&Apache::loncommon::end_data_table_row().'
                   7468:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      7469:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 7470:        '.&Apache::loncommon::end_data_table_row().'
                   7471:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      7472:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 7473:        '.&Apache::loncommon::end_data_table_row().'
                   7474:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7475:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 7476:        '.&Apache::loncommon::end_data_table_row().'
                   7477:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7478:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 7479:        '.&Apache::loncommon::end_data_table_row().'
                   7480:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7481: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 7482:             <td>
1.492     albertel 7483: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   7484:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   7485:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 7486: 	    </td>
1.489     albertel 7487:        '.&Apache::loncommon::end_data_table_row().'
                   7488:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 7489:             <td colspan="2">
1.572     www      7490:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 7491:             </td>
1.489     albertel 7492:        '.&Apache::loncommon::end_data_table_row().'
                   7493:     '.&Apache::loncommon::end_data_table().'
                   7494:     </form>
                   7495: ';
1.162     albertel 7496:    
                   7497:     $r->print($result);
                   7498: 
1.422     foxr     7499:     # Chunk of the form that prompts to view a scoring office file,
                   7500:     # corrected file, skipped records in a file.
                   7501: 
1.489     albertel 7502:     $r->print('
                   7503:    <br />
                   7504:    <form action="/adm/grades" name="scantron_download">
                   7505:      '.$default_form_data.'
                   7506:      <input type="hidden" name="command" value="scantron_download" />
                   7507:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7508:        '.&Apache::loncommon::start_data_table_header_row().'
                   7509:               <th>
1.492     albertel 7510:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 7511:               </th>
                   7512:        '.&Apache::loncommon::end_data_table_header_row().'
                   7513:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7514:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 7515:                 <br />
1.492     albertel 7516:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 7517:        '.&Apache::loncommon::end_data_table_row().'
                   7518:      '.&Apache::loncommon::end_data_table().'
                   7519:    </form>
                   7520:    <br />
                   7521: ');
1.162     albertel 7522: 
1.457     banghart 7523:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  7524: 
1.694     bisitz   7525:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  7526:              $default_form_data."\n".
                   7527:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   7528:              &Apache::loncommon::start_data_table_header_row()."\n".
                   7529:              '<th colspan="2">
1.572     www      7530:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  7531:              '</th>'."\n".
                   7532:               &Apache::loncommon::end_data_table_header_row()."\n".
                   7533:               &Apache::loncommon::start_data_table_row()."\n".
                   7534:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   7535:               '<td> '.$sequence_selector.' </td>'.
                   7536:               &Apache::loncommon::end_data_table_row()."\n".
                   7537:               &Apache::loncommon::start_data_table_row()."\n".
                   7538:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   7539:               '<td> '.$file_selector.' </td>'."\n".
                   7540:               &Apache::loncommon::end_data_table_row()."\n".
                   7541:               &Apache::loncommon::start_data_table_row()."\n".
                   7542:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   7543:               '<td> '.$format_selector.' </td>'."\n".
                   7544:               &Apache::loncommon::end_data_table_row()."\n".
                   7545:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  7546:               '<td> '.&mt('Options').' </td>'."\n".
                   7547:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   7548:               &Apache::loncommon::end_data_table_row()."\n".
                   7549:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  7550:               '<td colspan="2">'."\n".
                   7551:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      7552:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  7553:               '</td>'."\n".
                   7554:               &Apache::loncommon::end_data_table_row()."\n".
                   7555:               &Apache::loncommon::end_data_table()."\n".
                   7556:               '</form><br />');
                   7557:     return;
1.75      albertel 7558: }
                   7559: 
1.423     albertel 7560: =pod 
                   7561: 
                   7562: =item username_to_idmap
                   7563: 
1.556     weissno  7564:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  7565:     student username:domain. If a single ID occurs for more than one student,
                   7566:     the status of the student is checked, and if Active, the value in the hash
                   7567:     will be set to the Active student.
1.423     albertel 7568: 
                   7569:   Arguments:
                   7570: 
                   7571:     $classlist - reference to the class list hash. This is a hash
                   7572:                  keyed by student name:domain  whose elements are references
1.424     albertel 7573:                  to arrays containing various chunks of information
1.423     albertel 7574:                  about the student. (See loncoursedata for more info).
                   7575: 
                   7576:   Returns
                   7577:     %idmap - the constructed hash
                   7578: 
                   7579: =cut
                   7580: 
1.82      albertel 7581: sub username_to_idmap {
                   7582:     my ($classlist)= @_;
                   7583:     my %idmap;
                   7584:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  7585:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   7586:         unless ($id eq '') {
                   7587:             if (!exists($idmap{$id})) {
                   7588:                 $idmap{$id} = $student;
                   7589:             } else {
                   7590:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   7591:                 if ($status eq 'Active') {
                   7592:                     $idmap{$id} = $student;
                   7593:                 }
                   7594:             }
                   7595:         }
1.82      albertel 7596:     }
                   7597:     return %idmap;
                   7598: }
1.423     albertel 7599: 
                   7600: =pod
                   7601: 
1.424     albertel 7602: =item scantron_fixup_scanline
1.423     albertel 7603: 
                   7604:    Process a requested correction to a scanline.
                   7605: 
                   7606:   Arguments:
1.754     raeburn  7607:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 7608:     $scan_data         - hash of correction information 
                   7609:                           (see &scantron_getfile())
                   7610:     $line              - existing scanline
                   7611:     $whichline         - line number of the passed in scanline
                   7612:     $field             - type of change to process 
                   7613:                          (either 
1.573     bisitz   7614:                           'ID'     -> correct the student/employee ID
1.423     albertel 7615:                           'CODE'   -> correct the CODE
                   7616:                           'answer' -> fixup the submitted answers)
                   7617:     
                   7618:    $args               - hash of additional info,
                   7619:                           - 'ID' 
                   7620:                                'newid' -> studentID to use in replacement
1.424     albertel 7621:                                           of existing one
1.423     albertel 7622:                           - 'CODE' 
                   7623:                                'CODE_ignore_dup' - set to true if duplicates
                   7624:                                                    should be ignored.
                   7625: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 7626:                                         if the existing unfound code should
1.423     albertel 7627:                                         be used as is
                   7628:                           - 'answer'
                   7629:                                'response' - new answer or 'none' if blank
                   7630:                                'question' - the bubble line to change
1.503     raeburn  7631:                                'questionnum' - the question identifier,
                   7632:                                                may include subquestion. 
1.423     albertel 7633: 
                   7634:   Returns:
                   7635:     $line - the modified scanline
                   7636: 
                   7637:   Side effects: 
                   7638:     $scan_data - may be updated
                   7639: 
                   7640: =cut
                   7641: 
1.82      albertel 7642: 
1.157     albertel 7643: sub scantron_fixup_scanline {
                   7644:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   7645:     if ($field eq 'ID') {
                   7646: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 7647: 	    return ($line,1,'New value too large');
1.157     albertel 7648: 	}
                   7649: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   7650: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   7651: 				     $args->{'newid'});
                   7652: 	}
                   7653: 	substr($line,$$scantron_config{'IDstart'}-1,
                   7654: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   7655: 	if ($args->{'newid'}=~/^\s*$/) {
                   7656: 	    &scan_data($scan_data,"$whichline.user",
                   7657: 		       $args->{'username'}.':'.$args->{'domain'});
                   7658: 	}
1.186     albertel 7659:     } elsif ($field eq 'CODE') {
1.192     albertel 7660: 	if ($args->{'CODE_ignore_dup'}) {
                   7661: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   7662: 	}
                   7663: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   7664: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 7665: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   7666: 		return ($line,1,'New CODE value too large');
                   7667: 	    }
                   7668: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   7669: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   7670: 	    }
                   7671: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   7672: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 7673: 	}
1.157     albertel 7674:     } elsif ($field eq 'answer') {
1.497     foxr     7675: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 7676: 	my $off=$scantron_config->{'Qoff'};
                   7677: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     7678: 	my $answer=${off}x$length;
                   7679: 	if ($args->{'response'} eq 'none') {
                   7680: 	    &scan_data($scan_data,
1.503     raeburn  7681: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     7682: 	} else {
                   7683: 	    if ($on eq 'letter') {
                   7684: 		my @alphabet=('A'..'Z');
                   7685: 		$answer=$alphabet[$args->{'response'}];
                   7686: 	    } elsif ($on eq 'number') {
                   7687: 		$answer=$args->{'response'}+1;
                   7688: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 7689: 	    } else {
1.497     foxr     7690: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 7691: 	    }
1.497     foxr     7692: 	    &scan_data($scan_data,
1.503     raeburn  7693: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 7694: 	}
1.497     foxr     7695: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   7696: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 7697:     }
                   7698:     return $line;
                   7699: }
1.423     albertel 7700: 
                   7701: =pod
                   7702: 
                   7703: =item scan_data
                   7704: 
                   7705:     Edit or look up  an item in the scan_data hash.
                   7706: 
                   7707:   Arguments:
                   7708:     $scan_data  - The hash (see scantron_getfile)
                   7709:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 7710:                   scantronfilename_key).
1.423     albertel 7711:     $data        - New value of the hash entry.
                   7712:     $delete      - If true, the entry is removed from the hash.
                   7713: 
                   7714:   Returns:
                   7715:     The new value of the hash table field (undefined if deleted).
                   7716: 
                   7717: =cut
                   7718: 
                   7719: 
1.157     albertel 7720: sub scan_data {
                   7721:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 7722:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 7723:     if (defined($value)) {
                   7724: 	$scan_data->{$filename.'_'.$key} = $value;
                   7725:     }
                   7726:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   7727:     return $scan_data->{$filename.'_'.$key};
                   7728: }
1.423     albertel 7729: 
1.495     albertel 7730: # ----- These first few routines are general use routines.----
                   7731: 
                   7732: # Return the number of occurences of a pattern in a string.
                   7733: 
                   7734: sub occurence_count {
                   7735:     my ($string, $pattern) = @_;
                   7736: 
                   7737:     my @matches = ($string =~ /$pattern/g);
                   7738: 
                   7739:     return scalar(@matches);
                   7740: }
                   7741: 
                   7742: 
                   7743: # Take a string known to have digits and convert all the
                   7744: # digits into letters in the range J,A..I.
                   7745: 
                   7746: sub digits_to_letters {
                   7747:     my ($input) = @_;
                   7748: 
                   7749:     my @alphabet = ('J', 'A'..'I');
                   7750: 
                   7751:     my @input    = split(//, $input);
                   7752:     my $output ='';
                   7753:     for (my $i = 0; $i < scalar(@input); $i++) {
                   7754: 	if ($input[$i] =~ /\d/) {
                   7755: 	    $output .= $alphabet[$input[$i]];
                   7756: 	} else {
                   7757: 	    $output .= $input[$i];
                   7758: 	}
                   7759:     }
                   7760:     return $output;
                   7761: }
                   7762: 
1.423     albertel 7763: =pod 
                   7764: 
                   7765: =item scantron_parse_scanline
                   7766: 
1.711     bisitz   7767:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 7768: 
                   7769:  Arguments:
1.711     bisitz   7770:     line             - The text of the bubblesheet file line to process
1.423     albertel 7771:     whichline        - Line number
1.711     bisitz   7772:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 7773:     scan_data        - Hash of extra information about the scanline
                   7774:                        (see scantron_getfile for more information)
                   7775:     just_header      - True if should not process question answers but only
                   7776:                        the stuff to the left of the answers.
1.691     raeburn  7777:     randomorder      - True if randomorder in use
                   7778:     randompick       - True if randompick in use
                   7779:     sequence         - Exam folder URL
                   7780:     master_seq       - Ref to array containing symbs in exam folder
                   7781:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   7782:                        (corresponding values are resource objects)
                   7783:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   7784:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   7785:                        are refs to an array of resource objects, ordered
                   7786:                        according to order used for CODE, when randomorder
                   7787:                        and or randompick are in use.
                   7788:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   7789:                        for current line to question number used for same question
                   7790:                         in "Master Sequence" (as seen by Course Coordinator).
                   7791:     startline        - Ref to hash where key is question number (0 is first)
                   7792:                        and value is number of first bubble line for current 
                   7793:                        student or code-based randompick and/or randomorder.
                   7794:     totalref         - Ref of scalar used to score total number of bubble
                   7795:                        lines needed for responses in a scan line (used when
                   7796:                        randompick in use. 
                   7797:     
1.423     albertel 7798:  Returns:
                   7799:    Hash containing the result of parsing the scanline
                   7800: 
                   7801:    Keys are all proceeded by the string 'scantron.'
                   7802: 
                   7803:        CODE    - the CODE in use for this scanline
                   7804:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   7805:                  by the operator
                   7806:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   7807:                             CODEs were selected, but the usage has been
                   7808:                             forced by the operator
1.556     weissno  7809:        ID  - student/employee ID
1.423     albertel 7810:        PaperID - if used, the ID number printed on the sheet when the 
                   7811:                  paper was scanned
                   7812:        FirstName - first name from the sheet
                   7813:        LastName  - last name from the sheet
                   7814: 
                   7815:      if just_header was not true these key may also exist
                   7816: 
1.447     foxr     7817:        missingerror - a list of bubble ranges that are considered to be answers
                   7818:                       to a single question that don't have any bubbles filled in.
                   7819:                       Of the form questionnumber:firstbubblenumber:count.
                   7820:        doubleerror  - a list of bubble ranges that are considered to be answers
                   7821:                       to a single question that have more than one bubble filled in.
                   7822:                       Of the form questionnumber::firstbubblenumber:count
                   7823:    
                   7824:                 In the above, count is the number of bubble responses in the
                   7825:                 input line needed to represent the possible answers to the question.
                   7826:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   7827:                 per line would have count = 2.
                   7828: 
1.423     albertel 7829:        maxquest     - the number of the last bubble line that was parsed
                   7830: 
                   7831:        (<number> starts at 1)
                   7832:        <number>.answer - zero or more letters representing the selected
                   7833:                          letters from the scanline for the bubble line 
                   7834:                          <number>.
                   7835:                          if blank there was either no bubble or there where
                   7836:                          multiple bubbles, (consult the keys missingerror and
                   7837:                          doubleerror if this is an error condition)
                   7838: 
                   7839: =cut
                   7840: 
1.82      albertel 7841: sub scantron_parse_scanline {
1.691     raeburn  7842:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   7843:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   7844:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     7845: 
1.82      albertel 7846:     my %record;
1.691     raeburn  7847:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 7848:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   7849: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   7850: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   7851: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   7852: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 7853: 	    $record{'scantron.CODE'}=substr($data,
                   7854: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 7855: 					    $$scantron_config{'CODElength'});
1.191     albertel 7856: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   7857: 		$record{'scantron.useCODE'}=1;
                   7858: 	    }
1.192     albertel 7859: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   7860: 		$record{'scantron.CODE_ignore_dup'}=1;
                   7861: 	    }
1.82      albertel 7862: 	} else {
                   7863: 	    #FIXME interpret first N questions
                   7864: 	}
                   7865:     }
1.83      albertel 7866:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   7867: 				  $$scantron_config{'IDlength'});
1.157     albertel 7868:     $record{'scantron.PaperID'}=
                   7869: 	substr($data,$$scantron_config{'PaperID'}-1,
                   7870: 	       $$scantron_config{'PaperIDlength'});
                   7871:     $record{'scantron.FirstName'}=
                   7872: 	substr($data,$$scantron_config{'FirstName'}-1,
                   7873: 	       $$scantron_config{'FirstNamelength'});
                   7874:     $record{'scantron.LastName'}=
                   7875: 	substr($data,$$scantron_config{'LastName'}-1,
                   7876: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 7877:     if ($just_header) { return \%record; }
1.194     albertel 7878: 
1.82      albertel 7879:     my @alphabet=('A'..'Z');
                   7880:     my $questnum=0;
1.447     foxr     7881:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   7882: 
1.691     raeburn  7883:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   7884:     if ($randompick || $randomorder) {
                   7885:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   7886:                                          $master_seq,$symb_to_resource,
                   7887:                                          $partids_by_symb,$orderedforcode,
                   7888:                                          $respnumlookup,$startline);
                   7889:         if ($total) {
                   7890:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   7891:         }
                   7892:         if (ref($totalref)) {
                   7893:             $$totalref = $total;
                   7894:         }
                   7895:     }
                   7896:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     7897:     chomp($questions);		# Get rid of any trailing \n.
                   7898:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   7899:     while (length($questions)) {
1.691     raeburn  7900:         my $answers_needed;
                   7901:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7902:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   7903:         } else {
                   7904: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   7905:         }
1.503     raeburn  7906:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   7907:                              || 1;
                   7908:         $questnum++;
                   7909:         my $quest_id = $questnum;
                   7910:         my $currentquest = substr($questions,0,$answer_length);
                   7911:         $questions       = substr($questions,$answer_length);
                   7912:         if (length($currentquest) < $answer_length) { next; }
                   7913: 
1.691     raeburn  7914:         my $subdivided;
                   7915:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7916:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   7917:         } else {
                   7918:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   7919:         }
                   7920:         if ($subdivided =~ /,/) {
1.503     raeburn  7921:             my $subquestnum = 1;
                   7922:             my $subquestions = $currentquest;
1.691     raeburn  7923:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  7924:             foreach my $subans (@subanswers_needed) {
                   7925:                 my $subans_length =
                   7926:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   7927:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   7928:                 $subquestions   = substr($subquestions,$subans_length);
                   7929:                 $quest_id = "$questnum.$subquestnum";
                   7930:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   7931:                     ($$scantron_config{'Qon'} eq 'number')) {
                   7932:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   7933:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  7934:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7935:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7936:                 } else {
                   7937:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  7938:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   7939:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7940:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7941:                 }
                   7942:                 $subquestnum ++;
                   7943:             }
                   7944:         } else {
                   7945:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   7946:                 ($$scantron_config{'Qon'} eq 'number')) {
                   7947:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   7948:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7949:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7950:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7951:             } else {
                   7952:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   7953:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7954:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7955:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7956:             }
                   7957:         }
                   7958:     }
                   7959:     $record{'scantron.maxquest'}=$questnum;
                   7960:     return \%record;
                   7961: }
1.447     foxr     7962: 
1.691     raeburn  7963: sub get_master_seq {
1.788     raeburn  7964:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
1.691     raeburn  7965:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   7966:                    (ref($symb_to_resource) eq 'HASH'));
1.788     raeburn  7967:     if ($need_symb_in_map) {
                   7968:         return unless (ref($symb_for_examcode) eq 'HASH');
                   7969:     }
1.691     raeburn  7970:     my $resource_error;
                   7971:     foreach my $resource (@{$resources}) {
                   7972:         my $ressymb;
                   7973:         if (ref($resource)) {
                   7974:             $ressymb = $resource->symb();
                   7975:             push(@{$master_seq},$ressymb);
                   7976:             $symb_to_resource->{$ressymb} = $resource;
1.788     raeburn  7977:             if ($need_symb_in_map) {
                   7978:                 unless ($resource->is_map()) {
                   7979:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   7980:                     unless (exists($symb_for_examcode->{$map})) {
                   7981:                         $symb_for_examcode->{$map} = $ressymb;
                   7982:                     }
                   7983:                 }
                   7984:             }
1.691     raeburn  7985:         } else {
                   7986:             $resource_error = 1;
                   7987:             last;
                   7988:         }
                   7989:     }
                   7990:     return $resource_error;
                   7991: }
                   7992: 
                   7993: sub get_respnum_lookups {
                   7994:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   7995:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   7996:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   7997:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   7998:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   7999:                    (ref($startline) eq 'HASH'));
                   8000:     my ($user,$scancode);
                   8001:     if ((exists($record->{'scantron.CODE'})) &&
                   8002:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   8003:         $scancode = $record->{'scantron.CODE'};
                   8004:     } else {
                   8005:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   8006:     }
                   8007:     my @mapresources =
                   8008:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   8009:                      $orderedforcode);
                   8010:     my $total = 0;
                   8011:     my $count = 0;
                   8012:     foreach my $resource (@mapresources) {
                   8013:         my $id = $resource->id();
                   8014:         my $symb = $resource->symb();
                   8015:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   8016:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   8017:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   8018:                 if ($respnum ne '') {
                   8019:                     $respnumlookup->{$count} = $respnum;
                   8020:                     $startline->{$count} = $total;
                   8021:                     $total += $bubble_lines_per_response{$respnum};
                   8022:                     $count ++;
                   8023:                 }
                   8024:             }
                   8025:         }
                   8026:     }
                   8027:     return $total;
                   8028: }
                   8029: 
1.503     raeburn  8030: sub scantron_validator_lettnum {
                   8031:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  8032:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   8033:         $randompick,$respnumlookup) = @_;
1.503     raeburn  8034: 
                   8035:     # Qon 'letter' implies for each slot in currquest we have:
                   8036:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   8037:     #    about anything else (esp. a value of Qoff) for missing
                   8038:     #    bubbles.
                   8039:     #
                   8040:     # Qon 'number' implies each slot gives a digit that indexes the
                   8041:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   8042:     #    and * or ? for double bubbles on a single line.
                   8043:     #
1.447     foxr     8044: 
1.503     raeburn  8045:     my $matchon;
                   8046:     if ($$scantron_config{'Qon'} eq 'letter') {
                   8047:         $matchon = '[A-Z]';
                   8048:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   8049:         $matchon = '\d';
                   8050:     }
                   8051:     my $occurrences = 0;
1.691     raeburn  8052:     my $responsenum = $questnum-1;
                   8053:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   8054:        $responsenum = $respnumlookup->{$questnum-1} 
                   8055:     }
                   8056:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8057:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8058:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8059:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8060:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8061:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8062:         my @singlelines = split('',$currquest);
                   8063:         foreach my $entry (@singlelines) {
                   8064:             $occurrences = &occurence_count($entry,$matchon);
                   8065:             if ($occurrences > 1) {
                   8066:                 last;
                   8067:             }
1.691     raeburn  8068:         }
1.503     raeburn  8069:     } else {
                   8070:         $occurrences = &occurence_count($currquest,$matchon); 
                   8071:     }
                   8072:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   8073:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8074:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8075:             my $bubble = substr($currquest,$ans,1);
                   8076:             if ($bubble =~ /$matchon/ ) {
                   8077:                 if ($$scantron_config{'Qon'} eq 'number') {
                   8078:                     if ($bubble == 0) {
                   8079:                         $bubble = 10; 
                   8080:                     }
                   8081:                     $record->{"scantron.$ansnum.answer"} = 
                   8082:                         $alphabet->[$bubble-1];
                   8083:                 } else {
                   8084:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   8085:                 }
                   8086:             } else {
                   8087:                 $record->{"scantron.$ansnum.answer"}='';
                   8088:             }
                   8089:             $ansnum++;
                   8090:         }
                   8091:     } elsif (!defined($currquest)
                   8092:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   8093:             || (&occurence_count($currquest,$matchon) == 0)) {
                   8094:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8095:             $record->{"scantron.$ansnum.answer"}='';
                   8096:             $ansnum++;
                   8097:         }
                   8098:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8099:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   8100:         }
                   8101:     } else {
                   8102:         if ($$scantron_config{'Qon'} eq 'number') {
                   8103:             $currquest = &digits_to_letters($currquest);            
                   8104:         }
                   8105:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8106:             my $bubble = substr($currquest,$ans,1);
                   8107:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   8108:             $ansnum++;
                   8109:         }
                   8110:     }
                   8111:     return $ansnum;
                   8112: }
1.447     foxr     8113: 
1.503     raeburn  8114: sub scantron_validator_positional {
                   8115:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  8116:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   8117:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     8118: 
1.503     raeburn  8119:     # Otherwise there's a positional notation;
                   8120:     # each bubble line requires Qlength items, and there are filled in
                   8121:     # bubbles for each case where there 'Qon' characters.
                   8122:     #
1.447     foxr     8123: 
1.503     raeburn  8124:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     8125: 
1.503     raeburn  8126:     # If the split only gives us one element.. the full length of the
                   8127:     # answer string, no bubbles are filled in:
1.447     foxr     8128: 
1.507     raeburn  8129:     if ($answers_needed eq '') {
                   8130:         return;
                   8131:     }
                   8132: 
1.503     raeburn  8133:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   8134:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8135:             $record->{"scantron.$ansnum.answer"}='';
                   8136:             $ansnum++;
                   8137:         }
                   8138:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8139:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   8140:         }
                   8141:     } elsif (scalar(@array) == 2) {
                   8142:         my $location = length($array[0]);
                   8143:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   8144:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   8145:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8146:             if ($ans eq $line_num) {
                   8147:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   8148:             } else {
                   8149:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   8150:             }
                   8151:             $ansnum++;
                   8152:          }
                   8153:     } else {
                   8154:         #  If there's more than one instance of a bubble character
                   8155:         #  That's a double bubble; with positional notation we can
                   8156:         #  record all the bubbles filled in as well as the
                   8157:         #  fact this response consists of multiple bubbles.
                   8158:         #
1.691     raeburn  8159:         my $responsenum = $questnum-1;
                   8160:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   8161:             $responsenum = $respnumlookup->{$questnum-1}
                   8162:         }
                   8163:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8164:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8165:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8166:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8167:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8168:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8169:             my $doubleerror = 0;
                   8170:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   8171:                    (!$doubleerror)) {
                   8172:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   8173:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   8174:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   8175:                if (length(@currarray) > 2) {
                   8176:                    $doubleerror = 1;
                   8177:                } 
                   8178:             }
                   8179:             if ($doubleerror) {
                   8180:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8181:             }
                   8182:         } else {
                   8183:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8184:         }
                   8185:         my $item = $ansnum;
                   8186:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8187:             $record->{"scantron.$item.answer"} = '';
                   8188:             $item ++;
                   8189:         }
1.447     foxr     8190: 
1.503     raeburn  8191:         my @ans=@array;
                   8192:         my $i=0;
                   8193:         my $increment = 0;
                   8194:         while ($#ans) {
                   8195:             $i+=length($ans[0]) + $increment;
                   8196:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   8197:             my $bubble = $i%$$scantron_config{'Qlength'};
                   8198:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   8199:             shift(@ans);
                   8200:             $increment = 1;
                   8201:         }
                   8202:         $ansnum += $answers_needed;
1.82      albertel 8203:     }
1.503     raeburn  8204:     return $ansnum;
1.82      albertel 8205: }
                   8206: 
1.423     albertel 8207: =pod
                   8208: 
                   8209: =item scantron_add_delay
                   8210: 
                   8211:    Adds an error message that occurred during the grading phase to a
                   8212:    queue of messages to be shown after grading pass is complete
                   8213: 
                   8214:  Arguments:
1.424     albertel 8215:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 8216:    $scanline    - the scanline that caused the error
                   8217:    $errormesage - the error message
                   8218:    $errorcode   - a numeric code for the error
                   8219: 
                   8220:  Side Effects:
1.424     albertel 8221:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 8222: 
                   8223: =cut
                   8224: 
1.82      albertel 8225: sub scantron_add_delay {
1.140     albertel 8226:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   8227:     push(@$delayqueue,
                   8228: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   8229: 	  'ecode' => $errorcode }
                   8230: 	 );
1.82      albertel 8231: }
                   8232: 
1.423     albertel 8233: =pod
                   8234: 
                   8235: =item scantron_find_student
                   8236: 
1.424     albertel 8237:    Finds the username for the current scanline
                   8238: 
                   8239:   Arguments:
                   8240:    $scantron_record - hash result from scantron_parse_scanline
                   8241:    $scan_data       - hash of correction information 
                   8242:                       (see &scantron_getfile() form more information)
                   8243:    $idmap           - hash from &username_to_idmap()
                   8244:    $line            - number of current scanline
                   8245:  
                   8246:   Returns:
                   8247:    Either 'username:domain' or undef if unknown
                   8248: 
1.423     albertel 8249: =cut
                   8250: 
1.82      albertel 8251: sub scantron_find_student {
1.157     albertel 8252:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 8253:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 8254:     if ($scanID =~ /^\s*$/) {
                   8255:  	return &scan_data($scan_data,"$line.user");
                   8256:     }
1.83      albertel 8257:     foreach my $id (keys(%$idmap)) {
1.157     albertel 8258:  	if (lc($id) eq lc($scanID)) {
                   8259:  	    return $$idmap{$id};
                   8260:  	}
1.83      albertel 8261:     }
                   8262:     return undef;
                   8263: }
                   8264: 
1.423     albertel 8265: =pod
                   8266: 
                   8267: =item scantron_filter
                   8268: 
1.424     albertel 8269:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   8270:    hidden resources was selected
                   8271: 
1.423     albertel 8272: =cut
                   8273: 
1.83      albertel 8274: sub scantron_filter {
                   8275:     my ($curres)=@_;
1.331     albertel 8276: 
                   8277:     if (ref($curres) && $curres->is_problem()) {
                   8278: 	# if the user has asked to not have either hidden
                   8279: 	# or 'randomout' controlled resources to be graded
                   8280: 	# don't include them
                   8281: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   8282: 	    && $curres->randomout) {
                   8283: 	    return 0;
                   8284: 	}
1.83      albertel 8285: 	return 1;
                   8286:     }
                   8287:     return 0;
1.82      albertel 8288: }
                   8289: 
1.423     albertel 8290: =pod
                   8291: 
                   8292: =item scantron_process_corrections
                   8293: 
1.424     albertel 8294:    Gets correction information out of submitted form data and corrects
                   8295:    the scanline
                   8296: 
1.423     albertel 8297: =cut
                   8298: 
1.157     albertel 8299: sub scantron_process_corrections {
                   8300:     my ($r) = @_;
1.754     raeburn  8301:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8302:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8303:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 8304:     my $which=$env{'form.scantron_line'};
1.200     albertel 8305:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 8306:     my ($skip,$err,$errmsg);
1.257     albertel 8307:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 8308: 	$skip=1;
1.257     albertel 8309:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   8310: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   8311: 	    $env{'form.scantron_domain'};
1.157     albertel 8312: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   8313: 	($line,$err,$errmsg)=
                   8314: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   8315: 				     'ID',{'newid'=>$newid,
1.257     albertel 8316: 				    'username'=>$env{'form.scantron_username'},
                   8317: 				    'domain'=>$env{'form.scantron_domain'}});
                   8318:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   8319: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 8320: 	my $newCODE;
1.192     albertel 8321: 	my %args;
1.190     albertel 8322: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 8323: 	    $newCODE='use_unfound';
1.190     albertel 8324: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 8325: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 8326: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 8327: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 8328: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 8329: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 8330: 	}
1.257     albertel 8331: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 8332: 	    $args{'CODE_ignore_dup'}=1;
                   8333: 	}
                   8334: 	$args{'CODE'}=$newCODE;
1.186     albertel 8335: 	($line,$err,$errmsg)=
                   8336: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 8337: 				     'CODE',\%args);
1.257     albertel 8338:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   8339: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 8340: 	    ($line,$err,$errmsg)=
                   8341: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   8342: 					 $which,'answer',
                   8343: 					 { 'question'=>$question,
1.503     raeburn  8344: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   8345:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 8346: 	    if ($err) { last; }
                   8347: 	}
                   8348:     }
                   8349:     if ($err) {
1.703     bisitz   8350:         $r->print(
                   8351:             '<p class="LC_error">'
                   8352:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   8353:                 $errmsg)
1.704     raeburn  8354:            .'</p>');
1.157     albertel 8355:     } else {
1.200     albertel 8356: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 8357: 	&scantron_putfile($scanlines,$scan_data);
                   8358:     }
                   8359: }
                   8360: 
1.423     albertel 8361: =pod
                   8362: 
                   8363: =item reset_skipping_status
                   8364: 
1.424     albertel 8365:    Forgets the current set of remember skipped scanlines (and thus
                   8366:    reverts back to considering all lines in the
                   8367:    scantron_skipped_<filename> file)
                   8368: 
1.423     albertel 8369: =cut
                   8370: 
1.200     albertel 8371: sub reset_skipping_status {
                   8372:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8373:     &scan_data($scan_data,'remember_skipping',undef,1);
                   8374:     &scantron_putfile(undef,$scan_data);
                   8375: }
                   8376: 
1.423     albertel 8377: =pod
                   8378: 
                   8379: =item start_skipping
                   8380: 
1.424     albertel 8381:    Marks a scanline to be skipped. 
                   8382: 
1.423     albertel 8383: =cut
                   8384: 
1.376     albertel 8385: sub start_skipping {
1.200     albertel 8386:     my ($scan_data,$i)=@_;
                   8387:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8388:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   8389: 	$remembered{$i}=2;
                   8390:     } else {
                   8391: 	$remembered{$i}=1;
                   8392:     }
1.200     albertel 8393:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   8394: }
                   8395: 
1.423     albertel 8396: =pod
                   8397: 
                   8398: =item should_be_skipped
                   8399: 
1.424     albertel 8400:    Checks whether a scanline should be skipped.
                   8401: 
1.423     albertel 8402: =cut
                   8403: 
1.200     albertel 8404: sub should_be_skipped {
1.376     albertel 8405:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 8406:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 8407: 	# not redoing old skips
1.376     albertel 8408: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 8409: 	return 0;
                   8410:     }
                   8411:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8412: 
                   8413:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   8414: 	return 0;
                   8415:     }
1.200     albertel 8416:     return 1;
                   8417: }
                   8418: 
1.423     albertel 8419: =pod
                   8420: 
                   8421: =item remember_current_skipped
                   8422: 
1.424     albertel 8423:    Discovers what scanlines are in the scantron_skipped_<filename>
                   8424:    file and remembers them into scan_data for later use.
                   8425: 
1.423     albertel 8426: =cut
                   8427: 
1.200     albertel 8428: sub remember_current_skipped {
                   8429:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8430:     my %to_remember;
                   8431:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8432: 	if ($scanlines->{'skipped'}[$i]) {
                   8433: 	    $to_remember{$i}=1;
                   8434: 	}
                   8435:     }
1.376     albertel 8436: 
1.200     albertel 8437:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   8438:     &scantron_putfile(undef,$scan_data);
                   8439: }
                   8440: 
1.423     albertel 8441: =pod
                   8442: 
                   8443: =item check_for_error
                   8444: 
1.424     albertel 8445:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  8446:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 8447:     something went wrong.
                   8448: 
1.423     albertel 8449: =cut
                   8450: 
1.200     albertel 8451: sub check_for_error {
                   8452:     my ($r,$result)=@_;
                   8453:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 8454: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 8455:     }
                   8456: }
1.157     albertel 8457: 
1.423     albertel 8458: =pod
                   8459: 
                   8460: =item scantron_warning_screen
                   8461: 
1.424     albertel 8462:    Interstitial screen to make sure the operator has selected the
                   8463:    correct options before we start the validation phase.
                   8464: 
1.423     albertel 8465: =cut
                   8466: 
1.203     albertel 8467: sub scantron_warning_screen {
1.650     raeburn  8468:     my ($button_text,$symb)=@_;
1.257     albertel 8469:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  8470:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 8471:     my $CODElist;
1.284     albertel 8472:     if ($scantron_config{'CODElocation'} &&
                   8473: 	$scantron_config{'CODEstart'} &&
                   8474: 	$scantron_config{'CODElength'}) {
                   8475: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   8476: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 8477: 	$CODElist=
1.492     albertel 8478: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 8479: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 8480:     }
1.663     raeburn  8481:     my $lastbubblepoints;
                   8482:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8483:         $lastbubblepoints =
                   8484:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   8485:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   8486:     }
1.770     raeburn  8487:     return '
1.203     albertel 8488: <p>
1.492     albertel 8489: <span class="LC_warning">
1.705     raeburn  8490: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 8491: </p>
                   8492: <table>
1.492     albertel 8493: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   8494: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  8495: '.$CODElist.$lastbubblepoints.'
1.203     albertel 8496: </table>
1.680     raeburn  8497: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  8498: '.&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  8499: ';
1.203     albertel 8500: }
                   8501: 
1.423     albertel 8502: =pod
                   8503: 
                   8504: =item scantron_do_warning
                   8505: 
1.424     albertel 8506:    Check if the operator has picked something for all required
                   8507:    fields. Error out if something is missing.
                   8508: 
1.423     albertel 8509: =cut
                   8510: 
1.203     albertel 8511: sub scantron_do_warning {
1.608     www      8512:     my ($r,$symb)=@_;
1.203     albertel 8513:     if (!$symb) {return '';}
1.324     albertel 8514:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 8515:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 8516:     if ( $env{'form.selectpage'} eq '' ||
                   8517: 	 $env{'form.scantron_selectfile'} eq '' ||
                   8518: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  8519: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 8520: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 8521: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 8522: 	} 
1.257     albertel 8523: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  8524: 	    $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  8525: 	}
1.257     albertel 8526: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  8527: 	    $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  8528: 	}
1.237     albertel 8529:     } else {
1.650     raeburn  8530: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  8531:         my ($checksec,@possibles) = &gradable_sections();
                   8532:         my $gradesections;
                   8533:         if ($checksec) {
                   8534:             my $file=$env{'form.scantron_selectfile'};
                   8535:             if (&valid_file($file)) {
                   8536:                 my %bysec = &scantron_get_sections();
                   8537:                 my $table;
                   8538:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   8539:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   8540:                     $table = &Apache::loncommon::start_data_table()."\n".
                   8541:                              &Apache::loncommon::start_data_table_header_row().
                   8542:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   8543:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   8544:                     if ($bysec{'none'}) {
                   8545:                         $table .= &Apache::loncommon::start_data_table_row().
                   8546:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   8547:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8548:                     }
                   8549:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   8550:                         next if ($sec eq 'none');
                   8551:                         $table .= &Apache::loncommon::start_data_table_row().
                   8552:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   8553:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8554:                     }
                   8555:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   8556:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   8557:                                       '<p>'.$table.'</p>';
                   8558:                     if (@possibles) {
                   8559:                         $gradesections .= '<p>'.
                   8560:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   8561:                                               scalar(@possibles)).'<br />'.
                   8562:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   8563:                                               '<i>'.$checksec.'</i>').' ';
                   8564:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   8565:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   8566:                         }
                   8567:                         $gradesections .= '</p>';
                   8568:                     }
                   8569:                 }
                   8570:             } else {
                   8571:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   8572:             }
                   8573:         }
1.663     raeburn  8574:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 8575: 	$r->print('
1.770     raeburn  8576: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 8577: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 8578: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 8579: ');
1.237     albertel 8580:     }
1.614     www      8581:     $r->print("</form><br />");
1.203     albertel 8582:     return '';
                   8583: }
                   8584: 
1.423     albertel 8585: =pod
                   8586: 
                   8587: =item scantron_form_start
                   8588: 
1.424     albertel 8589:     html hidden input for remembering all selected grading options
                   8590: 
1.423     albertel 8591: =cut
                   8592: 
1.203     albertel 8593: sub scantron_form_start {
                   8594:     my ($max_bubble)=@_;
                   8595:     my $result= <<SCANTRONFORM;
                   8596: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 8597:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   8598:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   8599:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 8600:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 8601:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   8602:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   8603:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   8604:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 8605:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 8606: SCANTRONFORM
1.447     foxr     8607: 
                   8608:   my $line = 0;
                   8609:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   8610:        my $chunk =
                   8611: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     8612:        $chunk .=
                   8613: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  8614:        $chunk .= 
                   8615:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  8616:        $chunk .=
                   8617:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  8618:        $chunk .=
                   8619:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     8620:        $result .= $chunk;
                   8621:        $line++;
1.691     raeburn  8622:     }
1.203     albertel 8623:     return $result;
                   8624: }
                   8625: 
1.423     albertel 8626: =pod
                   8627: 
                   8628: =item scantron_validate_file
                   8629: 
1.659     raeburn  8630:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 8631: 
                   8632:     Also processes any necessary information resets that need to
                   8633:     occur before validation begins (ignore previous corrections,
                   8634:     restarting the skipped records processing)
                   8635: 
1.423     albertel 8636: =cut
                   8637: 
1.157     albertel 8638: sub scantron_validate_file {
1.608     www      8639:     my ($r,$symb) = @_;
1.157     albertel 8640:     if (!$symb) {return '';}
1.324     albertel 8641:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 8642:     
1.703     bisitz   8643:     # do the detection of only doing skipped records first before we delete
1.424     albertel 8644:     # them when doing the corrections reset
1.257     albertel 8645:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 8646: 	&reset_skipping_status();
                   8647:     }
1.257     albertel 8648:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 8649: 	&remember_current_skipped();
1.257     albertel 8650: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 8651:     }
                   8652: 
1.257     albertel 8653:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 8654: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   8655: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   8656: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 8657: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 8658:     }
1.200     albertel 8659: 
1.257     albertel 8660:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 8661: 	&scantron_process_corrections($r);
                   8662:     }
1.770     raeburn  8663: 
                   8664:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   8665:     my ($checksec,@gradable);
                   8666:     if ($env{'request.course.sec'}) {
                   8667:         ($checksec,my @possibles) = &gradable_sections();
                   8668:         if ($checksec) {
                   8669:             if (@possibles) {
                   8670:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   8671:                 if (@chosensecs) {
                   8672:                     foreach my $sec (@chosensecs) {
                   8673:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   8674:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   8675:                                 push(@gradable,$sec);
                   8676:                             }
                   8677:                         }
                   8678:                     }
                   8679:                 }
                   8680:             }
                   8681:             $r->print('<p><table>');
                   8682:             if (@gradable) {
                   8683:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   8684:                 $r->print(
                   8685:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   8686:             } else {
                   8687:                 $r->print(
                   8688:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   8689:             }
                   8690:             $r->print('</table></p>');
                   8691:         }
                   8692:     }
                   8693:     $r->rflush();
                   8694: 
1.157     albertel 8695:     #get the student pick code ready
                   8696:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  8697:     my $nav_error;
1.754     raeburn  8698:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8699:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8700:     if ($nav_error) {
                   8701:         $r->print(&navmap_errormsg());
                   8702:         return '';
                   8703:     }
1.203     albertel 8704:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  8705:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8706:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   8707:     }
1.157     albertel 8708:     $r->print($result);
                   8709:     
1.334     albertel 8710:     my @validate_phases=( 'sequence',
                   8711: 			  'ID',
1.157     albertel 8712: 			  'CODE',
                   8713: 			  'doublebubble',
                   8714: 			  'missingbubbles');
1.257     albertel 8715:     if (!$env{'form.validatepass'}) {
                   8716: 	$env{'form.validatepass'} = 0;
1.157     albertel 8717:     }
1.257     albertel 8718:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  8719:     my %skipbysec=();
1.448     foxr     8720: 
1.157     albertel 8721:     my $stop=0;
                   8722:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  8723: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 8724: 	$r->rflush();
1.691     raeburn  8725:      
1.157     albertel 8726: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   8727: 	{
                   8728: 	    no strict 'refs';
1.770     raeburn  8729:             my @extras=();
                   8730:             if ($validate_phases[$currentphase] eq 'ID') {
                   8731:                 @extras = (\%skipbysec,$checksec,@gradable);
                   8732:             }
                   8733: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 8734: 	}
                   8735:     }
                   8736:     if (!$stop) {
1.650     raeburn  8737: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  8738:         my $secinfo;
                   8739:         if (keys(%skipbysec) > 0) {
                   8740:             my $seclist = '<ul>';
                   8741:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   8742:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   8743:             }
                   8744:             $seclist .= '</ul>';
                   8745:             $secinfo = '<p class="LC_info">'.
                   8746:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   8747:                            $seclist).
                   8748:                        '</p>';
                   8749:         }
1.542     raeburn  8750: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  8751:                   $secinfo.$warning.
1.542     raeburn  8752:                   &mt('Perform verification for each student after storage of submissions?').
                   8753:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   8754:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   8755:                   ('&nbsp;'x3).'<label>'.
                   8756:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   8757:                   '</label></span><br />'.
                   8758:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  8759:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  8760:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   8761:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 8762:     } else {
                   8763: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   8764: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   8765:     }
                   8766:     if ($stop) {
1.334     albertel 8767: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  8768: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 8769: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 8770: 
1.650     raeburn  8771: 	    $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 8772: 	} else {
1.503     raeburn  8773:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  8774: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  8775:             } else {
1.539     riegler  8776:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  8777:             }
1.492     albertel 8778: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   8779: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   8780: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 8781: 	}
1.157     albertel 8782:     }
1.614     www      8783:     $r->print(" </form><br />");
1.157     albertel 8784:     return '';
                   8785: }
                   8786: 
1.423     albertel 8787: 
                   8788: =pod
                   8789: 
                   8790: =item scantron_remove_file
                   8791: 
1.659     raeburn  8792:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 8793:    scantron_original_<filename> is never removed
                   8794: 
                   8795: 
1.423     albertel 8796: =cut
                   8797: 
1.200     albertel 8798: sub scantron_remove_file {
1.192     albertel 8799:     my ($which)=@_;
1.257     albertel 8800:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8801:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8802:     my $file='scantron_';
1.200     albertel 8803:     if ($which eq 'corrected' || $which eq 'skipped') {
                   8804: 	$file.=$which.'_';
1.192     albertel 8805:     } else {
                   8806: 	return 'refused';
                   8807:     }
1.257     albertel 8808:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 8809:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   8810: }
                   8811: 
1.423     albertel 8812: 
                   8813: =pod
                   8814: 
                   8815: =item scantron_remove_scan_data
                   8816: 
1.659     raeburn  8817:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 8818:    data file.  (In the case that both the are doing skipped records we need
                   8819:    to remember the old skipped lines for the time being so that element
                   8820:    persists for a while.)
                   8821: 
1.423     albertel 8822: =cut
                   8823: 
1.200     albertel 8824: sub scantron_remove_scan_data {
1.257     albertel 8825:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8826:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8827:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   8828:     my @todelete;
1.257     albertel 8829:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 8830:     foreach my $key (@keys) {
                   8831: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 8832: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 8833: 		$key=~/remember_skipping/) {
                   8834: 		next;
                   8835: 	    }
1.192     albertel 8836: 	    push(@todelete,$key);
                   8837: 	}
                   8838:     }
1.200     albertel 8839:     my $result;
1.192     albertel 8840:     if (@todelete) {
1.491     albertel 8841: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   8842: 				       \@todelete,$cdom,$cname);
                   8843:     } else {
                   8844: 	$result = 'ok';
1.192     albertel 8845:     }
                   8846:     return $result;
                   8847: }
                   8848: 
1.423     albertel 8849: 
                   8850: =pod
                   8851: 
                   8852: =item scantron_getfile
                   8853: 
1.659     raeburn  8854:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 8855:     the scan_data hash
                   8856:   
                   8857:   Arguments:
                   8858:     None
                   8859: 
                   8860:   Returns:
                   8861:     2 hash references
                   8862: 
                   8863:      - first one has 
                   8864:          orig      -
                   8865:          corrected -
                   8866:          skipped   -  each of which points to an array ref of the specified
                   8867:                       file broken up into individual lines
                   8868:          count     - number of scanlines
                   8869:  
                   8870:      - second is the scan_data hash possible keys are
1.425     albertel 8871:        ($number refers to scanline numbered $number and thus the key affects
                   8872:         only that scanline
                   8873:         $bubline refers to the specific bubble line element and the aspects
                   8874:         refers to that specific bubble line element)
                   8875: 
                   8876:        $number.user - username:domain to use
                   8877:        $number.CODE_ignore_dup 
                   8878:                     - ignore the duplicate CODE error 
                   8879:        $number.useCODE
                   8880:                     - use the CODE in the scanline as is
                   8881:        $number.no_bubble.$bubline
                   8882:                     - it is valid that there is no bubbled in bubble
                   8883:                       at $number $bubline
                   8884:        remember_skipping
                   8885:                     - a frozen hash containing keys of $number and values
                   8886:                       of either 
                   8887:                         1 - we are on a 'do skipped records pass' and plan
                   8888:                             on processing this line
                   8889:                         2 - we are on a 'do skipped records pass' and this
                   8890:                             scanline has been marked to skip yet again
1.424     albertel 8891: 
1.423     albertel 8892: =cut
                   8893: 
1.157     albertel 8894: sub scantron_getfile {
1.200     albertel 8895:     #FIXME really would prefer a scantron directory
1.257     albertel 8896:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8897:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 8898:     my $lines;
                   8899:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8900: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 8901:     my %scanlines;
                   8902:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   8903:     my $temp=$scanlines{'orig'};
                   8904:     $scanlines{'count'}=$#$temp;
                   8905: 
                   8906:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8907: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 8908:     if ($lines eq '-1') {
                   8909: 	$scanlines{'corrected'}=[];
                   8910:     } else {
                   8911: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   8912:     }
                   8913:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8914: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 8915:     if ($lines eq '-1') {
                   8916: 	$scanlines{'skipped'}=[];
                   8917:     } else {
                   8918: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   8919:     }
1.175     albertel 8920:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 8921:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   8922:     my %scan_data = @tmp;
                   8923:     return (\%scanlines,\%scan_data);
                   8924: }
                   8925: 
1.423     albertel 8926: =pod
                   8927: 
                   8928: =item lonnet_putfile
                   8929: 
1.424     albertel 8930:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   8931: 
                   8932:  Arguments:
                   8933:    $contents - data to store
                   8934:    $filename - filename to store $contents into
                   8935: 
                   8936:  Returns:
                   8937:    result value from &Apache::lonnet::finishuserfileupload
                   8938: 
1.423     albertel 8939: =cut
                   8940: 
1.157     albertel 8941: sub lonnet_putfile {
                   8942:     my ($contents,$filename)=@_;
1.257     albertel 8943:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8944:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8945:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 8946:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 8947: 
                   8948: }
                   8949: 
1.423     albertel 8950: =pod
                   8951: 
                   8952: =item scantron_putfile
                   8953: 
1.659     raeburn  8954:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 8955:     scan_data hash. (Does not modify the original version only the
                   8956:     corrected and skipped versions.
                   8957: 
                   8958:  Arguments:
                   8959:     $scanlines - hash ref that looks like the first return value from
                   8960:                  &scantron_getfile()
                   8961:     $scan_data - hash ref that looks like the second return value from
                   8962:                  &scantron_getfile()
                   8963: 
1.423     albertel 8964: =cut
                   8965: 
1.157     albertel 8966: sub scantron_putfile {
                   8967:     my ($scanlines,$scan_data) = @_;
1.200     albertel 8968:     #FIXME really would prefer a scantron directory
1.257     albertel 8969:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8970:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 8971:     if ($scanlines) {
                   8972: 	my $prefix='scantron_';
1.157     albertel 8973: # no need to update orig, shouldn't change
                   8974: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 8975: #		    $env{'form.scantron_selectfile'});
1.200     albertel 8976: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   8977: 			$prefix.'corrected_'.
1.257     albertel 8978: 			$env{'form.scantron_selectfile'});
1.200     albertel 8979: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   8980: 			$prefix.'skipped_'.
1.257     albertel 8981: 			$env{'form.scantron_selectfile'});
1.200     albertel 8982:     }
1.175     albertel 8983:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 8984: }
                   8985: 
1.423     albertel 8986: =pod
                   8987: 
                   8988: =item scantron_get_line
                   8989: 
1.424     albertel 8990:    Returns the correct version of the scanline
                   8991: 
                   8992:  Arguments:
                   8993:     $scanlines - hash ref that looks like the first return value from
                   8994:                  &scantron_getfile()
                   8995:     $scan_data - hash ref that looks like the second return value from
                   8996:                  &scantron_getfile()
                   8997:     $i         - number of the requested line (starts at 0)
                   8998: 
                   8999:  Returns:
                   9000:    A scanline, (either the original or the corrected one if it
                   9001:    exists), or undef if the requested scanline should be
                   9002:    skipped. (Either because it's an skipped scanline, or it's an
                   9003:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   9004:    pass.
                   9005: 
1.423     albertel 9006: =cut
                   9007: 
1.157     albertel 9008: sub scantron_get_line {
1.200     albertel 9009:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 9010:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   9011:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 9012:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   9013:     return $scanlines->{'orig'}[$i]; 
                   9014: }
                   9015: 
1.423     albertel 9016: =pod
                   9017: 
                   9018: =item scantron_todo_count
                   9019: 
1.424     albertel 9020:     Counts the number of scanlines that need processing.
                   9021: 
                   9022:  Arguments:
                   9023:     $scanlines - hash ref that looks like the first return value from
                   9024:                  &scantron_getfile()
                   9025:     $scan_data - hash ref that looks like the second return value from
                   9026:                  &scantron_getfile()
                   9027: 
                   9028:  Returns:
                   9029:     $count - number of scanlines to process
                   9030: 
1.423     albertel 9031: =cut
                   9032: 
1.200     albertel 9033: sub get_todo_count {
                   9034:     my ($scanlines,$scan_data)=@_;
                   9035:     my $count=0;
                   9036:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   9037: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   9038: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9039: 	$count++;
                   9040:     }
                   9041:     return $count;
                   9042: }
                   9043: 
1.423     albertel 9044: =pod
                   9045: 
                   9046: =item scantron_put_line
                   9047: 
1.659     raeburn  9048:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 9049:     data file.
                   9050: 
                   9051:  Arguments:
                   9052:     $scanlines - hash ref that looks like the first return value from
                   9053:                  &scantron_getfile()
                   9054:     $scan_data - hash ref that looks like the second return value from
                   9055:                  &scantron_getfile()
                   9056:     $i         - line number to update
                   9057:     $newline   - contents of the updated scanline
                   9058:     $skip      - if true make the line for skipping and update the
                   9059:                  'skipped' file
                   9060: 
1.423     albertel 9061: =cut
                   9062: 
1.157     albertel 9063: sub scantron_put_line {
1.200     albertel 9064:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 9065:     if ($skip) {
                   9066: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 9067: 	&start_skipping($scan_data,$i);
1.157     albertel 9068: 	return;
                   9069:     }
                   9070:     $scanlines->{'corrected'}[$i]=$newline;
                   9071: }
                   9072: 
1.423     albertel 9073: =pod
                   9074: 
                   9075: =item scantron_clear_skip
                   9076: 
1.424     albertel 9077:    Remove a line from the 'skipped' file
                   9078: 
                   9079:  Arguments:
                   9080:     $scanlines - hash ref that looks like the first return value from
                   9081:                  &scantron_getfile()
                   9082:     $scan_data - hash ref that looks like the second return value from
                   9083:                  &scantron_getfile()
                   9084:     $i         - line number to update
                   9085: 
1.423     albertel 9086: =cut
                   9087: 
1.376     albertel 9088: sub scantron_clear_skip {
                   9089:     my ($scanlines,$scan_data,$i)=@_;
                   9090:     if (exists($scanlines->{'skipped'}[$i])) {
                   9091: 	undef($scanlines->{'skipped'}[$i]);
                   9092: 	return 1;
                   9093:     }
                   9094:     return 0;
                   9095: }
                   9096: 
1.423     albertel 9097: =pod
                   9098: 
                   9099: =item scantron_filter_not_exam
                   9100: 
1.424     albertel 9101:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   9102:    filter out resources that are not marked as 'exam' mode
                   9103: 
1.423     albertel 9104: =cut
                   9105: 
1.334     albertel 9106: sub scantron_filter_not_exam {
                   9107:     my ($curres)=@_;
                   9108:     
                   9109:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   9110: 	# if the user has asked to not have either hidden
                   9111: 	# or 'randomout' controlled resources to be graded
                   9112: 	# don't include them
                   9113: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   9114: 	    && $curres->randomout) {
                   9115: 	    return 0;
                   9116: 	}
                   9117: 	return 1;
                   9118:     }
                   9119:     return 0;
                   9120: }
                   9121: 
1.423     albertel 9122: =pod
                   9123: 
                   9124: =item scantron_validate_sequence
                   9125: 
1.424     albertel 9126:     Validates the selected sequence, checking for resource that are
                   9127:     not set to exam mode.
                   9128: 
1.423     albertel 9129: =cut
                   9130: 
1.334     albertel 9131: sub scantron_validate_sequence {
                   9132:     my ($r,$currentphase) = @_;
                   9133: 
                   9134:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9135:     unless (ref($navmap)) {
                   9136:         $r->print(&navmap_errormsg());
                   9137:         return (1,$currentphase);
                   9138:     }
1.334     albertel 9139:     my (undef,undef,$sequence)=
                   9140: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9141: 
                   9142:     my $map=$navmap->getResourceByUrl($sequence);
                   9143: 
                   9144:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   9145:                                     value="ignore" />');
                   9146:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   9147: 	my @resources=
                   9148: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   9149: 	if (@resources) {
1.675     bisitz   9150: 	    $r->print(
                   9151:                 '<p class="LC_warning">'
                   9152:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   9153:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   9154:                    .' work correctly.')
                   9155:                .'</p>'
                   9156:             );
1.334     albertel 9157: 	    return (1,$currentphase);
                   9158: 	}
                   9159:     }
                   9160: 
                   9161:     return (0,$currentphase+1);
                   9162: }
                   9163: 
1.423     albertel 9164: 
                   9165: 
1.157     albertel 9166: sub scantron_validate_ID {
1.770     raeburn  9167:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 9168:     
                   9169:     #get student info
                   9170:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9171:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  9172:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 9173: 
                   9174:     #get scantron line setup
1.754     raeburn  9175:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9176:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  9177: 
                   9178:     my $nav_error;
1.649     raeburn  9179:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  9180:     if ($nav_error) {
                   9181:         $r->print(&navmap_errormsg());
                   9182:         return(1,$currentphase);
                   9183:     }
1.157     albertel 9184: 
                   9185:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  9186:     my $unsavedskips = 0;
1.157     albertel 9187:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9188: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9189: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9190: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9191: 						 $scan_data);
                   9192: 	my $id=$$scan_record{'scantron.ID'};
                   9193: 	my $found;
                   9194: 	foreach my $checkid (keys(%idmap)) {
                   9195: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   9196: 	}
                   9197: 	if ($found) {
                   9198: 	    my $username=$idmap{$found};
1.770     raeburn  9199:             if ($checksec) {
                   9200:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   9201:                     my $stusec = $classlist->{$username}->[$secidx];
                   9202:                     if ($stusec ne $checksec) {
                   9203:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9204:                             my $skip=1;
                   9205:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9206:                             if (ref($skipbysec) eq 'HASH') {
                   9207:                                 if ($stusec eq '') {
                   9208:                                     $skipbysec->{'none'} ++;
                   9209:                                 } else {
                   9210:                                     $skipbysec->{$stusec} ++;
                   9211:                                 }
                   9212:                             }
                   9213:                             $unsavedskips ++;
                   9214:                             next;
                   9215:                         }
                   9216:                     }
                   9217:                 }
                   9218:             }
1.157     albertel 9219: 	    if ($found{'ids'}{$found}) {
                   9220: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9221: 					 $line,'duplicateID',$found);
1.770     raeburn  9222:                 if ($unsavedskips) {
                   9223:                     &scantron_putfile($scanlines,$scan_data);
                   9224:                     $unsavedskips = 0;
                   9225:                 }
1.194     albertel 9226: 		return(1,$currentphase);
1.157     albertel 9227: 	    } elsif ($found{'usernames'}{$username}) {
                   9228: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9229: 					 $line,'duplicateID',$username);
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: 	    }
1.186     albertel 9236: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 9237: 	    $found{'ids'}{$found}++;
                   9238: 	    $found{'usernames'}{$username}++;
                   9239: 	} else {
                   9240: 	    if ($id =~ /^\s*$/) {
1.158     albertel 9241: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  9242:                 if (($checksec && $username ne '')) {
                   9243:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   9244:                         my $stusec = $classlist->{$username}->[$secidx];
                   9245:                         if ($stusec ne $checksec) {
                   9246:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9247:                                 my $skip=1;
                   9248:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9249:                                 if (ref($skipbysec) eq 'HASH') {
                   9250:                                     if ($stusec eq '') {
                   9251:                                         $skipbysec->{'none'} ++;
                   9252:                                     } else {
                   9253:                                         $skipbysec->{$stusec} ++;
                   9254:                                     }
                   9255:                                 }
                   9256:                                 $unsavedskips ++;
                   9257:                                 next;
                   9258:                             }
                   9259:                         }
                   9260:                     }
                   9261: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 9262: 		    &scantron_get_correction($r,$i,$scan_record,
                   9263: 					     \%scantron_config,
                   9264: 					     $line,'duplicateID',$username);
1.770     raeburn  9265:                     if ($unsavedskips) {
                   9266:                         &scantron_putfile($scanlines,$scan_data);
                   9267:                         $unsavedskips = 0;
                   9268:                     }
1.194     albertel 9269: 		    return(1,$currentphase);
1.157     albertel 9270: 		} elsif (!defined($username)) {
                   9271: 		    &scantron_get_correction($r,$i,$scan_record,
                   9272: 					     \%scantron_config,
                   9273: 					     $line,'incorrectID');
1.770     raeburn  9274:                     if ($unsavedskips) {
                   9275:                         &scantron_putfile($scanlines,$scan_data);
                   9276:                         $unsavedskips = 0;
                   9277:                     }
1.194     albertel 9278: 		    return(1,$currentphase);
1.157     albertel 9279: 		}
                   9280: 		$found{'usernames'}{$username}++;
                   9281: 	    } else {
                   9282: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9283: 					 $line,'incorrectID');
1.770     raeburn  9284:                 if ($unsavedskips) {
                   9285:                     &scantron_putfile($scanlines,$scan_data);
                   9286:                     $unsavedskips = 0;
                   9287:                 }
1.194     albertel 9288: 		return(1,$currentphase);
1.157     albertel 9289: 	    }
                   9290: 	}
                   9291:     }
1.770     raeburn  9292:     if ($unsavedskips) {
                   9293:         &scantron_putfile($scanlines,$scan_data);
                   9294:         $unsavedskips = 0;
                   9295:     }
1.157     albertel 9296:     return (0,$currentphase+1);
                   9297: }
                   9298: 
1.770     raeburn  9299: sub scantron_get_sections {
                   9300:     my %bysec;
                   9301:     if ($env{'form.scantron_format'} ne '') {
                   9302:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   9303:         my ($scanlines,$scan_data)=&scantron_getfile();
                   9304:         my $classlist=&Apache::loncoursedata::get_classlist();
                   9305:         my %idmap=&username_to_idmap($classlist);
                   9306:         foreach my $key (keys(%idmap)) {
                   9307:             my $lckey = lc($key);
                   9308:             $idmap{$lckey} = $idmap{$key};
                   9309:         }
                   9310:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   9311:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   9312:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   9313:             if ($line=~/^[\s\cz]*$/) { next; }
                   9314:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9315:                                                      $scan_data);
                   9316:             my $id=lc($$scan_record{'scantron.ID'});
                   9317:             if (exists($idmap{$id})) {
                   9318:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9319:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9320:                     if ($stusec eq '') {
                   9321:                         $bysec{'none'} ++;
                   9322:                     } else {
                   9323:                         $bysec{$stusec} ++;
                   9324:                     }
                   9325:                 }
                   9326:             }
                   9327:         }
                   9328:     }
                   9329:     return %bysec;
                   9330: }
1.423     albertel 9331: 
1.157     albertel 9332: sub scantron_get_correction {
1.691     raeburn  9333:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   9334:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 9335: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 9336: #to show both the current line and the previous one and allow skipping
                   9337: #the previous one or the current one
                   9338: 
1.333     albertel 9339:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   9340:         $r->print(
                   9341:             '<p class="LC_warning">'
                   9342:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   9343:                 "<b>$error</b>",
                   9344:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   9345:            ."</p> \n");
1.157     albertel 9346:     } else {
1.658     bisitz   9347:         $r->print(
                   9348:             '<p class="LC_warning">'
                   9349:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   9350:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   9351:            ."</p> \n");
                   9352:     }
                   9353:     my $message =
                   9354:         '<p>'
                   9355:        .&mt('The ID on the form is [_1]',
                   9356:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   9357:        .'<br />'
1.665     raeburn  9358:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   9359:             $$scan_record{'scantron.LastName'},
                   9360:             $$scan_record{'scantron.FirstName'})
                   9361:        .'</p>';
1.242     albertel 9362: 
1.157     albertel 9363:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   9364:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  9365:                            # Array populated for doublebubble or
                   9366:     my @lines_to_correct;  # missingbubble errors to build javascript
                   9367:                            # to validate radio button checking   
                   9368: 
1.157     albertel 9369:     if ($error =~ /ID$/) {
1.186     albertel 9370: 	if ($error eq 'incorrectID') {
1.658     bisitz   9371:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 9372: 		      "</p>\n");
1.157     albertel 9373: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   9374:             $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 9375: 	}
1.242     albertel 9376: 	$r->print($message);
1.492     albertel 9377: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 9378: 	$r->print("\n<ul><li> ");
                   9379: 	#FIXME it would be nice if this sent back the user ID and
                   9380: 	#could do partial userID matches
                   9381: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   9382: 				       'scantron_username','scantron_domain'));
                   9383: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   9384: 	$r->print("\n:\n".
1.257     albertel 9385: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 9386: 
                   9387: 	$r->print('</li>');
1.186     albertel 9388:     } elsif ($error =~ /CODE$/) {
                   9389: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   9390: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 9391: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   9392: 	    $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 9393: 	}
1.658     bisitz   9394: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   9395: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   9396:                  ."</p>\n");
1.242     albertel 9397: 	$r->print($message);
1.658     bisitz   9398: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 9399: 	$r->print("\n<br /> ");
1.194     albertel 9400: 	my $i=0;
1.273     albertel 9401: 	if ($error eq 'incorrectCODE' 
                   9402: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 9403: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 9404: 	    if ($closest > 0) {
                   9405: 		foreach my $testcode (@{$closest}) {
                   9406: 		    my $checked='';
1.569     bisitz   9407: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9408: 		    $r->print("
                   9409:    <label>
1.569     bisitz   9410:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 9411:        ".&mt("Use the similar CODE [_1] instead.",
                   9412: 	    "<b><tt>".$testcode."</tt></b>")."
                   9413:     </label>
                   9414:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 9415: 		    $r->print("\n<br />");
                   9416: 		    $i++;
                   9417: 		}
1.194     albertel 9418: 	    }
                   9419: 	}
1.273     albertel 9420: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   9421: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9422: 	    $r->print("
                   9423:     <label>
1.569     bisitz   9424:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  9425:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 9426: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   9427:     </label>");
1.273     albertel 9428: 	    $r->print("\n<br />");
                   9429: 	}
1.194     albertel 9430: 
1.597     wenzelju 9431: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 9432: function change_radio(field) {
1.190     albertel 9433:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 9434:     var i;
                   9435:     for (i=0;i<slct.length;i++) {
                   9436:         if (slct[i].value==field) { slct[i].checked=true; }
                   9437:     }
                   9438: }
                   9439: ENDSCRIPT
1.187     albertel 9440: 	my $href="/adm/pickcode?".
1.359     www      9441: 	   "form=".&escape("scantronupload").
                   9442: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   9443: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   9444: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   9445: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 9446: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 9447: 	    $r->print("
                   9448:     <label>
                   9449:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   9450:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   9451: 	     "<a target='_blank' href='$href'>","</a>")."
                   9452:     </label> 
1.558     bisitz   9453:     ".&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 9454: 	    $r->print("\n<br />");
                   9455: 	}
1.492     albertel 9456: 	$r->print("
                   9457:     <label>
                   9458:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   9459:        ".&mt("Use [_1] as the CODE.",
                   9460: 	     "</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 9461: 	$r->print("\n<br /><br />");
1.157     albertel 9462:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   9463: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     9464: 
                   9465: 	# The form field scantron_questions is acutally a list of line numbers.
                   9466: 	# represented by this form so:
                   9467: 
1.691     raeburn  9468: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9469:                                                 $respnumlookup,$startline);
1.497     foxr     9470: 
1.157     albertel 9471: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9472: 		  $line_list.'" />');
1.242     albertel 9473: 	$r->print($message);
1.492     albertel 9474: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 9475: 	foreach my $question (@{$arg}) {
1.503     raeburn  9476: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9477:                                                    $scan_record, $error,
                   9478:                                                    $randomorder,$randompick,
                   9479:                                                    $respnumlookup,$startline);
1.524     raeburn  9480:             push(@lines_to_correct,@linenums);
1.157     albertel 9481: 	}
1.503     raeburn  9482:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9483:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   9484: 	$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 9485: 	$r->print($message);
1.492     albertel 9486: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  9487: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     9488: 
1.503     raeburn  9489: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     9490: 	# a list of question numbers. Therefore:
                   9491: 	#
1.691     raeburn  9492: 
                   9493: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9494:                                                 $respnumlookup,$startline);
1.497     foxr     9495: 
1.157     albertel 9496: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9497: 		  $line_list.'" />');
1.157     albertel 9498: 	foreach my $question (@{$arg}) {
1.503     raeburn  9499: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9500:                                                    $scan_record, $error,
                   9501:                                                    $randomorder,$randompick,
                   9502:                                                    $respnumlookup,$startline);
1.524     raeburn  9503:             push(@lines_to_correct,@linenums);
1.157     albertel 9504: 	}
1.503     raeburn  9505:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9506:     } else {
                   9507: 	$r->print("\n<ul>");
                   9508:     }
                   9509:     $r->print("\n</li></ul>");
1.497     foxr     9510: }
                   9511: 
1.503     raeburn  9512: sub verify_bubbles_checked {
                   9513:     my (@ansnums) = @_;
                   9514:     my $ansnumstr = join('","',@ansnums);
                   9515:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  9516:     &js_escape(\$warning);
1.767     raeburn  9517:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  9518: function verify_bubble_radio(form) {
                   9519:     var ansnumArray = new Array ("$ansnumstr");
                   9520:     var need_bubble_count = 0;
                   9521:     for (var i=0; i<ansnumArray.length; i++) {
                   9522:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   9523:             var bubble_picked = 0; 
                   9524:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   9525:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   9526:                     bubble_picked = 1;
                   9527:                 }
                   9528:             }
                   9529:             if (bubble_picked == 0) {
                   9530:                 need_bubble_count ++;
                   9531:             }
                   9532:         }
                   9533:     }
                   9534:     if (need_bubble_count) {
                   9535:         alert("$warning");
                   9536:         return;
                   9537:     }
                   9538:     form.submit(); 
                   9539: }
                   9540: ENDSCRIPT
                   9541:     return $output;
                   9542: }
                   9543: 
1.497     foxr     9544: =pod
                   9545: 
                   9546: =item  questions_to_line_list
1.157     albertel 9547: 
1.497     foxr     9548: Converts a list of questions into a string of comma separated
                   9549: line numbers in the answer sheet used by the questions.  This is
                   9550: used to fill in the scantron_questions form field.
                   9551: 
                   9552:   Arguments:
                   9553:      questions    - Reference to an array of questions.
1.691     raeburn  9554:      randomorder  - True if randomorder in use.
                   9555:      randompick   - True if randompick in use.
                   9556:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9557:                      for current line to question number used for same question
                   9558:                      in "Master Seqence" (as seen by Course Coordinator).
                   9559:      startline    - Reference to hash where key is question number (0 is first)
                   9560:                     and key is number of first bubble line for current student
                   9561:                     or code-based randompick and/or randomorder.
1.693     raeburn  9562: 
1.497     foxr     9563: =cut
                   9564: 
                   9565: 
                   9566: sub questions_to_line_list {
1.691     raeburn  9567:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     9568:     my @lines;
                   9569: 
1.503     raeburn  9570:     foreach my $item (@{$questions}) {
                   9571:         my $question = $item;
                   9572:         my ($first,$count,$last);
                   9573:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   9574:             $question = $1;
                   9575:             my $subquestion = $2;
1.691     raeburn  9576:             my $responsenum = $question-1;
                   9577:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9578:                 $responsenum = $respnumlookup->{$question-1};
                   9579:                 if (ref($startline) eq 'HASH') {
                   9580:                     $first = $startline->{$question-1} + 1;
                   9581:                 }
                   9582:             } else {
                   9583:                 $first = $first_bubble_line{$responsenum} + 1;
                   9584:             }
                   9585:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9586:             my $subcount = 1;
                   9587:             while ($subcount<$subquestion) {
                   9588:                 $first += $subans[$subcount-1];
                   9589:                 $subcount ++;
                   9590:             }
                   9591:             $count = $subans[$subquestion-1];
                   9592:         } else {
1.691     raeburn  9593:             my $responsenum = $question-1;
                   9594:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9595:                 $responsenum = $respnumlookup->{$question-1};
                   9596:                 if (ref($startline) eq 'HASH') {
                   9597:                     $first = $startline->{$question-1} + 1;
                   9598:                 }
                   9599:             } else {
                   9600:                 $first = $first_bubble_line{$responsenum} + 1;
                   9601:             }
                   9602: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9603:         }
1.506     raeburn  9604:         $last = $first+$count-1;
1.503     raeburn  9605:         push(@lines, ($first..$last));
1.497     foxr     9606:     }
                   9607:     return join(',', @lines);
                   9608: }
                   9609: 
                   9610: =pod 
                   9611: 
                   9612: =item prompt_for_corrections
                   9613: 
                   9614: Prompts for a potentially multiline correction to the
                   9615: user's bubbling (factors out common code from scantron_get_correction
                   9616: for multi and missing bubble cases).
                   9617: 
                   9618:  Arguments:
                   9619:    $r           - Apache request object.
                   9620:    $question    - The question number to prompt for.
                   9621:    $scan_config - The scantron file configuration hash.
                   9622:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  9623:    $error       - Type of error
1.691     raeburn  9624:    $randomorder - True if randomorder in use.
                   9625:    $randompick  - True if randompick in use.
                   9626:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9627:                     for current line to question number used for same question
                   9628:                     in "Master Seqence" (as seen by Course Coordinator).
                   9629:    $startline   - Reference to hash where key is question number (0 is first)
                   9630:                   and value is number of first bubble line for current student
                   9631:                   or code-based randompick and/or randomorder.
                   9632: 
1.497     foxr     9633: 
                   9634:  Implicit inputs:
                   9635:    %bubble_lines_per_response   - Starting line numbers for each question.
                   9636:                                   Numbered from 0 (but question numbers are from
                   9637:                                   1.
                   9638:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  9639:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   9640:                                   type problems render as separate sub-questions, 
1.503     raeburn  9641:                                   in exam mode. This hash contains a 
                   9642:                                   comma-separated list of the lines per 
                   9643:                                   sub-question.
1.510     raeburn  9644:    %responsetype_per_response   - essayresponse, formularesponse,
                   9645:                                   stringresponse, imageresponse, reactionresponse,
                   9646:                                   and organicresponse type problem parts can have
1.503     raeburn  9647:                                   multiple lines per response if the weight
                   9648:                                   assigned exceeds 10.  In this case, only
                   9649:                                   one bubble per line is permitted, but more 
                   9650:                                   than one line might contain bubbles, e.g.
                   9651:                                   bubbling of: line 1 - J, line 2 - J, 
                   9652:                                   line 3 - B would assign 22 points.  
1.497     foxr     9653: 
                   9654: =cut
                   9655: 
                   9656: sub prompt_for_corrections {
1.691     raeburn  9657:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   9658:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  9659:     my ($current_line,$lines);
                   9660:     my @linenums;
                   9661:     my $questionnum = $question;
1.691     raeburn  9662:     my ($first,$responsenum);
1.503     raeburn  9663:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   9664:         $question = $1;
                   9665:         my $subquestion = $2;
1.691     raeburn  9666:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9667:             $responsenum = $respnumlookup->{$question-1};
                   9668:             if (ref($startline) eq 'HASH') {
                   9669:                 $first = $startline->{$question-1};
                   9670:             }
                   9671:         } else {
                   9672:             $responsenum = $question-1;
1.714     raeburn  9673:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  9674:         }
                   9675:         $current_line = $first + 1 ;
                   9676:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9677:         my $subcount = 1;
                   9678:         while ($subcount<$subquestion) {
                   9679:             $current_line += $subans[$subcount-1];
                   9680:             $subcount ++;
                   9681:         }
                   9682:         $lines = $subans[$subquestion-1];
                   9683:     } else {
1.691     raeburn  9684:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9685:             $responsenum = $respnumlookup->{$question-1};
                   9686:             if (ref($startline) eq 'HASH') { 
                   9687:                 $first = $startline->{$question-1};
                   9688:             }
                   9689:         } else {
                   9690:             $responsenum = $question-1;
                   9691:             $first = $first_bubble_line{$responsenum};
                   9692:         }
                   9693:         $current_line = $first + 1;
                   9694:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9695:     }
1.497     foxr     9696:     if ($lines > 1) {
1.503     raeburn  9697:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  9698:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   9699:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   9700:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   9701:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   9702:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   9703:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   9704:             $r->print(
                   9705:                 &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)
                   9706:                .'<br /><br />'
                   9707:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   9708:                .'<br />'
                   9709:                .&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.')
                   9710:                .'<br />'
                   9711:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   9712:                .'<br /><br />'
                   9713:             );
1.503     raeburn  9714:         } else {
                   9715:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   9716:         }
1.497     foxr     9717:     }
                   9718:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  9719:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  9720: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  9721: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  9722:         push(@linenums,$current_line);
1.497     foxr     9723: 	$current_line++;
                   9724:     }
                   9725:     if ($lines > 1) {
                   9726: 	$r->print("<hr /><br />");
                   9727:     }
1.503     raeburn  9728:     return @linenums;
1.157     albertel 9729: }
1.423     albertel 9730: 
                   9731: =pod
                   9732: 
                   9733: =item scantron_bubble_selector
                   9734:   
                   9735:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 9736:    possibly showing the existing the selected bubbles if known
1.423     albertel 9737: 
                   9738:  Arguments:
                   9739:     $r           - Apache request object
1.754     raeburn  9740:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     9741:     $line        - Number of the line being displayed.
1.503     raeburn  9742:     $questionnum - Question number (may include subquestion)
                   9743:     $error       - Type of error.
1.497     foxr     9744:     @selected    - Array of bubbles picked on this line.
1.423     albertel 9745: 
                   9746: =cut
                   9747: 
1.157     albertel 9748: sub scantron_bubble_selector {
1.503     raeburn  9749:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 9750:     my $max=$$scan_config{'Qlength'};
1.274     albertel 9751: 
                   9752:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  9753:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   9754:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   9755:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   9756:             $max=$$scan_config{'BubblesPerRow'};
                   9757:             if (($scmode eq 'number') && ($max > 10)) {
                   9758:                 $max = 10;
                   9759:             } elsif (($scmode eq 'letter') && $max > 26) {
                   9760:                 $max = 26;
                   9761:             }
                   9762:         } else {
                   9763:             $max = 10;
                   9764:         }
                   9765:     }
1.274     albertel 9766: 
1.157     albertel 9767:     my @alphabet=('A'..'Z');
1.503     raeburn  9768:     $r->print(&Apache::loncommon::start_data_table().
                   9769:               &Apache::loncommon::start_data_table_row());
                   9770:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     9771:     for (my $i=0;$i<$max+1;$i++) {
                   9772: 	$r->print("\n".'<td align="center">');
                   9773: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   9774: 	else { $r->print('&nbsp;'); }
                   9775: 	$r->print('</td>');
                   9776:     }
1.503     raeburn  9777:     $r->print(&Apache::loncommon::end_data_table_row().
                   9778:               &Apache::loncommon::start_data_table_row());
1.497     foxr     9779:     for (my $i=0;$i<$max;$i++) {
                   9780: 	$r->print("\n".
                   9781: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   9782: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   9783:     }
1.503     raeburn  9784:     my $nobub_checked = ' ';
                   9785:     if ($error eq 'missingbubble') {
                   9786:         $nobub_checked = ' checked = "checked" ';
                   9787:     }
                   9788:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   9789: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   9790:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   9791:               $line.'" value="'.$questionnum.'" /></td>');
                   9792:     $r->print(&Apache::loncommon::end_data_table_row().
                   9793:               &Apache::loncommon::end_data_table());
1.157     albertel 9794: }
                   9795: 
1.423     albertel 9796: =pod
                   9797: 
                   9798: =item num_matches
                   9799: 
1.424     albertel 9800:    Counts the number of characters that are the same between the two arguments.
                   9801: 
                   9802:  Arguments:
                   9803:    $orig - CODE from the scanline
                   9804:    $code - CODE to match against
                   9805: 
                   9806:  Returns:
                   9807:    $count - integer count of the number of same characters between the
                   9808:             two arguments
                   9809: 
1.423     albertel 9810: =cut
                   9811: 
1.194     albertel 9812: sub num_matches {
                   9813:     my ($orig,$code) = @_;
                   9814:     my @code=split(//,$code);
                   9815:     my @orig=split(//,$orig);
                   9816:     my $same=0;
                   9817:     for (my $i=0;$i<scalar(@code);$i++) {
                   9818: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   9819:     }
                   9820:     return $same;
                   9821: }
                   9822: 
1.423     albertel 9823: =pod
                   9824: 
                   9825: =item scantron_get_closely_matching_CODEs
                   9826: 
1.424     albertel 9827:    Cycles through all CODEs and finds the set that has the greatest
                   9828:    number of same characters as the provided CODE
                   9829: 
                   9830:  Arguments:
                   9831:    $allcodes - hash ref returned by &get_codes()
                   9832:    $CODE     - CODE from the current scanline
                   9833: 
                   9834:  Returns:
                   9835:    2 element list
                   9836:     - first elements is number of how closely matching the best fit is 
                   9837:       (5 means best set has 5 matching characters)
                   9838:     - second element is an arrary ref containing the set of valid CODEs
                   9839:       that best fit the passed in CODE
                   9840: 
1.423     albertel 9841: =cut
                   9842: 
1.194     albertel 9843: sub scantron_get_closely_matching_CODEs {
                   9844:     my ($allcodes,$CODE)=@_;
                   9845:     my @CODEs;
                   9846:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   9847: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   9848:     }
                   9849: 
                   9850:     return ($#CODEs,$CODEs[-1]);
                   9851: }
                   9852: 
1.423     albertel 9853: =pod
                   9854: 
                   9855: =item get_codes
                   9856: 
1.424     albertel 9857:    Builds a hash which has keys of all of the valid CODEs from the selected
                   9858:    set of remembered CODEs.
                   9859: 
                   9860:  Arguments:
                   9861:   $old_name - name of the set of remembered CODEs
                   9862:   $cdom     - domain of the course
                   9863:   $cnum     - internal course name
                   9864: 
                   9865:  Returns:
                   9866:   %allcodes - keys are the valid CODEs, values are all 1
                   9867: 
1.423     albertel 9868: =cut
                   9869: 
1.194     albertel 9870: sub get_codes {
1.280     foxr     9871:     my ($old_name, $cdom, $cnum) = @_;
                   9872:     if (!$old_name) {
                   9873: 	$old_name=$env{'form.scantron_CODElist'};
                   9874:     }
                   9875:     if (!$cdom) {
                   9876: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9877:     }
                   9878:     if (!$cnum) {
                   9879: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   9880:     }
1.278     albertel 9881:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   9882: 				    $cdom,$cnum);
                   9883:     my %allcodes;
                   9884:     if ($result{"type\0$old_name"} eq 'number') {
                   9885: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   9886:     } else {
                   9887: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   9888:     }
1.194     albertel 9889:     return %allcodes;
                   9890: }
                   9891: 
1.423     albertel 9892: =pod
                   9893: 
                   9894: =item scantron_validate_CODE
                   9895: 
1.424     albertel 9896:    Validates all scanlines in the selected file to not have any
                   9897:    invalid or underspecified CODEs and that none of the codes are
                   9898:    duplicated if this was requested.
                   9899: 
1.423     albertel 9900: =cut
                   9901: 
1.157     albertel 9902: sub scantron_validate_CODE {
                   9903:     my ($r,$currentphase) = @_;
1.754     raeburn  9904:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 9905:     if ($scantron_config{'CODElocation'} &&
                   9906: 	$scantron_config{'CODEstart'} &&
                   9907: 	$scantron_config{'CODElength'}) {
1.257     albertel 9908: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 9909: 	    &FIXME_blow_up()
                   9910: 	}
                   9911:     } else {
                   9912: 	return (0,$currentphase+1);
                   9913:     }
                   9914:     
                   9915:     my %usedCODEs;
                   9916: 
1.194     albertel 9917:     my %allcodes=&get_codes();
1.186     albertel 9918: 
1.582     raeburn  9919:     my $nav_error;
1.649     raeburn  9920:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  9921:     if ($nav_error) {
                   9922:         $r->print(&navmap_errormsg());
                   9923:         return(1,$currentphase);
                   9924:     }
1.447     foxr     9925: 
1.186     albertel 9926:     my ($scanlines,$scan_data)=&scantron_getfile();
                   9927:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9928: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 9929: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9930: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9931: 						 $scan_data);
                   9932: 	my $CODE=$$scan_record{'scantron.CODE'};
                   9933: 	my $error=0;
1.224     albertel 9934: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   9935: 	    &scantron_get_correction($r,$i,$scan_record,
                   9936: 				     \%scantron_config,
                   9937: 				     $line,'incorrectCODE',\%allcodes);
                   9938: 	    return(1,$currentphase);
                   9939: 	}
1.221     albertel 9940: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   9941: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 9942: 	    &scantron_get_correction($r,$i,$scan_record,
                   9943: 				     \%scantron_config,
1.194     albertel 9944: 				     $line,'incorrectCODE',\%allcodes);
                   9945: 	    return(1,$currentphase);
1.186     albertel 9946: 	}
1.214     albertel 9947: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 9948: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 9949: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 9950: 	    &scantron_get_correction($r,$i,$scan_record,
                   9951: 				     \%scantron_config,
1.194     albertel 9952: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   9953: 	    return(1,$currentphase);
1.186     albertel 9954: 	}
1.524     raeburn  9955: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 9956:     }
1.157     albertel 9957:     return (0,$currentphase+1);
                   9958: }
                   9959: 
1.423     albertel 9960: =pod
                   9961: 
                   9962: =item scantron_validate_doublebubble
                   9963: 
1.424     albertel 9964:    Validates all scanlines in the selected file to not have any
                   9965:    bubble lines with multiple bubbles marked.
                   9966: 
1.423     albertel 9967: =cut
                   9968: 
1.157     albertel 9969: sub scantron_validate_doublebubble {
                   9970:     my ($r,$currentphase) = @_;
                   9971:     #get student info
                   9972:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9973:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  9974:     my (undef,undef,$sequence)=
                   9975:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 9976: 
                   9977:     #get scantron line setup
1.754     raeburn  9978:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9979:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  9980: 
                   9981:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9982:     unless (ref($navmap)) {
                   9983:         $r->print(&navmap_errormsg());
                   9984:         return(1,$currentphase);
                   9985:     }
                   9986:     my $map=$navmap->getResourceByUrl($sequence);
                   9987:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9988:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9989:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   9990:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9991: 
1.583     raeburn  9992:     my $nav_error;
1.691     raeburn  9993:     if (ref($map)) {
                   9994:         $randomorder = $map->randomorder();
                   9995:         $randompick = $map->randompick();
1.788     raeburn  9996:         unless ($randomorder || $randompick) {
                   9997:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9998:                 if ($res->randomorder()) {
                   9999:                     $randomorder = 1;
                   10000:                 }
                   10001:                 if ($res->randompick()) {
                   10002:                     $randompick = 1;
                   10003:                 }
                   10004:                 last if ($randomorder || $randompick);
                   10005:             }
                   10006:         }
1.691     raeburn  10007:         if ($randomorder || $randompick) {
                   10008:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10009:             if ($nav_error) {
                   10010:                 $r->print(&navmap_errormsg());
                   10011:                 return(1,$currentphase);
                   10012:             }
                   10013:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10014:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   10015:         }
                   10016:     } else {
                   10017:         $r->print(&navmap_errormsg());
                   10018:         return(1,$currentphase);
                   10019:     }
                   10020: 
1.649     raeburn  10021:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  10022:     if ($nav_error) {
                   10023:         $r->print(&navmap_errormsg());
                   10024:         return(1,$currentphase);
                   10025:     }
1.447     foxr     10026: 
1.157     albertel 10027:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 10028: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10029: 	if ($line=~/^[\s\cz]*$/) { next; }
                   10030: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  10031: 						 $scan_data,undef,\%idmap,$randomorder,
                   10032:                                                  $randompick,$sequence,\@master_seq,
                   10033:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   10034:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 10035: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   10036: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   10037: 				 'doublebubble',
1.691     raeburn  10038: 				 $$scan_record{'scantron.doubleerror'},
                   10039:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 10040:     	return (1,$currentphase);
                   10041:     }
                   10042:     return (0,$currentphase+1);
                   10043: }
                   10044: 
1.423     albertel 10045: 
1.503     raeburn  10046: sub scantron_get_maxbubble {
1.649     raeburn  10047:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 10048:     if (defined($env{'form.scantron_maxbubble'}) &&
                   10049: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     10050: 	&restore_bubble_lines();
1.257     albertel 10051: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 10052:     }
1.330     albertel 10053: 
1.447     foxr     10054:     my (undef, undef, $sequence) =
1.257     albertel 10055: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 10056: 
1.447     foxr     10057:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10058:     unless (ref($navmap)) {
                   10059:         if (ref($nav_error)) {
                   10060:             $$nav_error = 1;
                   10061:         }
1.591     raeburn  10062:         return;
1.582     raeburn  10063:     }
1.191     albertel 10064:     my $map=$navmap->getResourceByUrl($sequence);
                   10065:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  10066:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 10067: 
                   10068:     &Apache::lonxml::clear_problem_counter();
                   10069: 
1.557     raeburn  10070:     my $uname       = $env{'user.name'};
                   10071:     my $udom        = $env{'user.domain'};
1.435     foxr     10072:     my $cid         = $env{'request.course.id'};
                   10073:     my $total_lines = 0;
                   10074:     %bubble_lines_per_response = ();
1.447     foxr     10075:     %first_bubble_line         = ();
1.503     raeburn  10076:     %subdivided_bubble_lines   = ();
                   10077:     %responsetype_per_response = ();
1.691     raeburn  10078:     %masterseq_id_responsenum  = ();
1.554     raeburn  10079: 
1.447     foxr     10080:     my $response_number = 0;
                   10081:     my $bubble_line     = 0;
1.191     albertel 10082:     foreach my $resource (@resources) {
1.691     raeburn  10083:         my $resid = $resource->id(); 
1.672     raeburn  10084:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   10085:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  10086:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   10087: 	    foreach my $part_id (@{$parts}) {
                   10088:                 my $lines;
                   10089: 
                   10090: 	        # TODO - make this a persistent hash not an array.
                   10091: 
                   10092:                 # optionresponse, matchresponse and rankresponse type items 
                   10093:                 # render as separate sub-questions in exam mode.
                   10094:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   10095:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   10096:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   10097:                     my ($numbub,$numshown);
                   10098:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   10099:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   10100:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   10101:                         }
                   10102:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   10103:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   10104:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   10105:                         }
                   10106:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   10107:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   10108:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   10109:                         }
                   10110:                     }
                   10111:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   10112:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   10113:                     }
1.649     raeburn  10114:                     my $bubbles_per_row =
                   10115:                         &bubblesheet_bubbles_per_row($scantron_config);
                   10116:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   10117:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  10118:                         $inner_bubble_lines++;
                   10119:                     }
                   10120:                     for (my $i=0; $i<$numshown; $i++) {
                   10121:                         $subdivided_bubble_lines{$response_number} .= 
                   10122:                             $inner_bubble_lines.',';
                   10123:                     }
                   10124:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   10125:                     $lines = $numshown * $inner_bubble_lines;
                   10126:                 } else {
                   10127:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  10128:                 }
1.542     raeburn  10129: 
                   10130:                 $first_bubble_line{$response_number} = $bubble_line;
                   10131: 	        $bubble_lines_per_response{$response_number} = $lines;
                   10132:                 $responsetype_per_response{$response_number} = 
                   10133:                     $analysis->{$part_id.'.type'};
1.691     raeburn  10134:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  10135: 	        $response_number++;
                   10136: 
                   10137: 	        $bubble_line +=  $lines;
                   10138: 	        $total_lines +=  $lines;
                   10139: 	    }
                   10140:         }
                   10141:     }
1.552     raeburn  10142:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  10143: 
                   10144:     &save_bubble_lines();
                   10145:     $env{'form.scantron_maxbubble'} =
                   10146: 	$total_lines;
                   10147:     return $env{'form.scantron_maxbubble'};
                   10148: }
1.523     raeburn  10149: 
1.649     raeburn  10150: sub bubblesheet_bubbles_per_row {
                   10151:     my ($scantron_config) = @_;
                   10152:     my $bubbles_per_row;
                   10153:     if (ref($scantron_config) eq 'HASH') {
                   10154:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   10155:     }
                   10156:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   10157:         $bubbles_per_row = 10;
                   10158:     }
                   10159:     return $bubbles_per_row;
                   10160: }
                   10161: 
1.157     albertel 10162: sub scantron_validate_missingbubbles {
                   10163:     my ($r,$currentphase) = @_;
                   10164:     #get student info
                   10165:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10166:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  10167:     my (undef,undef,$sequence)=
                   10168:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 10169: 
                   10170:     #get scantron line setup
1.754     raeburn  10171:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 10172:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  10173: 
                   10174:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10175:     unless (ref($navmap)) {
                   10176:         $r->print(&navmap_errormsg());
                   10177:         return(1,$currentphase);
                   10178:     }
                   10179: 
                   10180:     my $map=$navmap->getResourceByUrl($sequence);
                   10181:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10182:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10183:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   10184:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10185: 
1.582     raeburn  10186:     my $nav_error;
1.691     raeburn  10187:     if (ref($map)) {
                   10188:         $randomorder = $map->randomorder();
                   10189:         $randompick = $map->randompick();
1.788     raeburn  10190:         unless ($randomorder || $randompick) {
                   10191:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10192:                 if ($res->randomorder()) {
                   10193:                     $randomorder = 1;
                   10194:                 }
                   10195:                 if ($res->randompick()) {
                   10196:                     $randompick = 1;
                   10197:                 }
                   10198:                 last if ($randomorder || $randompick);
                   10199:             }
                   10200:         }
1.691     raeburn  10201:         if ($randomorder || $randompick) {
                   10202:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10203:             if ($nav_error) {
                   10204:                 $r->print(&navmap_errormsg());
                   10205:                 return(1,$currentphase);
                   10206:             }
                   10207:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10208:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   10209:         }
                   10210:     } else {
                   10211:         $r->print(&navmap_errormsg());
                   10212:         return(1,$currentphase);
                   10213:     }
                   10214: 
                   10215: 
1.649     raeburn  10216:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  10217:     if ($nav_error) {
1.691     raeburn  10218:         $r->print(&navmap_errormsg());
1.693     raeburn  10219:         return(1,$currentphase);
1.582     raeburn  10220:     }
1.691     raeburn  10221: 
1.157     albertel 10222:     if (!$max_bubble) { $max_bubble=2**31; }
                   10223:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 10224: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10225: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  10226: 	my $scan_record =
                   10227:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   10228: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   10229:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   10230:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 10231: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   10232: 	my @to_correct;
1.470     foxr     10233: 	
                   10234: 	# Probably here's where the error is...
                   10235: 
1.157     albertel 10236: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  10237:             my $lastbubble;
                   10238:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   10239:                my $question = $1;
                   10240:                my $subquestion = $2;
1.691     raeburn  10241:                my ($first,$responsenum);
                   10242:                if ($randomorder || $randompick) {
                   10243:                    $responsenum = $respnumlookup{$question-1};
                   10244:                    $first = $startline{$question-1};
                   10245:                } else {
                   10246:                    $responsenum = $question-1; 
                   10247:                    $first = $first_bubble_line{$responsenum};
                   10248:                }
                   10249:                if (!defined($first)) { next; }
                   10250:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  10251:                my $subcount = 1;
                   10252:                while ($subcount<$subquestion) {
                   10253:                    $first += $subans[$subcount-1];
                   10254:                    $subcount ++;
                   10255:                }
                   10256:                my $count = $subans[$subquestion-1];
                   10257:                $lastbubble = $first + $count;
                   10258:             } else {
1.691     raeburn  10259:                my ($first,$responsenum);
                   10260:                if ($randomorder || $randompick) {
                   10261:                    $responsenum = $respnumlookup{$missing-1};
                   10262:                    $first = $startline{$missing-1};
                   10263:                } else {
                   10264:                    $responsenum = $missing-1;
                   10265:                    $first = $first_bubble_line{$responsenum};
                   10266:                }
                   10267:                if (!defined($first)) { next; }
                   10268:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  10269:             }
                   10270:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 10271: 	    push(@to_correct,$missing);
                   10272: 	}
                   10273: 	if (@to_correct) {
                   10274: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  10275: 				     $line,'missingbubble',\@to_correct,
                   10276:                                      $randomorder,$randompick,\%respnumlookup,
                   10277:                                      \%startline);
1.157     albertel 10278: 	    return (1,$currentphase);
                   10279: 	}
                   10280: 
                   10281:     }
                   10282:     return (0,$currentphase+1);
                   10283: }
                   10284: 
1.663     raeburn  10285: sub hand_bubble_option {
                   10286:     my (undef, undef, $sequence) =
                   10287:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10288:     return if ($sequence eq '');
                   10289:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10290:     unless (ref($navmap)) {
                   10291:         return;
                   10292:     }
                   10293:     my $needs_hand_bubbles;
                   10294:     my $map=$navmap->getResourceByUrl($sequence);
                   10295:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10296:     foreach my $res (@resources) {
                   10297:         if (ref($res)) {
                   10298:             if ($res->is_problem()) {
                   10299:                 my $partlist = $res->parts();
                   10300:                 foreach my $part (@{ $partlist }) {
                   10301:                     my @types = $res->responseType($part);
                   10302:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   10303:                         $needs_hand_bubbles = 1;
                   10304:                         last;
                   10305:                     }
                   10306:                 }
                   10307:             }
                   10308:         }
                   10309:     }
                   10310:     if ($needs_hand_bubbles) {
1.754     raeburn  10311:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  10312:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10313:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   10314:                &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 />').
                   10315:                '<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  10316:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  10317:     }
                   10318:     return;
                   10319: }
1.423     albertel 10320: 
1.82      albertel 10321: sub scantron_process_students {
1.608     www      10322:     my ($r,$symb) = @_;
1.513     foxr     10323: 
1.257     albertel 10324:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     10325:     if (!$symb) {
                   10326: 	return '';
                   10327:     }
1.324     albertel 10328:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 10329: 
1.754     raeburn  10330:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  10331:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 10332:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 10333:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10334:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 10335:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10336:     unless (ref($navmap)) {
                   10337:         $r->print(&navmap_errormsg());
                   10338:         return '';
1.691     raeburn  10339:     }
1.83      albertel 10340:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10341:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.788     raeburn  10342:         %grader_randomlists_by_symb,%symb_for_examcode);
1.677     raeburn  10343:     if (ref($map)) {
                   10344:         $randomorder = $map->randomorder();
1.689     raeburn  10345:         $randompick = $map->randompick();
1.788     raeburn  10346:         unless ($randomorder || $randompick) {
                   10347:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10348:                 if ($res->randomorder()) {
                   10349:                     $randomorder = 1;
                   10350:                 }
                   10351:                 if ($res->randompick()) {
                   10352:                     $randompick = 1;
                   10353:                 }
                   10354:                 last if ($randomorder || $randompick);
                   10355:             }
                   10356:         }
1.691     raeburn  10357:     } else {
                   10358:         $r->print(&navmap_errormsg());
                   10359:         return '';
1.677     raeburn  10360:     }
1.691     raeburn  10361:     my $nav_error;
1.83      albertel 10362:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10363:     if ($randomorder || $randompick) {
1.788     raeburn  10364:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
1.691     raeburn  10365:         if ($nav_error) {
                   10366:             $r->print(&navmap_errormsg());
                   10367:             return '';
                   10368:         }
                   10369:     }
1.557     raeburn  10370:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  10371:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  10372: 
1.554     raeburn  10373:     my ($uname,$udom);
1.82      albertel 10374:     my $result= <<SCANTRONFORM;
1.81      albertel 10375: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   10376:   <input type="hidden" name="command" value="scantron_configphase" />
                   10377:   $default_form_data
                   10378: SCANTRONFORM
1.82      albertel 10379:     $r->print($result);
                   10380: 
1.770     raeburn  10381:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 10382:     my @delayqueue;
1.542     raeburn  10383:     my (%completedstudents,%scandata);
1.770     raeburn  10384: 
1.520     www      10385:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 10386:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10387:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   10388:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  10389:     $r->print('<br />');
1.140     albertel 10390:     my $start=&Time::HiRes::time();
1.158     albertel 10391:     my $i=-1;
1.542     raeburn  10392:     my $started;
1.447     foxr     10393: 
1.649     raeburn  10394:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10395:     if ($nav_error) {
                   10396:         $r->print(&navmap_errormsg());
                   10397:         return '';
                   10398:     }
                   10399: 
1.513     foxr     10400:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   10401:     # the user and return.
                   10402: 
                   10403:     if ($ssi_error) {
                   10404: 	$r->print("</form>");
                   10405: 	&ssi_print_error($r);
1.520     www      10406:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     10407: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   10408:     }
1.447     foxr     10409: 
1.755     raeburn  10410:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  10411:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  10412:     my %orderedforcode;
1.542     raeburn  10413: 
1.157     albertel 10414:     while ($i<$scanlines->{'count'}) {
                   10415:  	($uname,$udom)=('','');
                   10416:  	$i++;
1.200     albertel 10417:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10418:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 10419: 	if ($started) {
1.667     www      10420: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 10421: 	}
                   10422: 	$started=1;
1.691     raeburn  10423:         my %respnumlookup = ();
                   10424:         my %startline = ();
                   10425:         my $total;
1.157     albertel 10426:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  10427:                                                  $scan_data,undef,\%idmap,$randomorder,
                   10428:                                                  $randompick,$sequence,\@master_seq,
                   10429:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   10430:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   10431:                                                  \$total);
1.157     albertel 10432:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10433:  					      \%idmap,$i)) {
                   10434:   	    &scantron_add_delay(\@delayqueue,$line,
                   10435:  				'Unable to find a student that matches',1);
                   10436:  	    next;
                   10437:   	}
                   10438:  	if (exists $completedstudents{$uname}) {
                   10439:  	    &scantron_add_delay(\@delayqueue,$line,
                   10440:  				'Student '.$uname.' has multiple sheets',2);
                   10441:  	    next;
                   10442:  	}
1.677     raeburn  10443:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  10444:         if (($checksec ne '') && ($checksec ne $usec)) {
                   10445:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   10446:                 &scantron_add_delay(\@delayqueue,$line,
                   10447:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   10448:                 next;
                   10449:             }
                   10450:         }
1.677     raeburn  10451:         my $user = $uname.':'.$usec;
1.157     albertel 10452:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 10453: 
1.677     raeburn  10454:         my $scancode;
                   10455:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10456:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10457:             $scancode = $scan_record->{'scantron.CODE'};
                   10458:         } else {
                   10459:             $scancode = '';
                   10460:         }
                   10461: 
                   10462:         my @mapresources = @resources;
1.689     raeburn  10463:         if ($randomorder || $randompick) {
1.678     raeburn  10464:             @mapresources = 
1.691     raeburn  10465:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10466:                              \%orderedforcode);
1.677     raeburn  10467:         }
1.586     raeburn  10468:         my (%partids_by_symb,$res_error);
1.677     raeburn  10469:         foreach my $resource (@mapresources) {
1.586     raeburn  10470:             my $ressymb;
                   10471:             if (ref($resource)) {
                   10472:                 $ressymb = $resource->symb();
                   10473:             } else {
                   10474:                 $res_error = 1;
                   10475:                 last;
                   10476:             }
1.557     raeburn  10477:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10478:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10479:                 my $currcode;
                   10480:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10481:                     $currcode = $scancode;
                   10482:                 }
1.557     raeburn  10483:                 my ($analysis,$parts) =
1.672     raeburn  10484:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  10485:                                               $uname,$udom,undef,$bubbles_per_row,
                   10486:                                               $currcode);
1.557     raeburn  10487:                 $partids_by_symb{$ressymb} = $parts;
                   10488:             } else {
                   10489:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   10490:             }
1.554     raeburn  10491:         }
                   10492: 
1.586     raeburn  10493:         if ($res_error) {
                   10494:             &scantron_add_delay(\@delayqueue,$line,
                   10495:                                 'An error occurred while grading student '.$uname,2);
                   10496:             next;
                   10497:         }
                   10498: 
1.330     albertel 10499: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  10500:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 10501: 
                   10502: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   10503: 	    &scantron_putfile($scanlines,$scan_data);
                   10504: 	}
1.161     albertel 10505: 	
1.542     raeburn  10506:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10507:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  10508:                                    $bubbles_per_row,$randomorder,$randompick,
                   10509:                                    \%respnumlookup,\%startline) 
                   10510:             eq 'ssi_error') {
1.542     raeburn  10511:             $ssi_error = 0; # So end of handler error message does not trigger.
                   10512:             $r->print("</form>");
                   10513:             &ssi_print_error($r);
                   10514:             &Apache::lonnet::remove_lock($lock);
                   10515:             return '';      # Why return ''?  Beats me.
                   10516:         }
1.513     foxr     10517: 
1.692     raeburn  10518:         if (($scancode) && ($randomorder || $randompick)) {
1.788     raeburn  10519:             foreach my $key (keys(%symb_for_examcode)) {
                   10520:                 my $symb_in_map = $symb_for_examcode{$key};
                   10521:                 if ($symb_in_map ne '') {
                   10522:                     my $parmresult =
                   10523:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   10524:                                                                '0_examcode',2,$scancode,
                   10525:                                                                'string_examcode',$uname,
                   10526:                                                                $udom);
                   10527:                 }
                   10528:             }
1.692     raeburn  10529:         }
1.140     albertel 10530: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  10531:         if ($env{'form.verifyrecord'}) {
                   10532:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  10533:             if ($randompick) {
                   10534:                 if ($total) {
                   10535:                     $lastpos = $total*$scantron_config{'Qlength'};
                   10536:                 }
                   10537:             }
                   10538: 
1.542     raeburn  10539:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10540:             chomp($studentdata);
                   10541:             $studentdata =~ s/\r$//;
                   10542:             my $studentrecord = '';
                   10543:             my $counter = -1;
1.677     raeburn  10544:             foreach my $resource (@mapresources) {
1.554     raeburn  10545:                 my $ressymb = $resource->symb();
1.542     raeburn  10546:                 ($counter,my $recording) =
                   10547:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10548:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10549:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   10550:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  10551:                 $studentrecord .= $recording;
                   10552:             }
                   10553:             if ($studentrecord ne $studentdata) {
1.554     raeburn  10554:                 &Apache::lonxml::clear_problem_counter();
                   10555:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10556:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  10557:                                            $bubbles_per_row,$randomorder,$randompick,
                   10558:                                            \%respnumlookup,\%startline) 
                   10559:                     eq 'ssi_error') {
1.554     raeburn  10560:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   10561:                     $r->print("</form>");
                   10562:                     &ssi_print_error($r);
                   10563:                     &Apache::lonnet::remove_lock($lock);
                   10564:                     delete($completedstudents{$uname});
                   10565:                     return '';
                   10566:                 }
1.542     raeburn  10567:                 $counter = -1;
                   10568:                 $studentrecord = '';
1.677     raeburn  10569:                 foreach my $resource (@mapresources) {
1.554     raeburn  10570:                     my $ressymb = $resource->symb();
1.542     raeburn  10571:                     ($counter,my $recording) =
                   10572:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10573:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10574:                                                  \%scantron_config,\%lettdig,$numletts,
                   10575:                                                  $randomorder,$randompick,\%respnumlookup,
                   10576:                                                  \%startline);
1.542     raeburn  10577:                     $studentrecord .= $recording;
                   10578:                 }
                   10579:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   10580:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  10581:                     if ($scancode eq '') {
1.658     bisitz   10582:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  10583:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   10584:                     } else {
1.658     bisitz   10585:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  10586:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   10587:                     }
                   10588:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   10589:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   10590:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   10591:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   10592:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10593:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   10594:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  10595:                               &Apache::loncommon::end_data_table_row().
                   10596:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10597:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   10598:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  10599:                               &Apache::loncommon::end_data_table_row().
                   10600:                               &Apache::loncommon::end_data_table().'</p>');
                   10601:                 } else {
                   10602:                     $r->print('<br /><span class="LC_warning">'.
                   10603:                              &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 />'.
                   10604:                              &mt("As a consequence, this user's submission history records two tries.").
                   10605:                                  '</span><br />');
                   10606:                 }
                   10607:             }
                   10608:         }
1.543     raeburn  10609:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 10610:     } continue {
1.330     albertel 10611: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  10612: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 10613:     }
1.140     albertel 10614:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      10615:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 10616: #    my $lasttime = &Time::HiRes::time()-$start;
                   10617: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 10618: 
1.200     albertel 10619:     $r->print("</form>");
1.157     albertel 10620:     return '';
1.75      albertel 10621: }
1.157     albertel 10622: 
1.557     raeburn  10623: sub graders_resources_pass {
1.649     raeburn  10624:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   10625:         $bubbles_per_row) = @_;
1.557     raeburn  10626:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   10627:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   10628:         foreach my $resource (@{$resources}) {
                   10629:             my $ressymb = $resource->symb();
                   10630:             my ($analysis,$parts) =
                   10631:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  10632:                                           $env{'user.name'},$env{'user.domain'},
                   10633:                                           1,$bubbles_per_row);
1.557     raeburn  10634:             $grader_partids_by_symb->{$ressymb} = $parts;
                   10635:             if (ref($analysis) eq 'HASH') {
                   10636:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   10637:                     $grader_randomlists_by_symb->{$ressymb} =
                   10638:                         $analysis->{'parts_withrandomlist'};
                   10639:                 }
                   10640:             }
                   10641:         }
                   10642:     }
                   10643:     return;
                   10644: }
                   10645: 
1.678     raeburn  10646: =pod
                   10647: 
                   10648: =item users_order
                   10649: 
                   10650:   Returns array of resources in current map, ordered based on either CODE,
                   10651:   if this is a CODEd exam, or based on student's identity if this is a 
                   10652:   "NAMEd" exam.
                   10653: 
1.691     raeburn  10654:   Should be used when randomorder and/or randompick applied when the 
                   10655:   corresponding exam was printed, prior to students completing bubblesheets 
                   10656:   for the version of the exam the student received.
1.678     raeburn  10657: 
                   10658: =cut
                   10659: 
                   10660: sub users_order  {
1.691     raeburn  10661:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  10662:     my @mapresources;
1.691     raeburn  10663:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  10664:         return @mapresources;
1.691     raeburn  10665:     }
                   10666:     if ($scancode) {
                   10667:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   10668:             @mapresources = @{$orderedforcode->{$scancode}};
                   10669:         } else {
                   10670:             $env{'form.CODE'} = $scancode;
                   10671:             my $actual_seq =
                   10672:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10673:                                                                $master_seq,
                   10674:                                                                $user,$scancode,1);
                   10675:             if (ref($actual_seq) eq 'ARRAY') {
                   10676:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10677:                 if (ref($orderedforcode) eq 'HASH') {
                   10678:                     if (@mapresources > 0) { 
                   10679:                         $orderedforcode->{$scancode} = \@mapresources;
                   10680:                     }
                   10681:                 }
                   10682:             }
                   10683:             delete($env{'form.CODE'});
1.678     raeburn  10684:         }
                   10685:     } else {
                   10686:         my $actual_seq =
                   10687:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10688:                                                            $master_seq,
1.688     raeburn  10689:                                                            $user,undef,1);
1.678     raeburn  10690:         if (ref($actual_seq) eq 'ARRAY') {
                   10691:             @mapresources = 
                   10692:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10693:         }
1.691     raeburn  10694:     }
                   10695:     return @mapresources;
1.678     raeburn  10696: }
                   10697: 
1.542     raeburn  10698: sub grade_student_bubbles {
1.691     raeburn  10699:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   10700:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   10701:     my $uselookup = 0;
                   10702:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   10703:         (ref($startline) eq 'HASH')) {
                   10704:         $uselookup = 1;
                   10705:     }
                   10706: 
1.554     raeburn  10707:     if (ref($resources) eq 'ARRAY') {
                   10708:         my $count = 0;
                   10709:         foreach my $resource (@{$resources}) {
                   10710:             my $ressymb = $resource->symb();
                   10711:             my %form = ('submitted'      => 'scantron',
                   10712:                         'grade_target'   => 'grade',
                   10713:                         'grade_username' => $uname,
                   10714:                         'grade_domain'   => $udom,
                   10715:                         'grade_courseid' => $env{'request.course.id'},
                   10716:                         'grade_symb'     => $ressymb,
                   10717:                         'CODE'           => $scancode
                   10718:                        );
1.649     raeburn  10719:             if ($bubbles_per_row ne '') {
                   10720:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   10721:             }
1.663     raeburn  10722:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   10723:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   10724:             }
1.554     raeburn  10725:             if (ref($parts) eq 'HASH') {
                   10726:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   10727:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  10728:                         if ($uselookup) {
                   10729:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   10730:                         } else {
                   10731:                             $form{'scantron_questnum_start.'.$part} =
                   10732:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   10733:                         }
1.554     raeburn  10734:                         $count++;
                   10735:                     }
                   10736:                 }
                   10737:             }
                   10738:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   10739:             return 'ssi_error' if ($ssi_error);
                   10740:             last if (&Apache::loncommon::connection_aborted($r));
                   10741:         }
1.542     raeburn  10742:     }
                   10743:     return;
                   10744: }
                   10745: 
1.157     albertel 10746: sub scantron_upload_scantron_data {
1.767     raeburn  10747:     my ($r,$symb) = @_;
1.565     raeburn  10748:     my $dom = $env{'request.role.domain'};
1.754     raeburn  10749:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  10750:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   10751:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 10752:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 10753: 							  'domainid',
1.565     raeburn  10754: 							  'coursename',$dom);
                   10755:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   10756:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      10757:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  10758:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  10759:     &js_escape(\$nofile_alert);
1.579     raeburn  10760:     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  10761:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 10762:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 10763:     function checkUpload(formname) {
                   10764: 	if (formname.upfile.value == "") {
1.579     raeburn  10765: 	    alert("'.$nofile_alert.'");
1.157     albertel 10766: 	    return false;
                   10767: 	}
1.565     raeburn  10768:         if (formname.courseid.value == "") {
1.579     raeburn  10769:             alert("'.$nocourseid_alert.'");
1.565     raeburn  10770:             return false;
                   10771:         }
1.157     albertel 10772: 	formname.submit();
                   10773:     }
1.565     raeburn  10774: 
                   10775:     function ToSyllabus() {
                   10776:         var cdom = '."'$dom'".';
                   10777:         var cnum = document.rules.courseid.value;
                   10778:         if (cdom == "" || cdom == null) {
                   10779:             return;
                   10780:         }
                   10781:         if (cnum == "" || cnum == null) {
                   10782:            return;
                   10783:         }
                   10784:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   10785:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   10786:         return;
                   10787:     }
                   10788: 
1.754     raeburn  10789:     '.$formatjs.'
1.597     wenzelju 10790: '));
                   10791:     $r->print('
1.648     bisitz   10792: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  10793: 
1.492     albertel 10794: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  10795: '.$default_form_data.
                   10796:   &Apache::lonhtmlcommon::start_pick_box().
                   10797:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   10798:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   10799:   &Apache::lonhtmlcommon::row_closure().
                   10800:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   10801:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   10802:   &Apache::lonhtmlcommon::row_closure().
                   10803:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   10804:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  10805:   &Apache::lonhtmlcommon::row_closure());
                   10806:     if ($formatoptions) {
                   10807:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   10808:                   &Apache::lonhtmlcommon::row_closure());
                   10809:     }
                   10810:     $r->print(
1.565     raeburn  10811:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   10812:   '<input type="file" name="upfile" size="50" />'.
                   10813:   &Apache::lonhtmlcommon::row_closure(1).
                   10814:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   10815: 
1.492     albertel 10816: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   10817: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 10818: </form>
1.492     albertel 10819: ');
1.157     albertel 10820:     return '';
                   10821: }
                   10822: 
1.754     raeburn  10823: sub scantron_upload_dataformat {
                   10824:     my ($dom) = @_;
                   10825:     my ($formatoptions,$formattitle,$formatjs);
                   10826:     $formatjs = <<'END';
                   10827: function toggleScantab(form) {
                   10828:    return;
                   10829: }
                   10830: END
                   10831:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   10832:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10833:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10834:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   10835:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   10836:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  10837:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   10838:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   10839:                             my ($onclick,$formatextra,$singleline);
                   10840:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   10841:                             my $count = 0;
                   10842:                             foreach my $line (@lines) {
1.790     raeburn  10843:                                 next if (($line =~ /^\#/) || ($line eq ''));
1.756     raeburn  10844:                                 $singleline = $line;
                   10845:                                 $count ++;
                   10846:                             }
                   10847:                             if ($count > 1) {
                   10848:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  10849:                                                '<span class="LC_nobreak">'.
1.776     raeburn  10850:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  10851:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  10852:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   10853:                                 $formatjs = <<"END";
1.754     raeburn  10854: function toggleScantab(form) {
                   10855:     var divid = 'bubbletype';
                   10856:     if (document.getElementById(divid)) {
                   10857:         var radioname = 'fileformat';
                   10858:         var num = form.elements[radioname].length;
                   10859:         if (num) {
                   10860:             for (var i=0; i<num; i++) {
                   10861:                 if (form.elements[radioname][i].checked) {
                   10862:                     var chosen = form.elements[radioname][i].value;
                   10863:                     if (chosen == 'dat') {
                   10864:                         document.getElementById(divid).style.display = 'none';
                   10865:                     } else if (chosen == 'csv') {
1.757     raeburn  10866:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  10867:                     }
                   10868:                 }
                   10869:             }
                   10870:         }
                   10871:     }
                   10872:     return;
                   10873: }
                   10874: 
                   10875: END
1.756     raeburn  10876:                             } elsif ($count == 1) {
                   10877:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   10878:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   10879:                             }
                   10880:                             $formattitle = &mt('File format');
                   10881:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   10882:                                              &mt('Plain Text (no delimiters)').
                   10883:                                              '</label>'.('&nbsp;'x2).
                   10884:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   10885:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  10886:                         }
                   10887:                     }
                   10888:                 }
                   10889:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  10890:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10891:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  10892:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  10893:                         $formatoptions = &scantron_scantab();
                   10894:                     }
1.754     raeburn  10895:                 }
                   10896:             }
                   10897:         }
                   10898:     }
                   10899:     return ($formatoptions,$formattitle,$formatjs);
                   10900: }
1.423     albertel 10901: 
1.157     albertel 10902: sub scantron_upload_scantron_data_save {
1.767     raeburn  10903:     my ($r,$symb) = @_;
1.182     albertel 10904:     my $doanotherupload=
                   10905: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   10906: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 10907: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 10908: 	'</form>'."\n";
1.257     albertel 10909:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 10910: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  10911: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   10912:         !&Apache::lonnet::allowed('usc',
                   10913:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      10914: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      10915: 	unless ($symb) {
1.182     albertel 10916: 	    $r->print($doanotherupload);
                   10917: 	}
1.162     albertel 10918: 	return '';
                   10919:     }
1.257     albertel 10920:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  10921:     my $uploadedfile;
1.710     bisitz   10922:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 10923:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10924:         $r->print(
                   10925:             &Apache::lonhtmlcommon::confirm_success(
                   10926:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10927:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 10928:     } else {
1.754     raeburn  10929:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   10930:         my $parser;
                   10931:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10932:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10933:                 my $is_csv;
                   10934:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   10935:                 if (@possibles > 1) {
                   10936:                     if ($env{'form.fileformat'} eq 'csv') {
                   10937:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10938:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10939:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10940:                                     $is_csv = 1;
                   10941:                                 }
1.754     raeburn  10942:                             }
                   10943:                         }
                   10944:                     }
                   10945:                 } elsif (@possibles == 1) {
                   10946:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10947:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10948:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10949:                                 $is_csv = 1;
                   10950:                             }
1.754     raeburn  10951:                         }
                   10952:                     }
                   10953:                 }
                   10954:                 if ($is_csv) {
                   10955:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   10956:                 }
                   10957:             }
                   10958:         }
                   10959:         my $result =
                   10960:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  10961:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   10962:         if ($result =~ m{^/uploaded/}) {
                   10963:             $r->print(
                   10964:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   10965:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   10966:                         (length($env{'form.upfile'})-1),
                   10967:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  10968:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  10969:             if ($uploadedfile =~ /^scantron_orig_/) {
                   10970:                 my $logname = $uploadedfile;
                   10971:                 $logname =~ s/^scantron_orig_//;
                   10972:                 if ($logname ne '') {
                   10973:                     my $now = time;
                   10974:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   10975:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   10976:                 }
                   10977:             }
1.567     raeburn  10978:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  10979:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   10980:         } else {
                   10981:             $r->print(
                   10982:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   10983:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   10984:                           $result,
1.568     raeburn  10985: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 10986: 	}
                   10987:     }
1.174     albertel 10988:     if ($symb) {
1.612     www      10989: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 10990:     } else {
1.182     albertel 10991: 	$r->print($doanotherupload);
1.174     albertel 10992:     }
1.157     albertel 10993:     return '';
                   10994: }
                   10995: 
1.567     raeburn  10996: sub validate_uploaded_scantron_file {
1.770     raeburn  10997:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   10998: 
1.567     raeburn  10999:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   11000:     my @lines;
                   11001:     if ($scanlines ne '-1') {
                   11002:         @lines=split("\n",$scanlines,-1);
                   11003:     }
1.770     raeburn  11004:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   11005:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   11006:     if ($context eq 'download') {
                   11007:         $priv = 'mgr';
                   11008:     } else {
                   11009:         $priv = 'usc';
                   11010:     }
                   11011:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   11012:             (($env{'request.course.id'}) &&
                   11013:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   11014:         if ($env{'request.course.sec'} ne '') {
                   11015:             unless (&Apache::lonnet::allowed($priv,
                   11016:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   11017:                 unless ($context eq 'download') {
                   11018:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   11019:                 }
                   11020:                 return $output;
                   11021:             }
                   11022:             ($checksec,@possibles)=&gradable_sections();
                   11023:         }
                   11024:     }
1.567     raeburn  11025:     if (@lines) {
                   11026:         my (%counts,$max_match_format);
1.710     bisitz   11027:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  11028:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   11029:         my %idmap = &username_to_idmap($classlist);
                   11030:         foreach my $key (keys(%idmap)) {
                   11031:             my $lckey = lc($key);
                   11032:             $idmap{$lckey} = $idmap{$key};
                   11033:         }
                   11034:         my %unique_formats;
1.754     raeburn  11035:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  11036:         foreach my $line (@formatlines) {
1.790     raeburn  11037:             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  11038:             my @config = split(/:/,$line);
                   11039:             my $idstart = $config[5];
                   11040:             my $idlength = $config[6];
                   11041:             if (($idstart ne '') && ($idlength > 0)) {
                   11042:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   11043:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   11044:                 } else {
                   11045:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   11046:                 }
                   11047:             }
                   11048:         }
                   11049:         foreach my $key (keys(%unique_formats)) {
                   11050:             my ($idstart,$idlength) = split(':',$key);
                   11051:             %{$counts{$key}} = (
                   11052:                                'found'   => 0,
                   11053:                                'total'   => 0,
1.770     raeburn  11054:                                'totalanysec' => 0,
                   11055:                                'othersec' => 0,
1.567     raeburn  11056:                               );
                   11057:             foreach my $line (@lines) {
                   11058:                 next if ($line =~ /^#/);
                   11059:                 next if ($line =~ /^[\s\cz]*$/);
                   11060:                 my $id = substr($line,$idstart-1,$idlength);
                   11061:                 $id = lc($id);
                   11062:                 if (exists($idmap{$id})) {
1.770     raeburn  11063:                     if ($checksec ne '') {
                   11064:                         $counts{$key}{'totalanysec'} ++;
                   11065:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   11066:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   11067:                             if ($stusec ne $checksec) {
                   11068:                                 if (@possibles) {
                   11069:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   11070:                                         $counts{$key}{'othersec'} ++;
                   11071:                                         next;
                   11072:                                     }
                   11073:                                 } else {
                   11074:                                     $counts{$key}{'othersec'} ++;
                   11075:                                     next;
                   11076:                                 }
                   11077:                             }
                   11078:                         }
                   11079:                     }
1.567     raeburn  11080:                     $counts{$key}{'found'} ++;
                   11081:                 }
                   11082:                 $counts{$key}{'total'} ++;
                   11083:             }
                   11084:             if ($counts{$key}{'total'}) {
                   11085:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   11086:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   11087:                     $max_match_pct = $percent_match;
                   11088:                     $max_match_format = $key;
1.710     bisitz   11089:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  11090:                     $max_match_count = $counts{$key}{'total'};
                   11091:                 }
                   11092:             }
                   11093:         }
1.770     raeburn  11094:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  11095:             my $format_descs;
                   11096:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   11097:             for (my $i=0; $i<$numwithformat; $i++) {
                   11098:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   11099:                 if ($i<$numwithformat-2) {
                   11100:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   11101:                 } elsif ($i==$numwithformat-2) {
                   11102:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   11103:                 } elsif ($i==$numwithformat-1) {
                   11104:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   11105:                 }
                   11106:             }
                   11107:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   11108:             $output .= '<br />';
                   11109:             if ($found_match_count == $max_match_count) {
                   11110:                 # 100% matching entries
                   11111:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   11112:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   11113:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   11114:                 &mt('Comparison of student IDs in the uploaded file with'.
                   11115:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   11116:                     ' in the file (for the format defined for [_3]).',
                   11117:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   11118:             } else {
                   11119:                 # Not all entries matching? -> Show warning and additional info
                   11120:                 $output .=
                   11121:                     &Apache::lonhtmlcommon::confirm_success(
                   11122:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   11123:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   11124:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   11125:                     &mt('Comparison of student IDs in the uploaded file with'.
                   11126:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   11127:                         ' in the file (for the format defined for [_3]).',
                   11128:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   11129:                     '<p class="LC_info">'.
                   11130:                     &mt('A low percentage of matches results from one of the following:').
                   11131:                     '</p><ul>'.
                   11132:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   11133:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   11134:                                '<i>'.$cdom.'</i>').'</li>'.
                   11135:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   11136:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   11137:                     '</ul>';
                   11138:             }
1.770     raeburn  11139:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11140:                 if ($counts{$max_match_format}{'othersec'}) {
                   11141:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   11142:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   11143:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   11144:                     &js_escape(\$confirmdel);
                   11145:                     $output .= '<p class="LC_warning">'.
                   11146:                                &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',
                   11147:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   11148:                                '<br />'.
                   11149:                                &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>').
                   11150:                                '</p><p>'.
                   11151:                                &mt('If you prefer to delete the file now, use: [_1]').
                   11152:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   11153:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   11154:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   11155:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   11156:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   11157:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   11158:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   11159:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   11160:                                '</form></p>';
                   11161:                 }
                   11162:             }
1.567     raeburn  11163:         }
1.770     raeburn  11164:         if (($context eq 'download') && ($checksec ne '')) {
                   11165:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11166:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   11167:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   11168:             }
                   11169:         } 
                   11170:     } elsif ($context ne 'download') {
1.710     bisitz   11171:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  11172:     }
                   11173:     return $output;
                   11174: }
                   11175: 
1.770     raeburn  11176: sub gradable_sections {
                   11177:     my $checksec = $env{'request.course.sec'};
                   11178:     my @oksecs;
                   11179:     if ($checksec) {
                   11180:         my %availablesecs = &sections_grade_privs();
                   11181:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   11182:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   11183:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   11184:                     push(@oksecs,$sec);
                   11185:                 }
                   11186:             }
                   11187:             if (grep(/^all$/,@oksecs)) {
                   11188:                 undef($checksec);
                   11189:             }
                   11190:         }
                   11191:     }
                   11192:     return($checksec,@oksecs);
                   11193: }
                   11194: 
                   11195: sub sections_grade_privs {
                   11196:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11197:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11198:     my %availablesecs = (
                   11199:                           mgr => [],
                   11200:                           vgr => [],
                   11201:                           usc => [],
                   11202:                         );
                   11203:     my $ccrole = 'cc';
                   11204:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   11205:         $ccrole = 'co';
                   11206:     }
                   11207:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   11208:                                                      'userroles',['active'],
                   11209:                                                      [$ccrole,'in','cr'],$cdom,1);
                   11210:     my $crsid = $cnum.':'.$cdom;
                   11211:     foreach my $item (keys(%crsroleshash)) {
                   11212:         next unless ($item =~ /^$crsid\:/);
                   11213:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   11214:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   11215:         if ($sec ne '') {
                   11216:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   11217:         }
                   11218:         if (($role eq $ccrole) || ($role eq 'in')) {
                   11219:             foreach my $priv ('mgr','vgr','usc') { 
                   11220:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11221:                     if ($sec eq '') {
                   11222:                         $availablesecs{$priv} = ['all'];
                   11223:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   11224:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11225:                             push(@{$availablesecs{$priv}},$sec);
                   11226:                         }
                   11227:                     }
                   11228:                 }
                   11229:             }
                   11230:         } elsif ($role =~ m{^cr/}) {
                   11231:             foreach my $priv ('mgr','vgr','usc') {
                   11232:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11233:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   11234:                         if ($sec eq '') {
                   11235:                             $availablesecs{$priv} = ['all'];
                   11236:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   11237:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11238:                                 push(@{$availablesecs{$priv}},$sec);
                   11239:                             }
                   11240:                         }
                   11241:                     }
                   11242:                 }
                   11243:             }
                   11244:         }
                   11245:     }
                   11246:     return %availablesecs;
                   11247: }
                   11248: 
                   11249: sub scantron_upload_delete {
                   11250:     my ($r,$symb) = @_;
                   11251:     my $filename = $env{'form.uploadedfile'};
                   11252:     if ($filename =~ /^scantron_orig_/) {
                   11253:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   11254:             &Apache::lonnet::allowed('usc',
                   11255:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   11256:             &Apache::lonnet::allowed('usc',
                   11257:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   11258:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   11259:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   11260:             if ($retrieval eq '-1') {
                   11261:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11262:                           &mt('File requested for deletion not found.'));
                   11263:             } else {
                   11264:                 $filename =~ s/^scantron_orig_//;
                   11265:                 if ($filename ne '') {
                   11266:                     my ($is_valid,$numleft);
                   11267:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11268:                     if (keys(%info)) {
                   11269:                         if (ref($info{$filename}) eq 'HASH') {
                   11270:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   11271:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11272:                                     $is_valid = 1;
                   11273:                                     delete($info{$filename}{$timestamp}); 
                   11274:                                 }
                   11275:                             }
                   11276:                             $numleft = scalar(keys(%{$info{$filename}}));
                   11277:                         }
                   11278:                     }
                   11279:                     if ($is_valid) {
                   11280:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   11281:                         if ($result eq 'ok') {
                   11282:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   11283:                             if ($numleft) {
                   11284:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   11285:                             } else {
                   11286:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11287:                             }
                   11288:                         } else {
                   11289:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11290:                                       &mt('Result was [_1]',$result));
                   11291:                         }
                   11292:                     } else {
                   11293:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11294:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   11295:                     }
                   11296:                 } else {
                   11297:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11298:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11299:                 }
                   11300:             }
                   11301:         } else {
                   11302:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   11303:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   11304:         }
                   11305:     } else {
                   11306:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11307:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11308:     }
                   11309:     return;
                   11310: }
                   11311: 
1.202     albertel 11312: sub valid_file {
                   11313:     my ($requested_file)=@_;
                   11314:     foreach my $filename (sort(&scantron_filenames())) {
                   11315: 	if ($requested_file eq $filename) { return 1; }
                   11316:     }
                   11317:     return 0;
                   11318: }
                   11319: 
                   11320: sub scantron_download_scantron_data {
1.767     raeburn  11321:     my ($r,$symb) = @_;
1.608     www      11322:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 11323:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   11324:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   11325:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 11326:     if (! &valid_file($file)) {
1.492     albertel 11327: 	$r->print('
1.202     albertel 11328: 	<p>
1.686     bisitz   11329: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 11330:         </p>
1.492     albertel 11331: ');
1.202     albertel 11332: 	return;
                   11333:     }
1.770     raeburn  11334:     my (%uploader,$is_owner,%counts,$percent);
                   11335:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   11336:     if (ref($uploader{$file}) eq 'HASH') {
                   11337:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   11338:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11339:                 $is_owner = 1;
                   11340:                 last;
                   11341:             }
                   11342:         }
                   11343:     }
                   11344:     unless ($is_owner) {
                   11345:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   11346:         if ($counts{'totalanysec'}) {
                   11347:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   11348:             if ($percent_othersec >= 10) {
                   11349:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   11350:                 $r->print('<p class="LC_warning">'.
                   11351:                           &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).
                   11352:                           '</p>');
                   11353:                 return;
                   11354:             }
                   11355:         }
                   11356:     }
1.202     albertel 11357:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   11358:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   11359:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   11360:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   11361:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   11362:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 11363:     $r->print('
1.202     albertel 11364:     <p>
1.723     raeburn  11365: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 11366: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 11367:     </p>
                   11368:     <p>
1.492     albertel 11369: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   11370: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 11371:     </p>
                   11372:     <p>
1.492     albertel 11373: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   11374: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 11375:     </p>
1.492     albertel 11376: ');
1.202     albertel 11377:     return '';
                   11378: }
1.157     albertel 11379: 
1.523     raeburn  11380: sub checkscantron_results {
1.608     www      11381:     my ($r,$symb) = @_;
1.523     raeburn  11382:     if (!$symb) {return '';}
                   11383:     my $cid = $env{'request.course.id'};
1.755     raeburn  11384:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  11385:     my $numletts = scalar(keys(%lettdig));
                   11386:     my $cnum = $env{'course.'.$cid.'.num'};
                   11387:     my $cdom = $env{'course.'.$cid.'.domain'};
                   11388:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   11389:     my %record;
                   11390:     my %scantron_config =
1.754     raeburn  11391:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  11392:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  11393:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  11394:     my $classlist=&Apache::loncoursedata::get_classlist();
                   11395:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   11396:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  11397:     unless (ref($navmap)) {
                   11398:         $r->print(&navmap_errormsg());
                   11399:         return '';
                   11400:     }
1.523     raeburn  11401:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  11402:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   11403:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  11404:     if (ref($map)) { 
                   11405:         $randomorder=$map->randomorder();
1.689     raeburn  11406:         $randompick=$map->randompick();
1.788     raeburn  11407:         unless ($randomorder || $randompick) {
                   11408:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   11409:                 if ($res->randomorder()) {
                   11410:                     $randomorder = 1;
                   11411:                 }
                   11412:                 if ($res->randompick()) {
                   11413:                     $randompick = 1;
                   11414:                 }
                   11415:                 last if ($randomorder || $randompick);
                   11416:             }
                   11417:         }
1.677     raeburn  11418:     }
1.557     raeburn  11419:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  11420:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   11421:     if ($nav_error) {
                   11422:         $r->print(&navmap_errormsg());
                   11423:         return '';
1.678     raeburn  11424:     }
1.673     raeburn  11425:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   11426:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  11427:     my ($uname,$udom);
1.523     raeburn  11428:     my (%scandata,%lastname,%bylast);
                   11429:     $r->print('
                   11430: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   11431: 
                   11432:     my @delayqueue;
                   11433:     my %completedstudents;
                   11434: 
1.691     raeburn  11435:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      11436:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  11437:     my ($username,$domain,$started);
1.649     raeburn  11438:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  11439:     if ($nav_error) {
                   11440:         $r->print(&navmap_errormsg());
                   11441:         return '';
                   11442:     }
1.523     raeburn  11443: 
1.667     www      11444:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  11445:     my $start=&Time::HiRes::time();
                   11446:     my $i=-1;
                   11447: 
                   11448:     while ($i<$scanlines->{'count'}) {
                   11449:         ($username,$domain,$uname)=('','','');
                   11450:         $i++;
                   11451:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   11452:         if ($line=~/^[\s\cz]*$/) { next; }
                   11453:         if ($started) {
1.667     www      11454:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  11455:         }
                   11456:         $started=1;
                   11457:         my $scan_record=
                   11458:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   11459:                                                      $scan_data);
1.693     raeburn  11460:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   11461:                                               \%idmap,$i)) {
1.523     raeburn  11462:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11463:                                 'Unable to find a student that matches',1);
                   11464:             next;
                   11465:         }
                   11466:         if (exists $completedstudents{$uname}) {
                   11467:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11468:                                 'Student '.$uname.' has multiple sheets',2);
                   11469:             next;
                   11470:         }
                   11471:         my $pid = $scan_record->{'scantron.ID'};
                   11472:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   11473:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  11474:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   11475:         my $user = $uname.':'.$usec;
1.523     raeburn  11476:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  11477: 
1.678     raeburn  11478:         my $scancode;
1.677     raeburn  11479:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   11480:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   11481:             $scancode = $scan_record->{'scantron.CODE'};
                   11482:         } else {
                   11483:             $scancode = '';
                   11484:         }
                   11485: 
                   11486:         my @mapresources = @resources;
1.691     raeburn  11487:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   11488:         my %respnumlookup=();
                   11489:         my %startline=();
1.689     raeburn  11490:         if ($randomorder || $randompick) {
1.678     raeburn  11491:             @mapresources =
1.691     raeburn  11492:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   11493:                              \%orderedforcode);
                   11494:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   11495:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   11496:                                              \%grader_partids_by_symb,\%orderedforcode,
                   11497:                                              \%respnumlookup,\%startline);
                   11498:             if ($randompick && $total) {
                   11499:                 $lastpos = $total*$scantron_config{'Qlength'};
                   11500:             }
1.677     raeburn  11501:         }
1.691     raeburn  11502:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   11503:         chomp($scandata{$pid});
                   11504:         $scandata{$pid} =~ s/\r$//;
                   11505: 
1.523     raeburn  11506:         my $counter = -1;
1.677     raeburn  11507:         foreach my $resource (@mapresources) {
1.557     raeburn  11508:             my $parts;
1.554     raeburn  11509:             my $ressymb = $resource->symb();
1.557     raeburn  11510:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   11511:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  11512:                 my $currcode;
                   11513:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   11514:                     $currcode = $scancode;
                   11515:                 }
1.557     raeburn  11516:                 (my $analysis,$parts) =
1.672     raeburn  11517:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   11518:                                               $username,$domain,undef,
1.741     raeburn  11519:                                               $bubbles_per_row,$currcode);
1.557     raeburn  11520:             } else {
                   11521:                 $parts = $grader_partids_by_symb{$ressymb};
                   11522:             }
1.542     raeburn  11523:             ($counter,my $recording) =
                   11524:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  11525:                                          $scandata{$pid},$parts,
1.691     raeburn  11526:                                          \%scantron_config,\%lettdig,$numletts,
                   11527:                                          $randomorder,$randompick,
                   11528:                                          \%respnumlookup,\%startline);
1.542     raeburn  11529:             $record{$pid} .= $recording;
1.523     raeburn  11530:         }
                   11531:     }
                   11532:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   11533:     $r->print('<br />');
                   11534:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   11535:     $passed = 0;
                   11536:     $failed = 0;
                   11537:     $numstudents = 0;
                   11538:     foreach my $last (sort(keys(%bylast))) {
                   11539:         if (ref($bylast{$last}) eq 'ARRAY') {
                   11540:             foreach my $pid (sort(@{$bylast{$last}})) {
                   11541:                 my $showscandata = $scandata{$pid};
                   11542:                 my $showrecord = $record{$pid};
                   11543:                 $showscandata =~ s/\s/&nbsp;/g;
                   11544:                 $showrecord =~ s/\s/&nbsp;/g;
                   11545:                 if ($scandata{$pid} eq $record{$pid}) {
                   11546:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   11547:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      11548: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  11549: '</tr>'."\n".
                   11550: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11551: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  11552:                     $passed ++;
                   11553:                 } else {
                   11554:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      11555:                     $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  11556: '</tr>'."\n".
                   11557: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11558: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  11559: '</tr>'."\n";
                   11560:                     $failed ++;
                   11561:                 }
                   11562:                 $numstudents ++;
                   11563:             }
                   11564:         }
                   11565:     }
1.648     bisitz   11566:     $r->print(
                   11567:         '<p>'
                   11568:        .&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).',
                   11569:             '<b>',
                   11570:             $numstudents,
                   11571:             '</b>',
                   11572:             $env{'form.scantron_maxbubble'})
                   11573:        .'</p>'
                   11574:     );
1.682     raeburn  11575:     $r->print('<p>'
1.683     raeburn  11576:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  11577:              .'<br />'
                   11578:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   11579:              .'</p>'
                   11580:     );
1.523     raeburn  11581:     if ($passed) {
1.572     www      11582:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11583:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11584:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11585:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11586:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11587:                  $okstudents."\n".
                   11588:                  &Apache::loncommon::end_data_table().'<br />');
                   11589:     }
                   11590:     if ($failed) {
1.572     www      11591:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11592:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11593:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11594:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11595:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11596:                  $badstudents."\n".
                   11597:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      11598:                  &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  11599:     }
1.614     www      11600:     $r->print('</form><br />');
1.523     raeburn  11601:     return;
                   11602: }
                   11603: 
1.542     raeburn  11604: sub verify_scantron_grading {
1.554     raeburn  11605:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  11606:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   11607:         $respnumlookup,$startline) = @_;
1.542     raeburn  11608:     my ($record,%expected,%startpos);
                   11609:     return ($counter,$record) if (!ref($resource));
                   11610:     return ($counter,$record) if (!$resource->is_problem());
                   11611:     my $symb = $resource->symb();
1.554     raeburn  11612:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   11613:     foreach my $part_id (@{$partids}) {
1.542     raeburn  11614:         $counter ++;
                   11615:         $expected{$part_id} = 0;
1.691     raeburn  11616:         my $respnum = $counter;
                   11617:         if ($randomorder || $randompick) {
                   11618:             $respnum = $respnumlookup->{$counter};
                   11619:             $startpos{$part_id} = $startline->{$counter} + 1;
                   11620:         } else {
                   11621:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   11622:         }
                   11623:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   11624:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  11625:             foreach my $item (@sub_lines) {
                   11626:                 $expected{$part_id} += $item;
                   11627:             }
                   11628:         } else {
1.691     raeburn  11629:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  11630:         }
                   11631:     }
                   11632:     if ($symb) {
                   11633:         my %recorded;
                   11634:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   11635:         if ($returnhash{'version'}) {
                   11636:             my %lasthash=();
                   11637:             my $version;
                   11638:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   11639:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   11640:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   11641:                 }
                   11642:             }
                   11643:             foreach my $key (keys(%lasthash)) {
                   11644:                 if ($key =~ /\.scantron$/) {
                   11645:                     my $value = &unescape($lasthash{$key});
                   11646:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   11647:                     if ($value eq '') {
                   11648:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11649:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   11650:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11651:                             }
                   11652:                         }
                   11653:                     } else {
                   11654:                         my @tocheck;
                   11655:                         my @items = split(//,$value);
                   11656:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   11657:                             ($scantron_config->{'Qon'} eq 'number')) {
                   11658:                             if (@items < $expected{$part_id}) {
                   11659:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   11660:                                 my @singles = split(//,$fragment);
                   11661:                                 foreach my $pos (@singles) {
                   11662:                                     if ($pos eq ' ') {
                   11663:                                         push(@tocheck,$pos);
                   11664:                                     } else {
                   11665:                                         my $next = shift(@items);
                   11666:                                         push(@tocheck,$next);
                   11667:                                     }
                   11668:                                 }
                   11669:                             } else {
                   11670:                                 @tocheck = @items;
                   11671:                             }
                   11672:                             foreach my $letter (@tocheck) {
                   11673:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   11674:                                     if ($letter !~ /^[A-J]$/) {
                   11675:                                         $letter = $scantron_config->{'Qoff'};
                   11676:                                     }
                   11677:                                     $recorded{$part_id} .= $letter;
                   11678:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   11679:                                     my $digit;
                   11680:                                     if ($letter !~ /^[A-J]$/) {
                   11681:                                         $digit = $scantron_config->{'Qoff'};
                   11682:                                     } else {
                   11683:                                         $digit = $lettdig->{$letter};
                   11684:                                     }
                   11685:                                     $recorded{$part_id} .= $digit;
                   11686:                                 }
                   11687:                             }
                   11688:                         } else {
                   11689:                             @tocheck = @items;
                   11690:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11691:                                 my $curr_sub = shift(@tocheck);
                   11692:                                 my $digit;
                   11693:                                 if ($curr_sub =~ /^[A-J]$/) {
                   11694:                                     $digit = $lettdig->{$curr_sub}-1;
                   11695:                                 }
                   11696:                                 if ($curr_sub eq 'J') {
                   11697:                                     $digit += scalar($numletts);
                   11698:                                 }
                   11699:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11700:                                     if ($j == $digit) {
                   11701:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   11702:                                     } else {
                   11703:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11704:                                     }
                   11705:                                 }
                   11706:                             }
                   11707:                         }
                   11708:                     }
                   11709:                 }
                   11710:             }
                   11711:         }
1.554     raeburn  11712:         foreach my $part_id (@{$partids}) {
1.542     raeburn  11713:             if ($recorded{$part_id} eq '') {
                   11714:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11715:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11716:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11717:                     }
                   11718:                 }
                   11719:             }
                   11720:             $record .= $recorded{$part_id};
                   11721:         }
                   11722:     }
                   11723:     return ($counter,$record);
                   11724: }
                   11725: 
1.75      albertel 11726: #-------- end of section for handling grading scantron forms -------
                   11727: #
                   11728: #-------------------------------------------------------------------
                   11729: 
1.72      ng       11730: #-------------------------- Menu interface -------------------------
                   11731: #
1.614     www      11732: #--- Href with symb and command ---
                   11733: 
                   11734: sub href_symb_cmd {
                   11735:     my ($symb,$cmd)=@_;
1.796     raeburn  11736:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.
                   11737:            &HTML::Entities::encode($cmd,'<>&"');
1.72      ng       11738: }
                   11739: 
1.443     banghart 11740: sub grading_menu {
1.608     www      11741:     my ($request,$symb) = @_;
1.443     banghart 11742:     if (!$symb) {return '';}
                   11743: 
                   11744:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      11745:                   'command'=>'individual');
1.538     schulted 11746:     
1.598     www      11747:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11748: 
                   11749:     $fields{'command'}='ungraded';
                   11750:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11751: 
                   11752:     $fields{'command'}='table';
                   11753:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11754: 
                   11755:     $fields{'command'}='all_for_one';
                   11756:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11757: 
1.621     www      11758:     $fields{'command'}='downloadfilesselect';
                   11759:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11760: 
1.443     banghart 11761:     $fields{'command'} = 'csvform';
1.538     schulted 11762:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11763:     
1.443     banghart 11764:     $fields{'command'} = 'processclicker';
1.538     schulted 11765:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11766:     
1.443     banghart 11767:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 11768:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      11769: 
                   11770:     $fields{'command'} = 'initialverifyreceipt';
                   11771:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  11772: 
                   11773:     my %permissions;
                   11774:     if ($perm{'mgr'}) {
                   11775:         $permissions{'either'} = 'F';
                   11776:         $permissions{'mgr'} = 'F';
                   11777:     }
                   11778:     if ($perm{'vgr'}) {
                   11779:         $permissions{'either'} = 'F';
                   11780:         $permissions{'vgr'} = 'F';
                   11781:     }
                   11782: 
1.598     www      11783:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 11784:             items =>[
1.598     www      11785:                         {	linktext => 'Select individual students to grade',
                   11786:                     		url => $url1a,
1.781     raeburn  11787:                     		permission => $permissions{'either'},
1.636     wenzelju 11788:                     		icon => 'grade_students.png',
1.598     www      11789:                     		linktitle => 'Grade current resource for a selection of students.'
                   11790:                         }, 
1.764     raeburn  11791:                         {       linktext => 'Grade ungraded submissions',
1.598     www      11792:                                 url => $url1b,
1.781     raeburn  11793:                                 permission => $permissions{'either'},
1.636     wenzelju 11794:                                 icon => 'ungrade_sub.png',
1.598     www      11795:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 11796:                         },
1.598     www      11797: 
                   11798:                         {       linktext => 'Grading table',
                   11799:                                 url => $url1c,
1.781     raeburn  11800:                                 permission => $permissions{'either'},
1.636     wenzelju 11801:                                 icon => 'grading_table.png',
1.598     www      11802:                                 linktitle => 'Grade current resource for all students.'
                   11803:                         },
1.615     www      11804:                         {       linktext => 'Grade page/folder for one student',
1.598     www      11805:                                 url => $url1d,
1.781     raeburn  11806:                                 permission => $permissions{'either'},
1.636     wenzelju 11807:                                 icon => 'grade_PageFolder.png',
1.598     www      11808:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      11809:                         },
                   11810:                         {       linktext => 'Download submissions',
                   11811:                                 url => $url1e,
1.781     raeburn  11812:                                 permission => $permissions{'either'},
1.636     wenzelju 11813:                                 icon => 'download_sub.png',
1.621     www      11814:                                 linktitle => 'Download all students submissions.'
1.598     www      11815:                         }]},
                   11816:                          { categorytitle=>'Automated Grading',
                   11817:                items =>[
                   11818: 
1.538     schulted 11819:                 	    {	linktext => 'Upload Scores',
                   11820:                     		url => $url2,
1.780     raeburn  11821:                     		permission => $permissions{'mgr'},
1.538     schulted 11822:                     		icon => 'uploadscores.png',
                   11823:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   11824:                 	    },
                   11825:                 	    {	linktext => 'Process Clicker',
                   11826:                     		url => $url3,
1.780     raeburn  11827:                     		permission => $permissions{'mgr'},
1.538     schulted 11828:                     		icon => 'addClickerInfoFile.png',
                   11829:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   11830:                 	    },
1.587     raeburn  11831:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 11832:                     		url => $url4,
1.780     raeburn  11833:                     		permission => $permissions{'mgr'},
1.636     wenzelju 11834:                     		icon => 'bubblesheet.png',
1.648     bisitz   11835:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      11836:                 	    },
1.616     www      11837:                             {   linktext => 'Verify Receipt Number',
1.602     www      11838:                                 url => $url5,
1.780     raeburn  11839:                                 permission => $permissions{'either'},
1.636     wenzelju 11840:                                 icon => 'receipt_number.png',
1.602     www      11841:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   11842:                             }
                   11843: 
1.538     schulted 11844:                     ]
                   11845:             });
1.796     raeburn  11846:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   11847:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   11848:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   11849:     if (keys(%passback)) {
                   11850:         $fields{'command'} = 'initialpassback';
                   11851:         my $url6 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11852:         push (@{$menu[1]{items}},
                   11853:                   { linktext => 'Passback of Scores',
                   11854:                     url => $url6,
                   11855:                     permission => $permissions{'either'},
                   11856:                     icon => 'passback.png',
                   11857:                     linktitle => 'Passback scores to launcher CMS for resources accessed via LTI-mediated deep-linking',
                   11858:                   });
                   11859:     }
1.443     banghart 11860:     # Create the menu
                   11861:     my $Str;
1.445     banghart 11862:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   11863:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      11864:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 11865: 
1.602     www      11866:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 11867:     return $Str;    
                   11868: }
                   11869: 
1.598     www      11870: sub ungraded {
                   11871:     my ($request)=@_;
                   11872:     &submit_options($request);
                   11873: }
                   11874: 
1.599     www      11875: sub submit_options_sequence {
1.608     www      11876:     my ($request,$symb) = @_;
1.599     www      11877:     if (!$symb) {return '';}
1.600     www      11878:     &commonJSfunctions($request);
                   11879:     my $result;
1.599     www      11880: 
1.600     www      11881:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11882:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      11883:     $result.=&selectfield(0).
1.601     www      11884:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      11885:             <div>
                   11886:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11887:             </div>
                   11888:         </div>
                   11889:   </form>';
                   11890:     return $result;
                   11891: }
                   11892: 
                   11893: sub submit_options_table {
1.608     www      11894:     my ($request,$symb) = @_;
1.600     www      11895:     if (!$symb) {return '';}
1.599     www      11896:     &commonJSfunctions($request);
1.746     raeburn  11897:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      11898:     my $result;
                   11899: 
                   11900:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11901:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      11902: 
1.745     raeburn  11903:     $result.=&selectfield(1,$is_tool).
1.601     www      11904:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      11905:             <div>
                   11906:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11907:             </div>
                   11908:         </div>
                   11909:   </form>';
                   11910:     return $result;
                   11911: }
1.443     banghart 11912: 
1.621     www      11913: sub submit_options_download {
                   11914:     my ($request,$symb) = @_;
                   11915:     if (!$symb) {return '';}
                   11916: 
1.773     raeburn  11917:     my $res_error;
                   11918:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   11919:         &response_type($symb,\$res_error);
                   11920:     if ($res_error) {
                   11921:         $request->print(&mt('An error occurred retrieving response types'));
                   11922:         return;
                   11923:     }
                   11924:     unless ($numessay) {
                   11925:         $request->print(&mt('No essayresponse items found'));
                   11926:         return;
                   11927:     }
                   11928:     my $table;
                   11929:     if (ref($partlist) eq 'ARRAY') {
                   11930:         if (scalar(@$partlist) > 1 ) {
                   11931:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   11932:         }
                   11933:     }
                   11934: 
1.746     raeburn  11935:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      11936:     &commonJSfunctions($request);
                   11937: 
                   11938:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  11939:                $table."\n".
                   11940:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      11941:     $result.='
                   11942: <h2>
1.750     raeburn  11943:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  11944: </h2>'.&selectfield(1,$is_tool).'
1.621     www      11945:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   11946:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11947:             </div>
                   11948:           </div>
1.600     www      11949: 
                   11950: 
1.621     www      11951:   </form>';
                   11952:     return $result;
                   11953: }
                   11954: 
1.443     banghart 11955: #--- Displays the submissions first page -------
                   11956: sub submit_options {
1.608     www      11957:     my ($request,$symb) = @_;
1.72      ng       11958:     if (!$symb) {return '';}
                   11959: 
1.746     raeburn  11960:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       11961:     &commonJSfunctions($request);
1.473     albertel 11962:     my $result;
1.533     bisitz   11963: 
1.72      ng       11964:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11965: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  11966:     $result.=&selectfield(1,$is_tool).'
1.601     www      11967:                 <input type="hidden" name="command" value="submission" /> 
                   11968: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11969:             </div>
                   11970:           </div>
                   11971:   </form>';
                   11972:     return $result;
                   11973: }
1.533     bisitz   11974: 
1.601     www      11975: sub selectfield {
1.745     raeburn  11976:    my ($full,$is_tool)=@_;
                   11977:    my %options;
                   11978:    if ($is_tool) {
                   11979:        %options =
                   11980:            (&transtatus_options,
                   11981:             'select_form_order' => ['yes','incorrect','all']);
                   11982:    } else {
                   11983:        %options = 
                   11984:            (&substatus_options,
                   11985:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   11986:    }
1.782     raeburn  11987: 
                   11988:   #
                   11989:   # PrepareClasslist() needs to be called to avoid getting a sections list
                   11990:   # for a different course from the @Sections global in lonstatistics.pm, 
                   11991:   # populated by an earlier request.
                   11992:   #
                   11993:    &Apache::lonstatistics::PrepareClasslist();
                   11994: 
1.601     www      11995:    my $result='<div class="LC_columnSection">
1.537     harmsja  11996:   
1.533     bisitz   11997:     <fieldset>
                   11998:       <legend>
                   11999:        '.&mt('Sections').'
                   12000:       </legend>
1.601     www      12001:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   12002:     </fieldset>
1.537     harmsja  12003:   
1.533     bisitz   12004:     <fieldset>
                   12005:       <legend>
                   12006:         '.&mt('Groups').'
                   12007:       </legend>
                   12008:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   12009:     </fieldset>
1.537     harmsja  12010:   
1.533     bisitz   12011:     <fieldset>
                   12012:       <legend>
                   12013:         '.&mt('Access Status').'
                   12014:       </legend>
1.601     www      12015:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   12016:     </fieldset>';
                   12017:     if ($full) {
1.745     raeburn  12018:         my $heading = &mt('Submission Status');
                   12019:         if ($is_tool) {
                   12020:             $heading = &mt('Transaction Status');
                   12021:         }
                   12022:         $result.='
1.533     bisitz   12023:     <fieldset>
                   12024:       <legend>
1.745     raeburn  12025:         '.$heading.'
1.601     www      12026:       </legend>'.
1.635     raeburn  12027:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      12028:    '</fieldset>';
                   12029:     }
                   12030:     $result.='</div><br />';
1.44      ng       12031:     return $result;
1.2       albertel 12032: }
                   12033: 
1.738     raeburn  12034: sub substatus_options {
                   12035:     return &Apache::lonlocal::texthash(
                   12036:                                       'yes'       => 'with submissions',
                   12037:                                       'queued'    => 'in grading queue',
                   12038:                                       'graded'    => 'with ungraded submissions',
                   12039:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  12040:                                       'all'       => 'with any status',
                   12041:                                       );
1.738     raeburn  12042: }
                   12043: 
1.745     raeburn  12044: sub transtatus_options {
                   12045:     return &Apache::lonlocal::texthash(
                   12046:                                        'yes'       => 'with score transactions',
                   12047:                                        'incorrect' => 'with less than full credit',
                   12048:                                        'all'       => 'with any status',
                   12049:                                       );
                   12050: }
                   12051: 
1.285     albertel 12052: sub reset_perm {
                   12053:     undef(%perm);
                   12054: }
                   12055: 
                   12056: sub init_perm {
                   12057:     &reset_perm();
1.770     raeburn  12058:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 12059: 
                   12060: 	my $scope = $env{'request.course.id'};
                   12061: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   12062: 
                   12063: 	    $scope .= '/'.$env{'request.course.sec'};
                   12064: 	    if ( $perm{$test_perm}=
                   12065: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   12066: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   12067: 	    } else {
                   12068: 		delete($perm{$test_perm});
                   12069: 	    }
1.285     albertel 12070: 	}
                   12071:     }
                   12072: }
                   12073: 
1.674     raeburn  12074: sub init_old_essays {
                   12075:     my ($symb,$apath,$adom,$aname) = @_;
                   12076:     if ($symb ne '') {
                   12077:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   12078:         if (keys(%essays) > 0) {
                   12079:             $old_essays{$symb} = \%essays;
                   12080:         }
                   12081:     }
                   12082:     return;
                   12083: }
                   12084: 
                   12085: sub reset_old_essays {
                   12086:     undef(%old_essays);
                   12087: }
                   12088: 
1.400     www      12089: sub gather_clicker_ids {
1.408     albertel 12090:     my %clicker_ids;
1.400     www      12091: 
                   12092:     my $classlist = &Apache::loncoursedata::get_classlist();
                   12093: 
                   12094:     # Set up a couple variables.
1.407     albertel 12095:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   12096:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      12097:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      12098: 
1.407     albertel 12099:     foreach my $student (keys(%$classlist)) {
1.438     www      12100:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 12101:         my $username = $classlist->{$student}->[$username_idx];
                   12102:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      12103:         my $clickers =
1.408     albertel 12104: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      12105:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      12106:             $id=~s/^[\#0]+//;
1.421     www      12107:             $id=~s/[\-\:]//g;
1.407     albertel 12108:             if (exists($clicker_ids{$id})) {
1.408     albertel 12109: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      12110:             } else {
1.408     albertel 12111: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      12112:             }
                   12113:         }
                   12114:     }
1.407     albertel 12115:     return %clicker_ids;
1.400     www      12116: }
                   12117: 
1.402     www      12118: sub gather_adv_clicker_ids {
1.408     albertel 12119:     my %clicker_ids;
1.402     www      12120:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   12121:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   12122:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 12123:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      12124:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   12125:             my ($puname,$pudom)=split(/\:/,$person);
                   12126:             my $clickers =
1.408     albertel 12127: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      12128:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      12129: 		$id=~s/^[\#0]+//;
1.421     www      12130:                 $id=~s/[\-\:]//g;
1.408     albertel 12131: 		if (exists($clicker_ids{$id})) {
                   12132: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   12133: 		} else {
                   12134: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   12135: 		}
1.405     www      12136:             }
1.402     www      12137:         }
                   12138:     }
1.407     albertel 12139:     return %clicker_ids;
1.402     www      12140: }
                   12141: 
1.413     www      12142: sub clicker_grading_parameters {
                   12143:     return ('gradingmechanism' => 'scalar',
                   12144:             'upfiletype' => 'scalar',
                   12145:             'specificid' => 'scalar',
                   12146:             'pcorrect' => 'scalar',
                   12147:             'pincorrect' => 'scalar');
                   12148: }
                   12149: 
1.400     www      12150: sub process_clicker {
1.608     www      12151:     my ($r,$symb)=@_;
1.400     www      12152:     if (!$symb) {return '';}
                   12153:     my $result=&checkforfile_js();
1.632     www      12154:     $result.=&Apache::loncommon::start_data_table().
                   12155:              &Apache::loncommon::start_data_table_header_row().
                   12156:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   12157:              &Apache::loncommon::end_data_table_header_row().
                   12158:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      12159: # Attempt to restore parameters from last session, set defaults if not present
                   12160:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12161:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   12162:                                                  \%Saveable_Parameters);
                   12163:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   12164:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   12165:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   12166:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   12167: 
                   12168:     my %checked;
1.521     www      12169:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      12170:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   12171:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      12172:        }
                   12173:     }
                   12174: 
1.632     www      12175:     my $upload=&mt("Evaluate File");
1.400     www      12176:     my $type=&mt("Type");
1.402     www      12177:     my $attendance=&mt("Award points just for participation");
                   12178:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      12179:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      12180:     my $given=&mt("Correctness determined from given list of answers").' '.
                   12181:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      12182:     my $pcorrect=&mt("Percentage points for correct solution");
                   12183:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      12184:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  12185: 						   {'iclicker' => 'i>clicker',
1.666     www      12186:                                                     'interwrite' => 'interwrite PRS',
                   12187:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 12188:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 12189:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      12190: function sanitycheck() {
                   12191: // Accept only integer percentages
                   12192:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   12193:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   12194: // Find out grading choice
                   12195:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12196:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   12197:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   12198:       }
                   12199:    }
                   12200: // By default, new choice equals user selection
                   12201:    newgradingchoice=gradingchoice;
                   12202: // Not good to give more points for false answers than correct ones
                   12203:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   12204:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   12205:    }
                   12206: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   12207:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   12208:       document.forms.gradesupload.pcorrect.value=100;
                   12209:       document.forms.gradesupload.pincorrect.value=100;
                   12210:    }
                   12211: // If the values are different, cannot be attendance only
                   12212:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   12213:        (gradingchoice=='attendance')) {
                   12214:        newgradingchoice='personnel';
                   12215:    }
                   12216: // Change grading choice to new one
                   12217:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12218:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   12219:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   12220:       } else {
                   12221:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   12222:       }
                   12223:    }
                   12224: // Remember the old state
                   12225:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   12226: }
1.597     wenzelju 12227: ENDUPFORM
                   12228:     $result.= <<ENDUPFORM;
1.400     www      12229: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   12230: <input type="hidden" name="symb" value="$symb" />
                   12231: <input type="hidden" name="command" value="processclickerfile" />
                   12232: <input type="file" name="upfile" size="50" />
                   12233: <br /><label>$type: $selectform</label>
1.632     www      12234: ENDUPFORM
                   12235:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   12236:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   12237:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   12238: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   12239: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      12240: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   12241: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      12242: <br />&nbsp;&nbsp;&nbsp;
                   12243: <input type="text" name="givenanswer" size="50" />
1.413     www      12244: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      12245: ENDGRADINGFORM
1.766     raeburn  12246:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      12247:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   12248:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   12249: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   12250: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  12251: </form>
1.632     www      12252: ENDPERCFORM
                   12253:     $result.='</td>'.
                   12254:              &Apache::loncommon::end_data_table_row().
                   12255:              &Apache::loncommon::end_data_table();
1.400     www      12256:     return $result;
                   12257: }
                   12258: 
                   12259: sub process_clicker_file {
1.766     raeburn  12260:     my ($r,$symb) = @_;
1.400     www      12261:     if (!$symb) {return '';}
1.413     www      12262: 
                   12263:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12264:     &Apache::loncommon::store_course_settings('grades_clicker',
                   12265:                                               \%Saveable_Parameters);
1.598     www      12266:     my $result='';
1.404     www      12267:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 12268: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      12269: 	return $result;
1.404     www      12270:     }
1.522     www      12271:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      12272:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      12273:         return $result;
1.521     www      12274:     }
1.522     www      12275:     my $foundgiven=0;
1.521     www      12276:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12277:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   12278:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      12279:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      12280:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      12281:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   12282:         $foundgiven=$#answers+1;
1.521     www      12283:     }
1.407     albertel 12284:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 12285:     my %correct_ids;
1.404     www      12286:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 12287: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      12288:     }
                   12289:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      12290: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   12291: 	   $correct_id=~tr/a-z/A-Z/;
                   12292: 	   $correct_id=~s/\s//gs;
                   12293: 	   $correct_id=~s/^[\#0]+//;
1.421     www      12294:            $correct_id=~s/[\-\:]//g;
1.414     www      12295:            if ($correct_id) {
                   12296: 	      $correct_ids{$correct_id}='specified';
                   12297:            }
                   12298:         }
1.400     www      12299:     }
1.404     www      12300:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 12301: 	$result.=&mt('Score based on attendance only');
1.521     www      12302:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      12303:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      12304:     } else {
1.408     albertel 12305: 	my $number=0;
1.411     www      12306: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 12307: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      12308: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 12309: 	    if ($correct_ids{$id} eq 'specified') {
                   12310: 		$result.=&mt('specified');
                   12311: 	    } else {
                   12312: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   12313: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   12314: 	    }
                   12315: 	    $number++;
                   12316: 	}
1.411     www      12317:         $result.="</p>\n";
1.710     bisitz   12318:         if ($number==0) {
                   12319:             $result .=
                   12320:                  &Apache::lonhtmlcommon::confirm_success(
                   12321:                      &mt('No IDs found to determine correct answer'),1);
                   12322:             return $result;
                   12323:         }
1.404     www      12324:     }
1.405     www      12325:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   12326:         $result .=
                   12327:             &Apache::lonhtmlcommon::confirm_success(
                   12328:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   12329:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      12330:         return $result;
1.405     www      12331:     }
1.760     raeburn  12332:     my $mimetype;
                   12333:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   12334:         my $mm = new File::MMagic;
                   12335:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   12336:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   12337:             $result.= '<p>'.
                   12338:                 &Apache::lonhtmlcommon::confirm_success(
                   12339:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   12340:             return $result;
                   12341:         }
                   12342:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   12343:         $result .= '<p>'.
                   12344:             &Apache::lonhtmlcommon::confirm_success(
                   12345:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   12346:         return $result;
                   12347:     }
1.410     www      12348: 
                   12349: # Were able to get all the info needed, now analyze the file
                   12350: 
1.411     www      12351:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 12352:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      12353:     $result.=&Apache::loncommon::start_data_table().
                   12354:              &Apache::loncommon::start_data_table_header_row().
                   12355:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   12356:              &Apache::loncommon::end_data_table_header_row().
                   12357:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   12358: <td>
1.410     www      12359: <form method="post" action="/adm/grades" name="clickeranalysis">
                   12360: <input type="hidden" name="symb" value="$symb" />
                   12361: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      12362: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   12363: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   12364: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      12365: ENDHEADER
1.522     www      12366:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12367:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   12368:     } 
1.408     albertel 12369:     my %responses;
                   12370:     my @questiontitles;
1.405     www      12371:     my $errormsg='';
                   12372:     my $number=0;
                   12373:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  12374:         if ($mimetype eq 'text/plain') {
                   12375:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   12376:         } elsif ($mimetype eq 'text/html') {
                   12377:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   12378:         }
                   12379:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      12380:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  12381:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      12382:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   12383:     }
1.411     www      12384:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   12385:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   12386:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   12387:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   12388:              '<br />';
1.522     www      12389:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   12390:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      12391:        return $result;
1.522     www      12392:     } 
1.414     www      12393: # Remember Question Titles
                   12394: # FIXME: Possibly need delimiter other than ":"
                   12395:     for (my $i=0;$i<$number;$i++) {
                   12396:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   12397:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   12398:     }
1.411     www      12399:     my $correct_count=0;
                   12400:     my $student_count=0;
                   12401:     my $unknown_count=0;
1.414     www      12402: # Match answers with usernames
                   12403: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 12404:     foreach my $id (keys(%responses)) {
1.410     www      12405:        if ($correct_ids{$id}) {
1.414     www      12406:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      12407:           $correct_count++;
1.410     www      12408:        } elsif ($clicker_ids{$id}) {
1.437     www      12409:           if ($clicker_ids{$id}=~/\,/) {
                   12410: # More than one user with the same clicker!
1.632     www      12411:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12412:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12413:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      12414:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12415:                            "<select name='multi".$id."'>";
                   12416:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   12417:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   12418:              }
                   12419:              $result.='</select>';
                   12420:              $unknown_count++;
                   12421:           } else {
                   12422: # Good: found one and only one user with the right clicker
                   12423:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   12424:              $student_count++;
                   12425:           }
1.410     www      12426:        } else {
1.632     www      12427:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12428:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12429:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      12430:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12431:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   12432:                    "\n".&mt("Domain").": ".
                   12433:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  12434:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      12435:           $unknown_count++;
1.410     www      12436:        }
1.405     www      12437:     }
1.412     www      12438:     $result.='<hr />'.
                   12439:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      12440:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      12441:        if ($correct_count==0) {
1.696     bisitz   12442:           $errormsg.="Found no correct answers for grading!";
1.412     www      12443:        } elsif ($correct_count>1) {
1.414     www      12444:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      12445:        }
                   12446:     }
1.428     www      12447:     if ($number<1) {
                   12448:        $errormsg.="Found no questions.";
                   12449:     }
1.412     www      12450:     if ($errormsg) {
                   12451:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   12452:     } else {
                   12453:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   12454:     }
1.632     www      12455:     $result.='</form></td>'.
                   12456:              &Apache::loncommon::end_data_table_row().
                   12457:              &Apache::loncommon::end_data_table();
1.614     www      12458:     return $result;
1.400     www      12459: }
                   12460: 
1.405     www      12461: sub iclicker_eval {
1.406     www      12462:     my ($questiontitles,$responses)=@_;
1.405     www      12463:     my $number=0;
                   12464:     my $errormsg='';
                   12465:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      12466:         my %components=&Apache::loncommon::record_sep($line);
                   12467:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 12468: 	if ($entries[0] eq 'Question') {
                   12469: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   12470: 		$$questiontitles[$number]=$entries[$i];
                   12471: 		$number++;
                   12472: 	    }
                   12473: 	}
                   12474: 	if ($entries[0]=~/^\#/) {
                   12475: 	    my $id=$entries[0];
                   12476: 	    my @idresponses;
                   12477: 	    $id=~s/^[\#0]+//;
                   12478: 	    for (my $i=0;$i<$number;$i++) {
                   12479: 		my $idx=3+$i*6;
1.644     www      12480:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 12481: 		push(@idresponses,$entries[$idx]);
                   12482: 	    }
                   12483: 	    $$responses{$id}=join(',',@idresponses);
                   12484: 	}
1.405     www      12485:     }
                   12486:     return ($errormsg,$number);
                   12487: }
                   12488: 
1.760     raeburn  12489: sub iclickerxml_eval {
                   12490:     my ($questiontitles,$responses)=@_;
                   12491:     my $number=0;
                   12492:     my $errormsg='';
                   12493:     my @state;
                   12494:     my %respbyid;
                   12495:     my $p = HTML::Parser->new
                   12496:     (
                   12497:         xml_mode => 1,
                   12498:         start_h =>
                   12499:             [sub {
                   12500:                  my ($tagname,$attr) = @_;
                   12501:                  push(@state,$tagname);
                   12502:                  if ("@state" eq "ssn p") {
                   12503:                      my $title = $attr->{qn};
                   12504:                      $title =~ s/(^\s+|\s+$)//g;
                   12505:                      $questiontitles->[$number]=$title;
                   12506:                  } elsif ("@state" eq "ssn p v") {
                   12507:                      my $id = $attr->{id};
                   12508:                      my $entry = $attr->{ans};
                   12509:                      $id=~s/^[\#0]+//;
                   12510:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   12511:                      $respbyid{$id}[$number] = $entry;
                   12512:                  }
                   12513:             }, "tagname, attr"],
                   12514:          end_h =>
                   12515:                [sub {
                   12516:                    my ($tagname) = @_;
                   12517:                    if ("@state" eq "ssn p") {
                   12518:                        $number++;
                   12519:                    }
                   12520:                    pop(@state);
                   12521:                 }, "tagname"],
                   12522:     );
                   12523: 
                   12524:     $p->parse($env{'form.upfile'});
                   12525:     $p->eof;
                   12526:     foreach my $id (keys(%respbyid)) {
                   12527:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   12528:     }
                   12529:     return ($errormsg,$number);
                   12530: }
                   12531: 
1.419     www      12532: sub interwrite_eval {
                   12533:     my ($questiontitles,$responses)=@_;
                   12534:     my $number=0;
                   12535:     my $errormsg='';
1.420     www      12536:     my $skipline=1;
                   12537:     my $questionnumber=0;
                   12538:     my %idresponses=();
1.419     www      12539:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12540:         my %components=&Apache::loncommon::record_sep($line);
                   12541:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      12542:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   12543:         if ($entries[1] eq 'Response') { $skipline=1; }
                   12544:         next if $skipline;
                   12545:         if ($entries[0]!=$questionnumber) {
                   12546:            $questionnumber=$entries[0];
                   12547:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   12548:            $number++;
1.419     www      12549:         }
1.420     www      12550:         my $id=$entries[4];
                   12551:         $id=~s/^[\#0]+//;
1.421     www      12552:         $id=~s/^v\d*\://i;
                   12553:         $id=~s/[\-\:]//g;
1.420     www      12554:         $idresponses{$id}[$number]=$entries[6];
                   12555:     }
1.524     raeburn  12556:     foreach my $id (keys(%idresponses)) {
1.420     www      12557:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   12558:        $$responses{$id}=~s/^\s*\,//;
1.419     www      12559:     }
                   12560:     return ($errormsg,$number);
                   12561: }
                   12562: 
1.666     www      12563: sub turning_eval {
                   12564:     my ($questiontitles,$responses)=@_;
                   12565:     my $number=0;
                   12566:     my $errormsg='';
                   12567:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12568:         my %components=&Apache::loncommon::record_sep($line);
                   12569:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   12570:         if ($#entries>$number) { $number=$#entries; }
                   12571:         my $id=$entries[0];
                   12572:         my @idresponses;
                   12573:         $id=~s/^[\#0]+//;
                   12574:         unless ($id) { next; }
                   12575:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   12576:             $entries[$idx]=~s/\,/\;/g;
                   12577:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   12578:             push(@idresponses,$entries[$idx]);
                   12579:         }
                   12580:         $$responses{$id}=join(',',@idresponses);
                   12581:     }
                   12582:     for (my $i=1; $i<=$number; $i++) {
                   12583:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   12584:     }
                   12585:     return ($errormsg,$number);
                   12586: }
                   12587: 
                   12588: 
1.414     www      12589: sub assign_clicker_grades {
1.766     raeburn  12590:     my ($r,$symb) = @_;
1.414     www      12591:     if (!$symb) {return '';}
1.416     www      12592: # See which part we are saving to
1.582     raeburn  12593:     my $res_error;
                   12594:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   12595:     if ($res_error) {
                   12596:         return &navmap_errormsg();
                   12597:     }
1.804     raeburn  12598:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12599:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12600:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   12601:     my (%skip_passback,%pbsave); 
1.416     www      12602: # FIXME: This should probably look for the first handgradeable part
                   12603:     my $part=$$partlist[0];
                   12604: # Start screen output
1.766     raeburn  12605:     my $result = &Apache::loncommon::start_data_table().
                   12606:                  &Apache::loncommon::start_data_table_header_row().
                   12607:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   12608:                  &Apache::loncommon::end_data_table_header_row().
                   12609:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      12610: # Get correct result
                   12611: # FIXME: Possibly need delimiter other than ":"
                   12612:     my @correct=();
1.415     www      12613:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   12614:     my $number=$env{'form.number'};
                   12615:     if ($gradingmechanism ne 'attendance') {
1.414     www      12616:        foreach my $key (keys(%env)) {
                   12617:           if ($key=~/^form\.correct\:/) {
                   12618:              my @input=split(/\,/,$env{$key});
                   12619:              for (my $i=0;$i<=$#input;$i++) {
                   12620:                  if (($correct[$i]) && ($input[$i]) &&
                   12621:                      ($correct[$i] ne $input[$i])) {
                   12622:                     $result.='<br /><span class="LC_warning">'.
                   12623:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   12624:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      12625:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      12626:                     $correct[$i]=$input[$i];
                   12627:                  }
                   12628:              }
                   12629:           }
                   12630:        }
1.415     www      12631:        for (my $i=0;$i<$number;$i++) {
1.644     www      12632:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      12633:              $result.='<br /><span class="LC_error">'.
                   12634:                       &mt('No correct result given for question "[_1]"!',
                   12635:                           $env{'form.question:'.$i}).'</span>';
                   12636:           }
                   12637:        }
1.644     www      12638:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      12639:     }
                   12640: # Start grading
1.415     www      12641:     my $pcorrect=$env{'form.pcorrect'};
                   12642:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      12643:     my $storecount=0;
1.632     www      12644:     my %users=();
1.415     www      12645:     foreach my $key (keys(%env)) {
1.420     www      12646:        my $user='';
1.415     www      12647:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      12648:           $user=$1;
                   12649:        }
                   12650:        if ($key=~/^form\.unknown\:(.*)$/) {
                   12651:           my $id=$1;
                   12652:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   12653:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      12654:           } elsif ($env{'form.multi'.$id}) {
                   12655:              $user=$env{'form.multi'.$id};
1.420     www      12656:           }
                   12657:        }
1.632     www      12658:        if ($user) {
                   12659:           if ($users{$user}) {
                   12660:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   12661:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      12662:                       '</span><br />';
                   12663:           }
                   12664:           $users{$user}=1; 
1.415     www      12665:           my @answer=split(/\,/,$env{$key});
                   12666:           my $sum=0;
1.522     www      12667:           my $realnumber=$number;
1.415     www      12668:           for (my $i=0;$i<$number;$i++) {
1.576     www      12669:              if  ($correct[$i] eq '-') {
                   12670:                 $realnumber--;
1.766     raeburn  12671:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      12672:                 if ($gradingmechanism eq 'attendance') {
                   12673:                    $sum+=$pcorrect;
1.576     www      12674:                 } elsif ($correct[$i] eq '*') {
1.522     www      12675:                    $sum+=$pcorrect;
1.415     www      12676:                 } else {
1.644     www      12677: # We actually grade if correct or not
                   12678:                    my $increment=$pincorrect;
                   12679: # Special case: numerical answer "0"
                   12680:                    if ($correct[$i] eq '0') {
                   12681:                       if ($answer[$i]=~/^[0\.]+$/) {
                   12682:                          $increment=$pcorrect;
                   12683:                       }
                   12684: # General numerical answer, both evaluate to something non-zero
                   12685:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   12686:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   12687:                          $increment=$pcorrect;
                   12688:                       }
                   12689: # Must be just alphanumeric
                   12690:                    } elsif ($answer[$i] eq $correct[$i]) {
                   12691:                       $increment=$pcorrect;
1.415     www      12692:                    }
1.644     www      12693:                    $sum+=$increment;
1.415     www      12694:                 }
                   12695:              }
                   12696:           }
1.522     www      12697:           my $ave=$sum/(100*$realnumber);
1.416     www      12698: # Store
                   12699:           my ($username,$domain)=split(/\:/,$user);
                   12700:           my %grades=();
                   12701:           $grades{"resource.$part.solved"}='correct_by_override';
                   12702:           $grades{"resource.$part.awarded"}=$ave;
                   12703:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   12704:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   12705:                                                  $env{'request.course.id'},
                   12706:                                                  $domain,$username);
                   12707:           if ($returncode ne 'ok') {
                   12708:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   12709:           } else {
                   12710:              $storecount++;
1.804     raeburn  12711:              if (keys(%needpb)) {
                   12712:                  my (%weights,%awardeds,%excuseds);
                   12713:                  my $usec = &Apache::lonnet::getsection($domain,$username,$env{'request.course.id'});
                   12714:                  $weights{$symb}{$part} = &Apache::lonnet::EXT("resource.$part.weight",$symb,$domain,$username,$usec);
                   12715:                  $awardeds{$symb}{$part} = $ave;
                   12716:                  $excuseds{$symb}{$part} = '';
                   12717:                  &process_passbacks('clickergrade',[$symb],$cdom,$cnum,$domain,$username,$usec,\%weights,
                   12718:                                     \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   12719:              }
1.416     www      12720:           }
1.415     www      12721:        }
                   12722:     }
                   12723: # We are done
1.549     hauer    12724:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      12725:              '</td>'.
                   12726:              &Apache::loncommon::end_data_table_row().
                   12727:              &Apache::loncommon::end_data_table();
1.614     www      12728:     return $result;
1.414     www      12729: }
                   12730: 
1.582     raeburn  12731: sub navmap_errormsg {
                   12732:     return '<div class="LC_error">'.
                   12733:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  12734:            &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  12735:            '</div>';
                   12736: }
1.607     droeschl 12737: 
1.609     www      12738: sub startpage {
1.777     raeburn  12739:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  12740:     my %args;
                   12741:     if ($onload) {
                   12742:          my %loaditems = (
                   12743:                         'onload' => $onload,
                   12744:                       );
                   12745:          $args{'add_entries'} = \%loaditems;
                   12746:     }
1.671     raeburn  12747:     if ($nomenu) {
1.754     raeburn  12748:         $args{'only_body'} = 1; 
1.777     raeburn  12749:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  12750:     } else {
1.785     raeburn  12751:         if ($env{'request.course.id'}) { 
                   12752:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   12753:         }
1.754     raeburn  12754:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  12755:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  12756:         if ($env{'request.course.id'}) {
                   12757:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   12758:         }
1.671     raeburn  12759:     }
1.613     www      12760:     unless ($nodisplayflag) {
1.773     raeburn  12761:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      12762:     }
1.607     droeschl 12763: }
1.582     raeburn  12764: 
1.622     www      12765: sub select_problem {
                   12766:     my ($r)=@_;
1.632     www      12767:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  12768:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      12769:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   12770:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   12771: }
                   12772: 
1.793     raeburn  12773: #----- display problem, answer, and submissions for a single student (no grading)
                   12774: 
                   12775: sub view_as_user {
                   12776:     my ($symb,$vuname,$vudom,$hasperm) = @_;
                   12777:     my $plainname = &Apache::loncommon::plainname($vuname,$vudom,'lastname');
                   12778:     my $displayname = &nameUserString('',$plainname,$vuname,$vudom);
                   12779:     my $output = &Apache::loncommon::get_student_view($symb,$vuname,$vudom,
                   12780:                                                       $env{'request.course.id'},
                   12781:                                                       undef,{'disable_submit' => 1}).
                   12782:                  "\n\n".
                   12783:                  '<div class="LC_grade_show_user">'.
                   12784:                  '<h2>'.$displayname.'</h2>'.
                   12785:                  "\n".
                   12786:                  &Apache::loncommon::track_student_link('View recent activity',
                   12787:                                                         $vuname,$vudom,'check').' '.
                   12788:                  "\n";
                   12789:     if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) ||
                   12790:         (($env{'request.course.sec'} ne '') &&
                   12791:          &Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
                   12792:         $output .= &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   12793:                                                $vuname,$vudom,$symb,'check');
                   12794:     }
                   12795:     $output .= "\n";
                   12796:     my $companswer = &Apache::loncommon::get_student_answers($symb,$vuname,$vudom,
                   12797:                                                              $env{'request.course.id'});
                   12798:     $companswer=~s|<form(.*?)>||g;
                   12799:     $companswer=~s|</form>||g;
                   12800:     $companswer=~s|name="submit"|name="would_have_been_submit"|g;
                   12801:     $output .= '<div class="LC_Box">'.
                   12802:                '<h3 class="LC_hcell">'.&mt('Correct answer for[_1]',$displayname).'</h3>'.
                   12803:                $companswer.
                   12804:                '</div>'."\n";
                   12805:     my $is_tool = ($symb =~ /ext\.tool$/);
                   12806:     my ($essayurl,%coursedesc_by_cid);
                   12807:     (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   12808:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$vudom,$vuname);
                   12809:     my $res_error;
                   12810:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   12811:         &response_type($symb,\$res_error);
                   12812:     my $fullname;
                   12813:     my $collabinfo;
                   12814:     if ($numessay) {
                   12815:         unless ($hasperm) {
                   12816:             &init_perm();
                   12817:         }
                   12818:         ($collabinfo,$fullname)=
                   12819:             &check_collaborators($symb,$vuname,$vudom,\%record,$handgrade,0);
                   12820:         unless ($hasperm) {
                   12821:             &reset_perm();
                   12822:         }
                   12823:     }
                   12824:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   12825:                     '" src="'.$Apache::lonnet::perlvar{'lonIconsURL'}.
                   12826:                     '/check.gif" height="16" border="0" />';
                   12827:     my ($lastsubonly,$partinfo) =
                   12828:         &show_last_submission($vuname,$vudom,$symb,$essayurl,$responseType,'datesub',
                   12829:                               '',$fullname,\%record,\%coursedesc_by_cid);
                   12830:     $output .= '<div class="LC_Box">'.
                   12831:                '<h3 class="LC_hcell">'.&mt('Submissions').'</h3>'."\n".$collabinfo."\n";
                   12832:     if (($numresp > $numessay) & !$is_tool) {
                   12833:         $output .='<p class="LC_info">'.
                   12834:                   &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon).
                   12835:                   "</p>\n";
                   12836:     }
                   12837:     $output .= $partinfo;
                   12838:     $output .= $lastsubonly;
                   12839:     $output .= &displaySubByDates($symb,\%record,$partlist,$responseType,$checkIcon,$vuname,$vudom);
                   12840:     $output .= '</div></div>'."\n";
                   12841:     return $output;
                   12842: }
                   12843: 
1.1       albertel 12844: sub handler {
1.41      ng       12845:     my $request=$_[0];
1.434     albertel 12846:     &reset_caches();
1.646     raeburn  12847:     if ($request->header_only) {
                   12848:         &Apache::loncommon::content_type($request,'text/html');
                   12849:         $request->send_http_header;
                   12850:         return OK;
                   12851:     }
                   12852:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   12853: 
1.664     raeburn  12854: # see what command we need to execute
                   12855: 
                   12856:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   12857:     my $command=$commands[0];
                   12858: 
1.646     raeburn  12859:     &init_perm();
                   12860:     if (!$env{'request.course.id'}) {
1.664     raeburn  12861:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   12862:                 ($command =~ /^scantronupload/)) {
                   12863:             # Not in a course.
                   12864:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   12865:             return HTTP_NOT_ACCEPTABLE;
                   12866:         }
1.646     raeburn  12867:     } elsif (!%perm) {
                   12868:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  12869:         return OK;
1.41      ng       12870:     }
1.646     raeburn  12871:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       12872:     $request->send_http_header;
1.646     raeburn  12873: 
1.160     albertel 12874:     if ($#commands > 0) {
                   12875: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   12876:     }
1.608     www      12877: 
1.801     raeburn  12878: # -------------------------------------- Flag and buffer for registered cleanup
                   12879:     $registered_cleanup=0;
                   12880:     undef(@Apache::grades::ltipassback);
                   12881: 
1.608     www      12882: # see what the symb is
                   12883: 
                   12884:     my $symb=$env{'form.symb'};
                   12885:     unless ($symb) {
                   12886:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   12887:        $symb=&Apache::lonnet::symbread($url);
                   12888:     }
1.646     raeburn  12889:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      12890: 
1.513     foxr     12891:     $ssi_error = 0;
1.637     www      12892:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      12893: #
1.637     www      12894: # Not called from a resource, but inside a course
1.601     www      12895: #    
1.622     www      12896:         &startpage($request,undef,[],1,1);
                   12897:         &select_problem($request);
1.41      ng       12898:     } else {
1.104     albertel 12899: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  12900:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  12901:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   12902:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12903:                     &choose_task_version_form($symb,$env{'form.student'},
                   12904:                                               $env{'form.userdom'});
                   12905:             }
1.773     raeburn  12906:             my $divforres;
                   12907:             if ($env{'form.student'} eq '') {
                   12908:                 $js .= &part_selector_js();
                   12909:                 $onload = "toggleParts('gradesub');";
                   12910:             } else {
                   12911:                 $divforres = 1;
                   12912:             }
1.778     raeburn  12913:             my $head_extra = $js;
                   12914:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12915:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12916:                 if ($csslinks) {
                   12917:                     $head_extra .= "\n$csslinks";
                   12918:                 }
                   12919:             }
1.777     raeburn  12920:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   12921:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  12922:             if ($versionform) {
1.775     raeburn  12923:                 if ($divforres) {
                   12924:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   12925:                 }
1.671     raeburn  12926:                 $request->print($versionform);
                   12927:             }
1.773     raeburn  12928: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  12929:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   12930:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12931:                 &choose_task_version_form($symb,$env{'form.student'},
                   12932:                                           $env{'form.userdom'},
                   12933:                                           $env{'form.inhibitmenu'});
1.778     raeburn  12934:             my $head_extra = $js;
                   12935:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12936:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12937:                 if ($csslinks) {
                   12938:                     $head_extra .= "\n$csslinks";
                   12939:                 }
                   12940:             }
1.777     raeburn  12941:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   12942:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  12943:             if ($versionform) {
                   12944:                 $request->print($versionform);
                   12945:             }
                   12946:             $request->print('<br clear="all" />');
                   12947:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 12948: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      12949:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12950:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      12951: 	    &pickStudentPage($request,$symb);
1.103     albertel 12952: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  12953:             my $csslinks;
                   12954:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12955:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  12956:             }
1.615     www      12957:             &startpage($request,$symb,
                   12958:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12959:                                        {href=>'',text=>'Select student'},
1.777     raeburn  12960:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      12961: 	    &displayPage($request,$symb);
1.104     albertel 12962: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      12963:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12964:                                        {href=>'',text=>'Select student'},
                   12965:                                        {href=>'',text=>'Grade student'},
                   12966:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      12967: 	    &updateGradeByPage($request,$symb);
1.104     albertel 12968: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  12969:             my $csslinks;
                   12970:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12971:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12972:             }
1.619     www      12973:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  12974:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      12975: 	    &processGroup($request,$symb);
1.104     albertel 12976: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      12977:             &startpage($request,$symb);
                   12978: 	    $request->print(&grading_menu($request,$symb));
1.598     www      12979: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      12980:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      12981: 	    $request->print(&submit_options($request,$symb));
1.598     www      12982:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  12983:             my $js = &part_selector_js();
                   12984:             my $onload = "toggleParts('gradesub');";
                   12985:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   12986:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      12987:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      12988:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      12989:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      12990:             $request->print(&submit_options_table($request,$symb));
1.598     www      12991:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      12992:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      12993:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 12994: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      12995:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      12996: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 12997: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      12998:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   12999:                                        {href=>'',text=>'Store grades'}]);
1.608     www      13000: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 13001: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      13002:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   13003:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   13004:                                                                              text=>"Modify grades"},
                   13005:                                        {href=>'', text=>"Store grades"}]);
1.608     www      13006: 	    $request->print(&editgrades($request,$symb));
1.602     www      13007:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      13008:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      13009:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 13010: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      13011:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   13012:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      13013: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      13014:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      13015:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      13016:             $request->print(&process_clicker($request,$symb));
1.400     www      13017:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      13018:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   13019:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      13020:             $request->print(&process_clicker_file($request,$symb));
1.414     www      13021:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      13022:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   13023:                                        {href=>'', text=>'Process clicker file'},
                   13024:                                        {href=>'', text=>'Store grades'}]);
1.608     www      13025:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 13026: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      13027:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13028: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 13029: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      13030:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13031: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 13032: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      13033:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13034: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 13035: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 13036: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      13037:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13038: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       13039: 	    } else {
1.257     albertel 13040: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   13041: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       13042: 		} else {
1.257     albertel 13043: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       13044: 		}
1.627     www      13045:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13046: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       13047: 	    }
1.246     albertel 13048: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      13049:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13050: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 13051: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  13052:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   13053:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      13054: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 13055:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      13056:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13057:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 13058: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      13059:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13060: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 13061: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      13062:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13063: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 13064:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  13065:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  13066:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   13067:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      13068:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 13069:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  13070:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      13071:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13072:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  13073:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      13074:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13075:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  13076:         } elsif ($command eq 'scantronupload_delete' &&
                   13077:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   13078:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   13079:             &scantron_upload_delete($request,$symb);
1.523     raeburn  13080:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      13081:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      13082:             $request->print(&checkscantron_results($request,$symb));
                   13083:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  13084:             my $js = &part_selector_js();
                   13085:             my $onload = "toggleParts('gradingMenu');";
                   13086:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   13087:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      13088:             $request->print(&submit_options_download($request,$symb));
                   13089:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   13090:             &startpage($request,$symb,
                   13091:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  13092:     {href=>'', text=>'Download submitted files'}],
                   13093:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  13094:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      13095:             &submit_download_link($request,$symb);
1.796     raeburn  13096:         } elsif ($command eq 'initialpassback') {
                   13097:             &startpage($request,$symb,[{href=>'', text=>'Choose Launcher'}],undef,1);
                   13098:             $request->print(&initialpassback($request,$symb));
                   13099:         } elsif ($command eq 'passback') {
                   13100:             &startpage($request,$symb,
                   13101:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13102:                         {href=>'', text=>'Types of User'}],undef,1);
                   13103:             $request->print(&passback_filters($request,$symb));
                   13104:         } elsif ($command eq 'passbacknames') {
                   13105:             my $chosen;
                   13106:             if ($env{'form.passback'} ne '') {
                   13107:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13108:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13109:                 }
                   13110:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13111:             }
                   13112:             &startpage($request,$symb,
                   13113:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13114:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13115:                         {href=>'', text=>'Select Users'}],undef,1);
                   13116:             $request->print(&names_for_passback($request,$symb));
                   13117:         } elsif ($command eq 'passbackscores') {
                   13118:             my ($chosen,$stu_status);
                   13119:             if ($env{'form.passback'} ne '') {
                   13120:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13121:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13122:                 }
                   13123:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13124:             }
                   13125:             if ($env{'form.Status'}) {
                   13126:                 $stu_status = &HTML::Entities::encode($env{'form.Status'});
                   13127:             }
                   13128:             &startpage($request,$symb,
                   13129:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13130:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13131:                         {href=>&href_symb_cmd($symb,'passbacknames').'&amp;Status='.$stu_status.'&amp;passback='.$chosen, text=>'Select Users'},
                   13132:                         {href=>'', text=>'Execute Passback'}],undef,1);
                   13133:             $request->print(&do_passback($request,$symb));
1.106     albertel 13134: 	} elsif ($command) {
1.620     www      13135:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   13136: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 13137: 	}
1.2       albertel 13138:     }
1.513     foxr     13139:     if ($ssi_error) {
                   13140: 	&ssi_print_error($request);
                   13141:     }
1.671     raeburn  13142:     if ($env{'form.inhibitmenu'}) {
                   13143:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  13144:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  13145:         &Apache::lonquickgrades::endGradeScreen($request);
                   13146:     }
1.434     albertel 13147:     &reset_caches();
1.646     raeburn  13148:     return OK;
1.44      ng       13149: }
                   13150: 
1.1       albertel 13151: 1;
                   13152: 
1.13      albertel 13153: __END__;
1.531     jms      13154: 
                   13155: 
                   13156: =head1 NAME
                   13157: 
                   13158: Apache::grades
                   13159: 
                   13160: =head1 SYNOPSIS
                   13161: 
                   13162: Handles the viewing of grades.
                   13163: 
                   13164: This is part of the LearningOnline Network with CAPA project
                   13165: described at http://www.lon-capa.org.
                   13166: 
                   13167: =head1 OVERVIEW
                   13168: 
                   13169: Do an ssi with retries:
1.715     bisitz   13170: While I'd love to factor out this with the version in lonprintout,
1.531     jms      13171: 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
                   13172: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   13173: 
                   13174: At least the logic that drives this has been pulled out into loncommon.
                   13175: 
                   13176: 
                   13177: 
                   13178: ssi_with_retries - Does the server side include of a resource.
                   13179:                      if the ssi call returns an error we'll retry it up to
                   13180:                      the number of times requested by the caller.
1.715     bisitz   13181:                      If we still have a problem, no text is appended to the
1.531     jms      13182:                      output and we set some global variables.
                   13183:                      to indicate to the caller an SSI error occurred.  
                   13184:                      All of this is supposed to deal with the issues described
1.715     bisitz   13185:                      in LON-CAPA BZ 5631 see:
1.531     jms      13186:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   13187:                      by informing the user that this happened.
                   13188: 
                   13189: Parameters:
                   13190:   resource   - The resource to include.  This is passed directly, without
                   13191:                interpretation to lonnet::ssi.
                   13192:   form       - The form hash parameters that guide the interpretation of the resource
                   13193:                
                   13194:   retries    - Number of retries allowed before giving up completely.
                   13195: Returns:
                   13196:   On success, returns the rendered resource identified by the resource parameter.
                   13197: Side Effects:
                   13198:   The following global variables can be set:
                   13199:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   13200:                               It is up to the caller to initialize this to false
                   13201:                               if desired.
                   13202:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   13203:                               of the resource that could not be rendered by the ssi
                   13204:                               call.
                   13205:    ssi_error_message   - The error string fetched from the ssi response
                   13206:                               in the event of an error.
                   13207: 
                   13208: 
                   13209: =head1 HANDLER SUBROUTINE
                   13210: 
                   13211: ssi_with_retries()
                   13212: 
                   13213: =head1 SUBROUTINES
                   13214: 
                   13215: =over
                   13216: 
1.671     raeburn  13217: =head1 Routines to display previous version of a Task for a specific student
                   13218: 
                   13219: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   13220: can receive another opportunity. Access to tasks is slot-based. If a slot
                   13221: requires a proctor to check-in the student, a new version of the Task will
                   13222: be created when the student is checked in to the new opportunity.
                   13223: 
                   13224: If a particular student has tried two or more versions of a particular task,
                   13225: the submission screen provides a user with vgr privileges (e.g., a Course
                   13226: Coordinator) the ability to display a previous version worked on by the
                   13227: student.  By default, the current version is displayed. If a previous version
                   13228: has been selected for display, submission data are only shown that pertain
                   13229: to that particular version, and the interface to submit grades is not shown.
                   13230: 
                   13231: =over 4
                   13232: 
                   13233: =item show_previous_task_version()
                   13234: 
                   13235: Displays a specified version of a student's Task, as the student sees it.
                   13236: 
                   13237: Inputs: 2
                   13238:         request - request object
                   13239:         symb    - unique symb for current instance of resource
                   13240: 
                   13241: Output: None.
                   13242: 
                   13243: Side Effects: calls &show_problem() to print version of Task, with
                   13244:               version contained in form item: $env{'form.previousversion'}
                   13245: 
                   13246: =item choose_task_version_form()
                   13247: 
                   13248: Displays a web form used to select which version of a student's view of a
                   13249: Task should be displayed.  Either launches a pop-up window, or replaces
                   13250: content in existing pop-up, or replaces page in main window.
                   13251: 
                   13252: Inputs: 4
                   13253:         symb    - unique symb for current instance of resource
                   13254:         uname   - username of student
                   13255:         udom    - domain of student
                   13256:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13257:                   breadcrumbs etc., are displayed
                   13258: 
                   13259: Output: 4
                   13260:         current   - student's current version
                   13261:         displayed - student's version being displayed
                   13262:         result    - scalar containing HTML for web form used to switch to
                   13263:                     a different version (or a link to close window, if pop-up).
                   13264:         js        - javascript for processing selection in versions web form
                   13265: 
                   13266: Side Effects: None.
                   13267: 
                   13268: =item previous_display_javascript()
                   13269: 
                   13270: Inputs: 2
                   13271:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13272:                   breadcrumbs etc., are displayed.
                   13273:         current - student's current version number.
                   13274: 
                   13275: Output: 1
                   13276:         js      - javascript for processing selection in versions web form.
                   13277: 
                   13278: Side Effects: None.
                   13279: 
                   13280: =back
                   13281: 
                   13282: =head1 Routines to process bubblesheet data.
                   13283: 
                   13284: =over 4
                   13285: 
1.531     jms      13286: =item scantron_get_correction() : 
                   13287: 
                   13288:    Builds the interface screen to interact with the operator to fix a
                   13289:    specific error condition in a specific scanline
                   13290: 
                   13291:  Arguments:
                   13292:     $r           - Apache request object
                   13293:     $i           - number of the current scanline
                   13294:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  13295:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      13296:     $line        - full contents of the current scanline
                   13297:     $error       - error condition, valid values are
                   13298:                    'incorrectCODE', 'duplicateCODE',
                   13299:                    'doublebubble', 'missingbubble',
                   13300:                    'duplicateID', 'incorrectID'
                   13301:     $arg         - extra information needed
                   13302:        For errors:
                   13303:          - duplicateID   - paper number that this studentID was seen before on
                   13304:          - duplicateCODE - array ref of the paper numbers this CODE was
                   13305:                            seen on before
                   13306:          - incorrectCODE - current incorrect CODE 
                   13307:          - doublebubble  - array ref of the bubble lines that have double
                   13308:                            bubble errors
                   13309:          - missingbubble - array ref of the bubble lines that have missing
                   13310:                            bubble errors
                   13311: 
1.788     raeburn  13312:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   13313:    $randompick  - True if exam folder (or a sub-folder) has randompick set
1.691     raeburn  13314:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   13315:                      for current line to question number used for same question
                   13316:                      in "Master Seqence" (as seen by Course Coordinator).
                   13317:    $startline   - Reference to hash where key is question number (0 is first)
                   13318:                   and value is number of first bubble line for current student
                   13319:                   or code-based randompick and/or randomorder.
                   13320: 
                   13321: 
                   13322: 
1.531     jms      13323: =item  scantron_get_maxbubble() : 
                   13324: 
1.582     raeburn  13325:    Arguments:
                   13326:        $nav_error  - Reference to scalar which is a flag to indicate a
                   13327:                       failure to retrieve a navmap object.
                   13328:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   13329:        calling routine should trap the error condition and display the warning
                   13330:        found in &navmap_errormsg().
                   13331: 
1.649     raeburn  13332:        $scantron_config - Reference to bubblesheet format configuration hash.
                   13333: 
1.531     jms      13334:    Returns the maximum number of bubble lines that are expected to
                   13335:    occur. Does this by walking the selected sequence rendering the
                   13336:    resource and then checking &Apache::lonxml::get_problem_counter()
                   13337:    for what the current value of the problem counter is.
                   13338: 
                   13339:    Caches the results to $env{'form.scantron_maxbubble'},
                   13340:    $env{'form.scantron.bubble_lines.n'}, 
                   13341:    $env{'form.scantron.first_bubble_line.n'} and
                   13342:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  13343:    which are the total number of bubble lines, the number of bubble
1.531     jms      13344:    lines for response n and number of the first bubble line for response n,
                   13345:    and a comma separated list of numbers of bubble lines for sub-questions
                   13346:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   13347: 
                   13348: 
                   13349: =item  scantron_validate_missingbubbles() : 
                   13350: 
                   13351:    Validates all scanlines in the selected file to not have any
                   13352:     answers that don't have bubbles that have not been verified
                   13353:     to be bubble free.
                   13354: 
                   13355: =item  scantron_process_students() : 
                   13356: 
1.659     raeburn  13357:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      13358: 
                   13359:    The parsed scanline hash is added to %env 
                   13360: 
                   13361:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   13362:    foreach resource , with the form data of
                   13363: 
                   13364: 	'submitted'     =>'scantron' 
                   13365: 	'grade_target'  =>'grade',
                   13366: 	'grade_username'=> username of student
                   13367: 	'grade_domain'  => domain of student
                   13368: 	'grade_courseid'=> of course
                   13369: 	'grade_symb'    => symb of resource to grade
                   13370: 
                   13371:     This triggers a grading pass. The problem grading code takes care
                   13372:     of converting the bubbled letter information (now in %env) into a
                   13373:     valid submission.
                   13374: 
                   13375: =item  scantron_upload_scantron_data() :
                   13376: 
1.659     raeburn  13377:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      13378: 
                   13379: =item  scantron_upload_scantron_data_save() : 
                   13380: 
                   13381:    Adds a provided bubble information data file to the course if user
1.770     raeburn  13382:    has the correct privileges to do so.
                   13383: 
                   13384: = item scantron_upload_delete() :
                   13385: 
                   13386:    Deletes a previously uploaded bubble information data file, if user
                   13387:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      13388: 
                   13389: =item  valid_file() :
                   13390: 
                   13391:    Validates that the requested bubble data file exists in the course.
                   13392: 
                   13393: =item  scantron_download_scantron_data() : 
                   13394: 
                   13395:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  13396:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      13397:    course.
                   13398: 
                   13399: =item  scantron_validate_ID() : 
                   13400: 
                   13401:    Validates all scanlines in the selected file to not have any
1.556     weissno  13402:    invalid or underspecified student/employee IDs
1.531     jms      13403: 
1.582     raeburn  13404: =item navmap_errormsg() :
                   13405: 
                   13406:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  13407:    Should be called whenever the request to instantiate a navmap object fails.
                   13408: 
                   13409: =back
1.582     raeburn  13410: 
1.531     jms      13411: =back
                   13412: 
                   13413: =cut

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