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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.806   ! raeburn     4: # $Id: grades.pm,v 1.805 2024/12/13 05:04:49 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();
1.806   ! raeburn  1266:     my ($launchsymb,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
1.796     raeburn  1267:     if ($env{'form.passback'} ne '') {
                   1268:         $chosen = &unescape($env{'form.passback'});
                   1269:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
1.806   ! raeburn  1270:         ($launchsymb,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
1.796     raeburn  1271:     }
1.806   ! raeburn  1272:     if ($launchsymb ne '') {
        !          1273:         $request->print(&launcher_info_box($launchsymb,$appname,$setter,$linkuri,$scope));
1.796     raeburn  1274:     }
                   1275:     my $error;
                   1276:     if ($perm{'mgr'}) {
1.806   ! raeburn  1277:         if ($launchsymb ne '') {
1.796     raeburn  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 $pbmap;
1.806   ! raeburn  1316:                             if ($launchsymb =~ /\.(page|sequence)$/) {
        !          1317:                                 $pbmap = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($launchsymb))[2]);
1.796     raeburn  1318:                             } else {
1.806   ! raeburn  1319:                                 $pbmap = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($launchsymb))[0]);
1.796     raeburn  1320:                             }
                   1321:                             $pbmap = &Apache::lonnet::clutter($pbmap);
                   1322:                             my $pbscope;
                   1323:                             if ($scope eq 'res') {
                   1324:                                 $pbscope = 'resource';
                   1325:                             } elsif ($scope eq 'map') {
                   1326:                                 $pbscope = 'nonrec';
                   1327:                             } elsif ($scope eq 'rec') {
                   1328:                                 $pbscope = 'map';
                   1329:                             }
1.798     raeburn  1330:                             my %pb = &common_passback_info();
1.796     raeburn  1331:                             my $numstudents = scalar(keys(%tosend));
                   1332:                             my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($request,$numstudents);
                   1333:                             my $outcome = &Apache::loncommon::start_data_table().
1.806   ! raeburn  1334:                                           &Apache::loncommon::start_data_table_header_row();
1.796     raeburn  1335:                             my $loop = 0;
                   1336:                             while ($loop < 2) {
                   1337:                                 $outcome .= '<th>'.&mt('No.').'</th>'.
1.806   ! raeburn  1338:                                             '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>'.
        !          1339:                                             '<th>'.&mt('Score').'</th>';
        !          1340:                                 $loop++;
1.796     raeburn  1341:                             }
                   1342:                             $outcome .= &Apache::loncommon::end_data_table_header_row()."\n";
                   1343:                             my $ctr=0;
                   1344:                             foreach my $student (sort
                   1345:                                 {
                   1346:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1347:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1348:                                      }
                   1349:                                      return $a cmp $b;
                   1350:                                 } (keys(%$fullname))) {
                   1351:                                 next unless ($tosend{$student});
                   1352:                                 my ($uname,$udom) = split(/:/,$student);
                   1353:                                 &Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last student');
                   1354:                                 my ($uname,$udom) = split(/:/,$student);
                   1355:                                 my $uhome = &Apache::lonnet::homeserver($uname,$udom),
                   1356:                                 my $id = $passback{$student}[0],
                   1357:                                 my $url = $passback{$student}[1],
                   1358:                                 my ($total,$possible,$usec);
                   1359:                                 if (ref($classlist->{$student}) eq 'ARRAY') {
                   1360:                                     $usec = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION];
                   1361:                                 }
                   1362:                                 if ($pbscope eq 'resource') {
                   1363:                                     $total = 0;
                   1364:                                     $possible = 0;
                   1365:                                     my $navmap = Apache::lonnavmaps::navmap->new($uname,$udom);
                   1366:                                     if (ref($navmap)) {
1.806   ! raeburn  1367:                                         my $res = $navmap->getBySymb($launchsymb);
1.796     raeburn  1368:                                         if (ref($res)) {
                   1369:                                             my $partlist = $res->parts();
                   1370:                                             if (ref($partlist) eq 'ARRAY') {
1.806   ! raeburn  1371:                                                 my %record = &Apache::lonnet::restore($launchsymb,$env{'request.course.id'},$udom,$uname);
1.796     raeburn  1372:                                                 foreach my $part (@{$partlist}) {
                   1373:                                                     next if ($record{"resource.$part.solved"} =~/^excused/);
1.806   ! raeburn  1374:                                                     my $weight = &Apache::lonnet::EXT("resource.$part.weight",$launchsymb,$udom,$uname,$usec);
1.796     raeburn  1375:                                                     $possible += $weight;
                   1376:                                                     if (($record{'version'}) && (exists($record{"resource.$part.awarded"}))) {
                   1377:                                                         my $awarded = $record{"resource.$part.awarded"};
                   1378:                                                         if ($awarded) {
                   1379:                                                             $total += $weight * $awarded;
                   1380:                                                         }
                   1381:                                                     }
                   1382:                                                 }
                   1383:                                             }
                   1384:                                         }
                   1385:                                     }
                   1386:                                 } elsif (($pbscope eq 'map') || ($pbscope eq 'nonrec')) {
                   1387:                                     ($total,$possible) =
1.806   ! raeburn  1388:                                         &Apache::lonhomework::get_lti_score($uname,$udom,$usec,$pbmap,$pbscope);
1.796     raeburn  1389:                                 }
                   1390:                                 if (($id ne '') && ($url ne '') && ($possible)) {
                   1391:                                     my ($sent,$score,$code,$result) =
1.798     raeburn  1392:                                         &LONCAPA::ltiutils::send_grade($cdom,$cnum,$crsdef,$pb{'type'},$ltinum,$keynum,$id,
                   1393:                                                                        $url,$scoretype,$pb{'sigmethod'},$msgformat,$total,$possible);
1.796     raeburn  1394:                                     my $no_passback;
                   1395:                                     if ($sent) {
                   1396:                                         if ($code == 200) {
                   1397:                                             delete($tosend{$student});
                   1398:                                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
                   1399:                                             my $store = {
                   1400:                                                  'score' => $score,
1.798     raeburn  1401:                                                  'ip' => $pb{'ip'},
                   1402:                                                  'host' => $pb{'lonhost'},
1.796     raeburn  1403:                                                  'protector' => $linkprotector,
                   1404:                                                  'deeplink' => $linkuri,
                   1405:                                                  'scope' => $scope,
                   1406:                                                  'url' => $url,
                   1407:                                                  'id' => $id,
1.798     raeburn  1408:                                                  'clientip' => $pb{'clientip'},
1.796     raeburn  1409:                                                  'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
1.806   ! raeburn  1410:                                             };
1.796     raeburn  1411:                                             my $value='';
                   1412:                                             foreach my $key (keys(%{$store})) {
                   1413:                                                 $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
                   1414:                                             }
                   1415:                                             $value=~s/\&$//;
                   1416:                                             &Apache::lonnet::courselog(&escape($linkuri).':'.$uname.':'.$udom.':EXPORT:'.$value);
1.798     raeburn  1417:                                             &Apache::lonnet::cstore({'score' => $score},$chosen,$namespace,$udom,$uname,'',$pb{'ip'},1);
1.796     raeburn  1418:                                             $ctr++;
                   1419:                                             if ($ctr%2 ==1) {
                   1420:                                                 $outcome .= &Apache::loncommon::start_data_table_row();
                   1421:                                             }
                   1422:                                             my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
                   1423:                                             $outcome .= '<td align="right">'.$ctr.'&nbsp;</td>'.
1.806   ! raeburn  1424:                                                         '<td>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).
        !          1425:                                                         '&nbsp;'.$usec.($group ne '' ?'/'.$group:'').'</td>'.
        !          1426:                                                         '<td>'.$score.'</td>'."\n";
1.796     raeburn  1427:                                             if ($ctr%2 ==0) {
                   1428:                                                 $outcome .= &Apache::loncommon::end_data_table_row()."\n";
                   1429:                                             }
                   1430:                                         } else {
                   1431:                                             $remotenotok{$student} = 1;
                   1432:                                             $no_passback = "Passback response for ".$linkprotector." was $code ($result)";
                   1433:                                             &Apache::lonnet::logthis($no_passback." for $uname:$udom in ${cdom}_${cnum}");
                   1434:                                         }
                   1435:                                     } else {
                   1436:                                         $scorenotok{$student} = 1;
                   1437:                                         $no_passback = "Passback of grades not sent for ".$linkprotector;
                   1438:                                         &Apache::lonnet::logthis($no_passback." for $uname:$udom in ${cdom}_${cnum}");
                   1439:                                     }
                   1440:                                     if ($no_passback) {
                   1441:                                         &Apache::lonnet::log($udom,$uname,$uhome,$no_passback." score: $score; total: $total; possible: $possible");
1.805     raeburn  1442:                                         my $key = &Time::HiRes::time().':'.$uname.':'.$udom.':'.
                   1443:                                                   "$linkuri\0$linkprotector\0$scope"; 
1.796     raeburn  1444:                                         my $ltigrade = {
1.805     raeburn  1445:                                                          $key => {
                   1446:                                                                    'ltinum'   => $ltinum,
                   1447:                                                                    'lti'      => $lti_in_use,
                   1448:                                                                    'crsdef'   => $crsdef,
                   1449:                                                                    'cid'      => $cdom.'_'.$cnum,
                   1450:                                                                    'uname'    => $uname,
                   1451:                                                                    'udom'     => $udom,
                   1452:                                                                    'uhome'    => $uhome,
                   1453:                                                                    'pbid'     => $id,
                   1454:                                                                    'pburl'    => $url,
                   1455:                                                                    'pbtype'   => $pb{'type'},
                   1456:                                                                    'pbscope'  => $pbscope,
                   1457:                                                                    'pbmap'    => $pbmap,
1.806   ! raeburn  1458:                                                                    'pbsymb'   => $launchsymb,
1.805     raeburn  1459:                                                                    'format'   => $scoretype,
                   1460:                                                                    'scope'    => $scope,
                   1461:                                                                    'clientip' => $pb{'clientip'},
                   1462:                                                                    'linkprot' => $linkprotector.':'.$linkuri,
                   1463:                                                                    'total'    => $total,
                   1464:                                                                    'possible' => $possible,
                   1465:                                                                    'score'    => $score,
                   1466:                                                                  },
1.796     raeburn  1467:                                         };
                   1468:                                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1469:                                     }
                   1470:                                 } else {
                   1471:                                     if (($id ne '') && ($url ne '')) {
                   1472:                                         $zeroposs{$student} = 1;
                   1473:                                     } else {
                   1474:                                         $nopbinfo{$student} = 1;
                   1475:                                     }
                   1476:                                 }
                   1477:                             }
                   1478:                             &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
                   1479:                             if ($ctr%2 ==1) {
                   1480:                                 $outcome .= &Apache::loncommon::end_data_table_row();
                   1481:                             }
                   1482:                             $outcome .= &Apache::loncommon::end_data_table();
                   1483:                             if ($ctr) {
                   1484:                                 $request->print('<p><br />'.&mt('Scores sent to launcher CMS').'</p>'.
                   1485:                                                 '<p>'.$outcome.'</p>');
                   1486:                             } else {
                   1487:                                 $request->print('<p>'.&mt('No scores sent to launcher CMS').'</p>');
                   1488:                             }
                   1489:                             if (keys(%tosend)) {
                   1490:                                 $request->print('<p>'.&mt('No scores sent for following'));
                   1491:                                 my ($zeros,$nopbcreds,$noconfirm,$noscore);
                   1492:                                 foreach my $student (sort
                   1493:                                 {
                   1494:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1495:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1496:                                      }
                   1497:                                      return $a cmp $b;
                   1498:                                 } (keys(%$fullname))) {
                   1499:                                     next unless ($tosend{$student});
                   1500:                                     my ($uname,$udom) = split(/:/,$student);
                   1501:                                     my $line = '<li>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).'</li>'."\n";
                   1502:                                     if ($zeroposs{$student}) {
                   1503:                                         $zeros .= $line;
                   1504:                                     } elsif ($nopbinfo{$student}) {
                   1505:                                         $nopbcreds .= $line;
                   1506:                                     } elsif ($remotenotok{$student}) {
                   1507:                                         $noconfirm .= $line;
                   1508:                                     } elsif ($scorenotok{$student}) {
                   1509:                                         $noscore .= $line;
                   1510:                                     }
                   1511:                                 }
                   1512:                                 if ($zeros) {
                   1513:                                     $request->print('<br />'.&mt('Total points possible was 0').':'.
                   1514:                                                     '<ul>'.$zeros.'</ul><br />');
                   1515:                                 }
                   1516:                                 if ($nopbcreds) {
                   1517:                                     $request->print('<br />'.&mt('Missing unique identifier and/or passback location').':'.
                   1518:                                                     '<ul>'.$nopbcreds.'</ul><br />');
                   1519:                                 }
                   1520:                                 if ($noconfirm) {
                   1521:                                     $request->print('<br />'.&mt('Score receipt not confirmed by receiving CMS').':'.
                   1522:                                                     '<ul>'.$noconfirm.'</ul><br />');
                   1523:                                 }
                   1524:                                 if ($noscore) {
                   1525:                                     $request->print('<br />'.&mt('Score computation or transmission failed').':'.
                   1526:                                                     '<ul>'.$noscore.'</ul><br />');
                   1527:                                 }
                   1528:                                 $request->print('</p>');
                   1529:                             }
                   1530:                         } else {
                   1531:                             $error = &mt('Settings for deep-link launch target unavailable, so no scores were sent');
                   1532:                         }
                   1533:                     } else {
                   1534:                         $error = &mt('No available students for whom scores can be sent.');
                   1535:                     }
                   1536:                 } else {
                   1537:                     $error = &mt('Classlist could not be retrieved so no scores were sent.');
                   1538:                 }
                   1539:             } else {
                   1540:                 $error = &mt('No students selected to receive scores so none were sent.');
                   1541:             }
                   1542:         } else {
                   1543:             if ($env{'form.passback'}) {
                   1544:                 $error = &mt('Deep-link launch target was invalid so no scores were sent.');
                   1545:             } else {
                   1546:                 $error = &mt('Deep-link launch target was missing so no scores were sent.');
                   1547:             }
                   1548:         }
                   1549:     } else {
                   1550:         $error = &mt('You do not have permission to manage grades, so no scores were sent');
                   1551:     }
                   1552:     if ($error) {
                   1553:         $request->print('<p class="LC_info">'.$error.'</p>');
                   1554:     }
                   1555:     return;
                   1556: }
                   1557: 
                   1558: sub get_passback_launcher {
                   1559:     my ($cdom,$cnum,$chosen) = @_;
                   1560:     my ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1561:     my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
                   1562:     my ($appname,$setter);
                   1563:     if ($ltitype eq 'c') {
                   1564:         my %lti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1565:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1566:             $appname = $lti{$ltinum}{'name'};
                   1567:             if ($appname) {
                   1568:                 $setter = ' (defined in course)';
                   1569:             }
                   1570:         }
                   1571:     } elsif ($ltitype eq 'd') {
                   1572:         my %lti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1573:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1574:             $appname = $lti{$ltinum}{'name'};
                   1575:             if ($appname) {
                   1576:                 $setter = ' (defined in domain)';
                   1577:             }
                   1578:         }
                   1579:     }
1.806   ! raeburn  1580:     my $launchsymb = &Apache::loncommon::symb_from_tinyurl($linkuri,$cnum,$cdom);
        !          1581:     if ($launchsymb eq '') {
        !          1582:         my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
        !          1583:         foreach my $poss_symb (keys(%passback)) {
        !          1584:             if (ref($passback{$poss_symb}) eq 'HASH') {
        !          1585:                 if (exists($passback{$poss_symb}{$chosen})) {
        !          1586:                     $launchsymb = $poss_symb;
        !          1587:                     last;
1.796     raeburn  1588:                 }
                   1589:             }
                   1590:         }
1.806   ! raeburn  1591:         if ($launchsymb ne '') {
        !          1592:             return ($launchsymb,$appname,$setter);
        !          1593:         }
        !          1594:     } else {
        !          1595:         my %passback = &Apache::lonnet::get('nohist_linkprot_passback',[$launchsymb],$cdom,$cnum);
        !          1596:         if (ref($passback{$launchsymb}) eq 'HASH') {
        !          1597:             if (exists($passback{$launchsymb}{$chosen})) {
        !          1598:                 return ($launchsymb,$appname,$setter);
        !          1599:             }
        !          1600:         }
1.796     raeburn  1601:     }
                   1602:     return ();
                   1603: }
                   1604: 
                   1605: sub sections_and_groups {
                   1606:     my (@sections,@groups,$group_display);
                   1607:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   1608:     if (grep(/^all$/,@groups)) {
                   1609:          @groups = ('all');
                   1610:          $group_display = 'all';
                   1611:     } elsif (grep(/^none$/,@groups)) {
                   1612:          @groups = ('none');
                   1613:          $group_display = 'none';
                   1614:     } elsif (@groups > 0) {
                   1615:          $group_display = join(', ',@groups);
                   1616:     }
                   1617:     if ($env{'request.course.sec'} ne '') {
                   1618:         @sections = ($env{'request.course.sec'});
                   1619:     } else {
                   1620:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1621:     }
                   1622:     my $disabled = ' disabled="disabled"';
                   1623:     if ($perm{'mgr'}) {
                   1624:         if (grep(/^all$/,@sections)) {
                   1625:             undef($disabled);
                   1626:         } else {
                   1627:             foreach my $sec (@sections) {
                   1628:                 if (&canmodify($sec)) {
                   1629:                     undef($disabled);
                   1630:                     last;
                   1631:                 }
                   1632:             }
                   1633:         }
                   1634:     }
                   1635:     if (grep(/^all$/,@sections)) {
                   1636:         @sections = ('all');
                   1637:     }
                   1638:     return(\@sections,\@groups,$group_display,$disabled);
                   1639: }
                   1640: 
                   1641: sub launcher_info_box {
                   1642:     my ($launcher,$appname,$setter,$linkuri,$scope) = @_;
                   1643:     my $shownscope;
                   1644:     if ($scope eq 'res') {
                   1645:         $shownscope = &mt('Resource');
                   1646:     } elsif ($scope eq 'map') {
                   1647:         $shownscope = &mt('Folder');
                   1648:     }  elsif ($scope eq 'rec') {
                   1649:         $shownscope = &mt('Folder + sub-folders');
                   1650:     }
                   1651:     return '<p>'.
                   1652:            &Apache::lonhtmlcommon::start_pick_box().
                   1653:            &Apache::lonhtmlcommon::row_title(&mt('Launch Item Title')).
1.797     raeburn  1654:            &Apache::lonnet::gettitle($launcher).
1.796     raeburn  1655:            &Apache::lonhtmlcommon::row_closure().
                   1656:            &Apache::lonhtmlcommon::row_title(&mt('Deep-link')).
                   1657:            $linkuri.
                   1658:            &Apache::lonhtmlcommon::row_closure().
                   1659:            &Apache::lonhtmlcommon::row_title(&mt('Launcher')).
                   1660:            $appname.' '.$setter.
                   1661:            &Apache::lonhtmlcommon::row_closure().
                   1662:            &Apache::lonhtmlcommon::row_title(&mt('Score Type')).
                   1663:            $shownscope.      
                   1664:            &Apache::lonhtmlcommon::row_closure(1).
                   1665:            &Apache::lonhtmlcommon::end_pick_box().'</p>'."\n";
                   1666: }
                   1667: 
1.798     raeburn  1668: sub passbacks_for_symb {
                   1669:     my ($cdom,$cnum,$symb) = @_;
                   1670:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   1671:     my %needpb;
                   1672:     if (keys(%passback)) {
                   1673:         my $checkpb = 1;
                   1674:         if (exists($passback{$symb})) {
                   1675:             if (keys(%passback) == 1) {
                   1676:                 undef($checkpb);
                   1677:             }
                   1678:             if (ref($passback{$symb}) eq 'HASH') {
                   1679:                 foreach my $launcher (keys(%{$passback{$symb}})) {
1.806   ! raeburn  1680:                     $needpb{$launcher} = $symb;
1.798     raeburn  1681:                 }
                   1682:             }
                   1683:         }
                   1684:         if ($checkpb) {
                   1685:             my ($map,$id,$url) = &Apache::lonnet::decode_symb($symb);
                   1686:             my $navmap = Apache::lonnavmaps::navmap->new();
                   1687:             if (ref($navmap)) {
                   1688:                 my $mapres = $navmap->getResourceByUrl($map);
                   1689:                 if (ref($mapres)) {
                   1690:                     my $mapsymb = $mapres->symb();
                   1691:                     if (exists($passback{$mapsymb})) {
                   1692:                         if (keys(%passback) == 1) {
                   1693:                             undef($checkpb);
                   1694:                         }
                   1695:                         if (ref($passback{$mapsymb}) eq 'HASH') {
                   1696:                             foreach my $launcher (keys(%{$passback{$mapsymb}})) {
1.806   ! raeburn  1697:                                 $needpb{$launcher} = $mapsymb;
1.798     raeburn  1698:                             }
                   1699:                         }
                   1700:                     }
                   1701:                     my %posspb;
                   1702:                     if ($checkpb) {
                   1703:                         my @recurseup = $navmap->recurseup_maps($map,1);
                   1704:                         if (@recurseup) {
                   1705:                             map { $posspb{$_} = 1; } @recurseup;
                   1706:                         }
                   1707:                     }
                   1708:                     foreach my $key (keys(%passback)) {
                   1709:                         if (exists($posspb{$key})) {
                   1710:                             if (ref($passback{$key}) eq 'HASH') {
                   1711:                                 foreach my $launcher (keys(%{$passback{$key}})) {
                   1712:                                     my ($linkuri,$linkprotector,$scope) = split("\0",$launcher);
                   1713:                                     next unless ($scope eq 'rec');
1.806   ! raeburn  1714:                                     $needpb{$launcher} = $key;
1.798     raeburn  1715:                                 }
                   1716:                             }
                   1717:                         }
                   1718:                     }
                   1719:                 }
                   1720:             }
                   1721:         }
                   1722:     }
                   1723:     return %needpb;
                   1724: }
                   1725: 
                   1726: sub process_passbacks {
1.802     raeburn  1727:     my ($context,$symbs,$cdom,$cnum,$udom,$uname,$usec,$weights,$awardeds,$excuseds,$needpb,
1.798     raeburn  1728:         $skip_passback,$pbsave,$pbids) = @_;
                   1729:     if ((ref($needpb) eq 'HASH') && (ref($skip_passback) eq 'HASH') && (ref($pbsave) eq 'HASH')) {
                   1730:         my (%weight,%awarded,%excused);
                   1731:         if ((ref($symbs) eq 'ARRAY') && (ref($weights) eq 'HASH') && (ref($awardeds) eq 'HASH') &&
                   1732:             (ref($excuseds) eq 'HASH')) {
                   1733:             %weight = %{$weights};
                   1734:             %awarded = %{$awardeds};
                   1735:             %excused = %{$excuseds};
                   1736:         }
                   1737:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
                   1738:         my @launchers = keys(%{$needpb});
                   1739:         my %pbinfo;
                   1740:         if (ref($pbids) eq 'HASH') {
                   1741:             %pbinfo = %{$pbids};
                   1742:         } else {
                   1743:             %pbinfo = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@launchers,$udom,$uname);
                   1744:         }
                   1745:         my %pbc = &common_passback_info();
                   1746:         foreach my $launcher (@launchers) {
                   1747:             if (ref($pbinfo{$launcher}) eq 'ARRAY') {
                   1748:                 my $pbid = $pbinfo{$launcher}[0];
                   1749:                 my $pburl = $pbinfo{$launcher}[1];
                   1750:                 my (%total_by_symb,%possible_by_symb);
                   1751:                 if (($pbid ne '') && ($pburl ne '')) {
                   1752:                     next if ($skip_passback->{$launcher});
                   1753:                     my %pb = %pbc;
                   1754:                     if ((exists($pbsave->{$launcher})) &&
                   1755:                         (ref($pbsave->{$launcher}) eq 'HASH')) {
                   1756:                         foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
                   1757:                                           'symb','map','pbscope','linkuri','linkprotector','scope') {
                   1758:                             $pb{$item} = $pbsave->{$launcher}{$item};
                   1759:                         }
                   1760:                     } else {
                   1761:                         my $ltitype;
                   1762:                         ($pb{'linkuri'},$pb{'linkprotector'},$pb{'scope'}) = split("\0",$launcher);
                   1763:                         ($pb{'ltinum'},$ltitype) = ($pb{'linkprotector'} =~ /^(\d+)(c|d)$/);
                   1764:                         if ($ltitype eq 'c') {
                   1765:                             my %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1766:                             $pb{'lti_in_use'} = $crslti{$pb{'ltinum'}};
                   1767:                             $pb{'crsdef'} = 1;
                   1768:                         } else {
                   1769:                             my %domlti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1770:                             $pb{'lti_in_use'} = $domlti{$pb{'ltinum'}};
                   1771:                         }
                   1772:                         if (ref($pb{'lti_in_use'}) eq 'HASH') {
                   1773:                             $pb{'msgformat'} = $pb{'lti_in_use'}->{'passbackformat'};
                   1774:                             $pb{'keynum'} = $pb{'lti_in_use'}->{'cipher'};
                   1775:                             $pb{'scoretype'} = 'decimal';
                   1776:                             if ($pb{'lti_in_use'}->{'scoreformat'} =~ /^(decimal|ratio|percentage)$/) {
                   1777:                                 $pb{'scoretype'} = $1;
                   1778:                             }
1.806   ! raeburn  1779:                             $pb{'symb'} = $needpb->{$launcher};
1.798     raeburn  1780:                             if ($pb{'symb'} =~ /\.(page|sequence)$/) {
                   1781:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[2]);
                   1782:                             } else {
                   1783:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[0]);
                   1784:                             }
                   1785:                             $pb{'map'} = &Apache::lonnet::clutter($pb{'map'});
                   1786:                             if ($pb{'scope'} eq 'res') {
                   1787:                                 $pb{'pbscope'} = 'resource';
                   1788:                             } elsif ($pb{'scope'} eq 'map') {
                   1789:                                 $pb{'pbscope'} = 'nonrec';
                   1790:                             } elsif ($pb{'scope'} eq 'rec') {
                   1791:                                 $pb{'pbscope'} = 'map';
                   1792:                             }
                   1793:                             foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
                   1794:                                               'symb','map','pbscope','linkuri','linkprotector','scope') {
                   1795:                                 $pbsave->{$launcher}{$item} = $pb{$item};
                   1796:                             }
                   1797:                         } else {
                   1798:                             $skip_passback->{$launcher} = 1;
                   1799:                         }
                   1800:                     }
                   1801:                     if (ref($symbs) eq 'ARRAY') {
                   1802:                         foreach my $symb (@{$symbs}) {
                   1803:                             if ((ref($weight{$symb}) eq 'HASH') && (ref($awarded{$symb}) eq 'HASH') &&
                   1804:                                 (ref($excused{$symb}) eq 'HASH')) {
                   1805:                                 foreach my $part (keys(%{$weight{$symb}})) {
                   1806:                                     if ($excused{$symb}{$part}) {
                   1807:                                         next;
                   1808:                                     }
                   1809:                                     my $partweight = $weight{$symb}{$part} eq '' ? 1 :
                   1810:                                                      $weight{$symb}{$part};
                   1811:                                     if ($awarded{$symb}{$part}) {
                   1812:                                         $total_by_symb{$symb} += $partweight * $awarded{$symb}{$part};
                   1813:                                     }
                   1814:                                     $possible_by_symb{$symb} += $partweight;
                   1815:                                 }
                   1816:                             }
                   1817:                         }
                   1818:                     }
                   1819:                     if ($context eq 'updatebypage') {
                   1820:                         my $ltigrade = {
                   1821:                                         'ltinum'     => $pb{'ltinum'},
                   1822:                                         'lti'        => $pb{'lti_in_use'},
                   1823:                                         'crsdef'     => $pb{'crsdef'},
                   1824:                                         'cid'        => $cdom.'_'.$cnum,
                   1825:                                         'uname'      => $uname,
                   1826:                                         'udom'       => $udom,
                   1827:                                         'uhome'      => $uhome,
1.802     raeburn  1828:                                         'usec'       => $usec,
1.798     raeburn  1829:                                         'pbid'       => $pbid,
                   1830:                                         'pburl'      => $pburl,
                   1831:                                         'pbtype'     => $pb{'type'},
                   1832:                                         'pbscope'    => $pb{'pbscope'},
                   1833:                                         'pbmap'      => $pb{'map'},
                   1834:                                         'pbsymb'     => $pb{'symb'},
                   1835:                                         'format'     => $pb{'scoretype'},
                   1836:                                         'scope'      => $pb{'scope'},
                   1837:                                         'clientip'   => $pb{'clientip'},
1.799     raeburn  1838:                                         'linkprot'   => $pb{'linkprotector'}.':'.$pb{'linkuri'},
1.798     raeburn  1839:                                         'total_s'    => \%total_by_symb,
                   1840:                                         'possible_s' => \%possible_by_symb,
                   1841:                         };
1.801     raeburn  1842:                         push(@Apache::grades::ltipassback,$ltigrade);
1.798     raeburn  1843:                         next;
                   1844:                     }
                   1845:                     my ($total,$possible);
                   1846:                     if ($pb{'pbscope'} eq 'resource') {
                   1847:                         $total = $total_by_symb{$pb{'symb'}};
                   1848:                         $possible = $possible_by_symb{$pb{'symb'}};
                   1849:                     } elsif (($pb{'pbscope'} eq 'map') || ($pb{'pbscope'} eq 'nonrec')) {
                   1850:                         ($total,$possible) =
1.806   ! raeburn  1851:                             &Apache::lonhomework::get_lti_score($uname,$udom,$usec,$pb{'map'},$pb{'pbscope'},
1.798     raeburn  1852:                                                                 \%total_by_symb,\%possible_by_symb);
                   1853:                     }
                   1854:                     if (!$possible) {
                   1855:                         $total = 0;
                   1856:                         $possible = 1;
                   1857:                     }
                   1858:                     my ($sent,$score,$code,$result) =
                   1859:                         &LONCAPA::ltiutils::send_grade($cdom,$cnum,$pb{'crsdef'},$pb{'type'},$pb{'ltinum'},
                   1860:                                                        $pb{'keynum'},$pbid,$pburl,$pb{'scoretype'},$pb{'sigmethod'},
                   1861:                                                        $pb{'msgformat'},$total,$possible);
                   1862:                     my $no_passback;
                   1863:                     if ($sent) {
                   1864:                         if ($code == 200) {
                   1865:                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
                   1866:                             my $store = {
                   1867:                                 'score' => $score,
                   1868:                                 'ip' => $pb{'ip'},
                   1869:                                 'host' => $pb{'lonhost'},
                   1870:                                 'protector' => $pb{'linkprotector'},
                   1871:                                 'deeplink' => $pb{'linkuri'},
                   1872:                                 'scope' => $pb{'scope'},
                   1873:                                 'url' => $pburl,
                   1874:                                 'id' => $pbid,
                   1875:                                 'clientip' => $pb{'clientip'},
                   1876:                                 'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
                   1877:                             };
                   1878:                             my $value='';
                   1879:                             foreach my $key (keys(%{$store})) {
                   1880:                                  $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
                   1881:                             }
                   1882:                             $value=~s/\&$//;
                   1883:                             &Apache::lonnet::courselog(&escape($pb{'linkuri'}).':'.$uname.':'.$udom.':EXPORT:'.$value);
                   1884:                             &Apache::lonnet::cstore({'score' => $score},$launcher,$namespace,$udom,$uname,'',$pb{'ip'},1);
                   1885:                         } else {
                   1886:                             $no_passback = 1;
                   1887:                         }
                   1888:                     } else {
                   1889:                         $no_passback = 1;
                   1890:                     }
                   1891:                     if ($no_passback) {
                   1892:                         &Apache::lonnet::log($udom,$uname,$uhome,$no_passback." score: $score; total: $total; possible: $possible");
                   1893:                         my $ltigrade = {
                   1894:                            'ltinum'   => $pb{'ltinum'},
                   1895:                            'lti'      => $pb{'lti_in_use'},
                   1896:                            'crsdef'   => $pb{'crsdef'},
                   1897:                            'cid'      => $cdom.'_'.$cnum,
                   1898:                            'uname'    => $uname,
                   1899:                            'udom'     => $udom,
                   1900:                            'uhome'    => $uhome,
                   1901:                            'pbid'     => $pbid,
                   1902:                            'pburl'    => $pburl,
                   1903:                            'pbtype'   => $pb{'type'},
                   1904:                            'pbscope'  => $pb{'pbscope'},
                   1905:                            'pbmap'    => $pb{'map'},
                   1906:                            'pbsymb'   => $pb{'symb'},
                   1907:                            'format'   => $pb{'scoretype'},
                   1908:                            'scope'    => $pb{'scope'},
                   1909:                            'clientip' => $pb{'clientip'},
1.799     raeburn  1910:                            'linkprot' => $pb{'linkprotector'}.':'.$pb{'linkuri'},
1.798     raeburn  1911:                            'total'    => $total,
                   1912:                            'possible' => $possible,
                   1913:                            'score'    => $score,
                   1914:                         };
                   1915:                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1916:                     }
                   1917:                 }
                   1918:             }
                   1919:         }
                   1920:     }
                   1921:     return;
                   1922: }
                   1923: 
                   1924: sub common_passback_info {
                   1925:     my %pbc = (
                   1926:                sigmethod => 'HMAC-SHA1',
                   1927:                type      => 'linkprot',
                   1928:                clientip  => &Apache::lonnet::get_requestor_ip(),
                   1929:                lonhost   => $Apache::lonnet::perlvar{'lonHostID'},
                   1930:                ip        => &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}),
                   1931:              );
                   1932:     return %pbc;
                   1933: }
                   1934: 
1.44      ng       1935: #--- This is called by a number of programs.
                   1936: #--- Called from the Grading Menu - View/Grade an individual student
                   1937: #--- Also called directly when one clicks on the subm button 
                   1938: #    on the problem page.
1.30      ng       1939: sub listStudents {
1.773     raeburn  1940:     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1941: 
1.747     raeburn  1942:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1943:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1944:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1945:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1946:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www      1947:     unless ($submitonly) {
1.766     raeburn  1948:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www      1949:     }
1.49      albertel 1950: 
1.632     www      1951:     my $result='';
1.623     www      1952:     my $res_error;
1.773     raeburn  1953:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   1954: 
                   1955:     my $table;
                   1956:     if (ref($partlist) eq 'ARRAY') {
                   1957:         if (scalar(@$partlist) > 1 ) {
                   1958:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1959:         } elsif ($divforres) {
                   1960:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1961:         } else {
                   1962:             $table = '<br clear="all" />';
                   1963:         }
                   1964:     }
1.49      albertel 1965: 
1.796     raeburn  1966:     $request->print(&checkselect_js());
1.597     wenzelju 1967:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1968: 
                   1969:     function reLoadList(formname) {
1.112     ng       1970: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1971: 	formname.command.value = 'submission';
                   1972: 	formname.submit();
                   1973:     }
1.45      ng       1974: LISTJAVASCRIPT
                   1975: 
1.118     ng       1976:     &commonJSfunctions($request);
1.41      ng       1977:     $request->print($result);
1.39      ng       1978: 
1.154     albertel 1979:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.773     raeburn  1980: 	"\n".$table;
                   1981: 
1.561     bisitz   1982:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn  1983:     unless ($is_tool) {
                   1984:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1985:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1986:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1987:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1988:                       .&Apache::lonhtmlcommon::row_closure();
                   1989:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1990:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1991:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1992:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1993:                       .&Apache::lonhtmlcommon::row_closure();
                   1994:     }
1.485     albertel 1995: 
1.442     banghart 1996:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1997:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1998:     $env{'form.Status'} = $saveStatus;
1.745     raeburn  1999:     my %optiontext;
                   2000:     if ($is_tool) {
                   2001:         %optiontext = &Apache::lonlocal::texthash (
                   2002:                           lastonly => 'last transaction',
                   2003:                           last     => 'last transaction with details',
                   2004:                           datesub  => 'all transactions',
                   2005:                           all      => 'all transactions with details',
                   2006:                       );
                   2007:     } else {
                   2008:         %optiontext = &Apache::lonlocal::texthash (
                   2009:                           lastonly => 'last submission',
                   2010:                           last     => 'last submission with details',
                   2011:                           datesub  => 'all submissions',
                   2012:                           all      => 'all submissions with details',
                   2013:                       );
                   2014:     }
1.773     raeburn  2015:     my $submission_options =
1.592     bisitz   2016:         '<span class="LC_nobreak">'.
1.624     www      2017:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  2018:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   2019:         '<span class="LC_nobreak">'.
                   2020:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  2021:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   2022:         '<span class="LC_nobreak">'.
1.628     www      2023:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  2024:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   2025:         '<span class="LC_nobreak">'.
                   2026:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  2027:         $optiontext{'all'}.'</label></span>';
                   2028:     my $viewtitle;
                   2029:     if ($is_tool) {
                   2030:         $viewtitle = &mt('View Transactions');
                   2031:     } else {
                   2032:         $viewtitle = &mt('View Submissions');
                   2033:     }
1.773     raeburn  2034:     my ($compmsg,$nocompmsg);
                   2035:     $nocompmsg = ' checked="checked"';
                   2036:     if ($numessay) {
                   2037:         $compmsg = $nocompmsg;
                   2038:         $nocompmsg = '';
                   2039:     }
1.745     raeburn  2040:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.780     raeburn  2041:                   .$submission_options;
                   2042: # Check if any gradable
                   2043:     my $showmore;
                   2044:     if ($perm{'mgr'}) {
                   2045:         my @sections;
                   2046:         if ($env{'request.course.sec'} ne '') {
                   2047:             @sections = ($env{'request.course.sec'});
1.783     raeburn  2048:         } elsif ($env{'form.section'} eq '') {
                   2049:             @sections = ('all');
1.780     raeburn  2050:         } else {
                   2051:             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   2052:         }
                   2053:         if (grep(/^all$/,@sections)) {
                   2054:             $showmore = 1;
                   2055:         } else {
                   2056:             foreach my $sec (@sections) {
                   2057:                 if (&canmodify($sec)) {
                   2058:                     $showmore = 1;
                   2059:                     last;
                   2060:                 }
                   2061:             }
                   2062:         }
                   2063:     }
                   2064: 
                   2065:     if ($showmore) {
                   2066:         $gradeTable .=
                   2067:                    &Apache::lonhtmlcommon::row_closure()
1.773     raeburn  2068:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   2069:                   .'<span class="LC_nobreak">'
                   2070:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   2071:                   .&mt('No').('&nbsp;'x2).'</label>'
                   2072:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   2073:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   2074:                   .&Apache::lonhtmlcommon::row_closure();
                   2075: 
1.780     raeburn  2076:         $gradeTable .= 
                   2077:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   2078:                   .'<select name="increment">'
                   2079:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   2080:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   2081:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   2082:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773     raeburn  2083:                   .'</select>';
1.780     raeburn  2084:     }
1.485     albertel 2085:     $gradeTable .= 
1.432     banghart 2086:         &build_section_inputs().
1.45      ng       2087: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 2088: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       2089: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      2090:     if (exists($env{'form.Status'})) {
1.784     raeburn  2091: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng       2092:     } else {
1.773     raeburn  2093:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2094:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   2095:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773     raeburn  2096:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       2097:     }
1.773     raeburn  2098:     if ($numessay) {
                   2099:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2100:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   2101:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  2102:     }
1.773     raeburn  2103:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
                   2104:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  2105:     my $regrademsg;
                   2106:     if ($is_tool) {
                   2107:         $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.");
                   2108:     } else {
                   2109:         $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.");
                   2110:     }
1.561     bisitz   2111:     $gradeTable .= '<p>'
1.745     raeburn  2112:                   .$regrademsg."\n"
1.561     bisitz   2113:                   .'<input type="hidden" name="command" value="processGroup" />'
                   2114:                   .'</p>';
1.249     albertel 2115: 
                   2116: # checkall buttons
                   2117:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       2118:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   2119:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   2120:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 2121:     $gradeTable.=&check_buttons();
1.450     banghart 2122:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 2123:     $gradeTable.= &Apache::loncommon::start_data_table().
                   2124: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       2125:     my $loop = 0;
                   2126:     while ($loop < 2) {
1.485     albertel 2127: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   2128: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      2129: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 2130: 	    foreach my $part (sort(@$partlist)) {
                   2131: 		my $display_part=
                   2132: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   2133: 		$gradeTable.=
                   2134: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       2135: 	    }
1.301     albertel 2136: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 2137: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       2138: 	}
                   2139: 	$loop++;
1.126     ng       2140: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       2141:     }
1.474     albertel 2142:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       2143: 
1.45      ng       2144:     my $ctr = 0;
1.294     albertel 2145:     foreach my $student (sort 
                   2146: 			 {
                   2147: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2148: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2149: 			     }
                   2150: 			     return $a cmp $b;
                   2151: 			 }
                   2152: 			 (keys(%$fullname))) {
1.41      ng       2153: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2154: 
1.110     ng       2155: 	my %status = ();
1.301     albertel 2156: 
                   2157: 	if ($submitonly eq 'queued') {
                   2158: 	    my %queue_status = 
                   2159: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2160: 							$udom,$uname);
                   2161: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2162: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   2163: 	}
                   2164: 
1.618     www      2165: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 2166: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2167: 	    my $submitted = 0;
1.164     albertel 2168: 	    my $graded = 0;
1.248     albertel 2169: 	    my $incorrect = 0;
1.110     ng       2170: 	    foreach (keys(%status)) {
1.145     albertel 2171: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2172: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   2173: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   2174: 		
1.110     ng       2175: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2176: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 2177: 		    $submitted = 0;
1.150     albertel 2178: 		    my ($part)=split(/\./,$partid);
1.110     ng       2179: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 2180: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       2181: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   2182: 		}
1.41      ng       2183: 	    }
1.248     albertel 2184: 	    
1.156     albertel 2185: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2186: 				     $submitonly eq 'incorrect' ||
                   2187: 				     $submitonly eq 'graded'));
1.248     albertel 2188: 	    next if (!$graded && ($submitonly eq 'graded'));
                   2189: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2190: 	}
1.34      ng       2191: 
1.45      ng       2192: 	$ctr++;
1.249     albertel 2193: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 2194:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 2195: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 2196: 	    if ($ctr%2 ==1) {
                   2197: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   2198: 	    }
1.126     ng       2199: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   2200:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 2201:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   2202: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   2203: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 2204: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       2205: 
1.618     www      2206: 	    if ($submitonly ne 'all') {
1.524     raeburn  2207: 		foreach (sort(keys(%status))) {
1.485     albertel 2208: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   2209: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       2210: 		}
1.41      ng       2211: 	    }
1.126     ng       2212: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 2213: 	    if ($ctr%2 ==0) {
                   2214: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   2215: 	    }
1.41      ng       2216: 	}
                   2217:     }
1.110     ng       2218:     if ($ctr%2 ==1) {
1.126     ng       2219: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      2220: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       2221: 		foreach (@$partlist) {
                   2222: 		    $gradeTable.='<td>&nbsp;</td>';
                   2223: 		}
1.301     albertel 2224: 	    } elsif ($submitonly eq 'queued') {
                   2225: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       2226: 	    }
1.474     albertel 2227: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       2228:     }
                   2229: 
1.474     albertel 2230:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   2231:         '<input type="button" '.
                   2232:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   2233:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       2234:     if ($ctr == 0) {
1.96      albertel 2235: 	my $num_students=(scalar(keys(%$fullname)));
                   2236: 	if ($num_students eq 0) {
1.485     albertel 2237: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 2238: 	} else {
1.171     albertel 2239: 	    my $submissions='submissions';
                   2240: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   2241: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 2242: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 2243: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   2244: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 2245: 		    $num_students).
                   2246: 		'</span><br />';
1.96      albertel 2247: 	}
1.46      ng       2248:     } elsif ($ctr == 1) {
1.474     albertel 2249: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       2250:     }
                   2251:     $request->print($gradeTable);
1.44      ng       2252:     return '';
1.10      ng       2253: }
                   2254: 
1.796     raeburn  2255: #---- Called from the listStudents and the names_for_passback routines.
                   2256: 
                   2257: sub checkselect_js {
                   2258:     my ($formname) = @_;
                   2259:     if ($formname eq '') {
                   2260:         $formname = 'gradesub';
                   2261:     }
                   2262:     my %js_lt;
                   2263:     if ($formname eq 'passbackusers') {
                   2264:         %js_lt = &Apache::lonlocal::texthash (
                   2265:                      'multiple' => 'Please select a student or group of students before pushing the Save Scores button.',
                   2266:                      'single'   => 'Please select the student before pushing the Save Scores button.',
                   2267:                  );
                   2268:     } else {
                   2269:         %js_lt = &Apache::lonlocal::texthash (
                   2270:                      'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   2271:                      'single'   => 'Please select the student before clicking on the Next button.',
                   2272:                  );
                   2273:     }
                   2274:     &js_escape(\%js_lt);
                   2275:     return &Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT);
                   2276: 
                   2277:     function checkSelect(checkBox) {
                   2278:         var ctr=0;
                   2279:         var sense="";
                   2280:         var len = checkBox.length;
                   2281:         if (len == undefined) len = 1;
                   2282:         if (len > 1) {
                   2283:             for (var i=0; i<len; i++) {
                   2284:                 if (checkBox[i].checked) {
                   2285:                     ctr++;
                   2286:                 }
                   2287:             }
                   2288:             sense = '$js_lt{'multiple'}';
                   2289:         } else {
                   2290:             if (checkBox.checked) {
                   2291:                 ctr = 1;
                   2292:             }
                   2293:             sense = '$js_lt{'single'}';
                   2294:         }
                   2295:         if (ctr == 0) {
                   2296:             alert(sense);
                   2297:             return false;
                   2298:         }
                   2299:         document.$formname.submit();
                   2300:     }
                   2301: LISTJAVASCRIPT
                   2302: 
                   2303: }
1.249     albertel 2304: 
                   2305: sub check_script {
1.766     raeburn  2306:     my ($form,$type) = @_;
                   2307:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 2308:     function checkall() {
                   2309:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2310:             ele = document.forms.'.$form.'.elements[i];
                   2311:             if (ele.name == "'.$type.'") {
                   2312:             document.forms.'.$form.'.elements[i].checked=true;
                   2313:                                        }
                   2314:         }
                   2315:     }
                   2316: 
                   2317:     function checksec() {
                   2318:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2319:             ele = document.forms.'.$form.'.elements[i];
                   2320:            string = document.forms.'.$form.'.chksec.value;
                   2321:            if
                   2322:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   2323:               document.forms.'.$form.'.elements[i].checked=true;
                   2324:             }
                   2325:         }
                   2326:     }
                   2327: 
                   2328: 
                   2329:     function uncheckall() {
                   2330:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2331:             ele = document.forms.'.$form.'.elements[i];
                   2332:             if (ele.name == "'.$type.'") {
                   2333:             document.forms.'.$form.'.elements[i].checked=false;
                   2334:                                        }
                   2335:         }
                   2336:     }
                   2337: 
1.597     wenzelju 2338: '."\n");
1.249     albertel 2339:     return $chkallscript;
                   2340: }
                   2341: 
                   2342: sub check_buttons {
1.485     albertel 2343:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   2344:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   2345:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 2346:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   2347:     return $buttons;
                   2348: }
                   2349: 
1.44      ng       2350: #     Displays the submissions for one student or a group of students
1.34      ng       2351: sub processGroup {
1.766     raeburn  2352:     my ($request,$symb) = @_;
1.41      ng       2353:     my $ctr        = 0;
1.155     albertel 2354:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       2355:     my $total      = scalar(@stuchecked)-1;
1.45      ng       2356: 
1.396     banghart 2357:     foreach my $student (@stuchecked) {
                   2358: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 2359: 	$env{'form.student'}        = $uname;
                   2360: 	$env{'form.userdom'}        = $udom;
                   2361: 	$env{'form.fullname'}       = $fullname;
1.619     www      2362: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2363: 	$ctr++;
                   2364:     }
                   2365:     return '';
1.35      ng       2366: }
1.34      ng       2367: 
1.44      ng       2368: #------------------------------------------------------------------------------------
                   2369: #
                   2370: #-------------------------- Next few routines handles grading by student, essentially
                   2371: #                           handles essay response type problem/part
                   2372: #
                   2373: #--- Javascript to handle the submission page functionality ---
                   2374: sub sub_page_js {
                   2375:     my $request = shift;
1.736     damieng  2376:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   2377:     &js_escape(\$alertmsg);
1.597     wenzelju 2378:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       2379:     function updateRadio(formname,id,weight) {
1.125     ng       2380: 	var gradeBox = formname["GD_BOX"+id];
                   2381: 	var radioButton = formname["RADVAL"+id];
                   2382: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       2383: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       2384: 	gradeBox.value = pts;
                   2385: 	var resetbox = false;
                   2386: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  2387: 	    alert("$alertmsg"+pts);
1.71      ng       2388: 	    for (var i=0; i<radioButton.length; i++) {
                   2389: 		if (radioButton[i].checked) {
                   2390: 		    gradeBox.value = i;
                   2391: 		    resetbox = true;
                   2392: 		}
                   2393: 	    }
                   2394: 	    if (!resetbox) {
                   2395: 		formtextbox.value = "";
                   2396: 	    }
                   2397: 	    return;
1.44      ng       2398: 	}
1.71      ng       2399: 
                   2400: 	if (pts > weight) {
                   2401: 	    var resp = confirm("You entered a value ("+pts+
                   2402: 			       ") greater than the weight for the part. Accept?");
                   2403: 	    if (resp == false) {
1.125     ng       2404: 		gradeBox.value = oldpts;
1.71      ng       2405: 		return;
                   2406: 	    }
1.44      ng       2407: 	}
1.13      albertel 2408: 
1.71      ng       2409: 	for (var i=0; i<radioButton.length; i++) {
                   2410: 	    radioButton[i].checked=false;
                   2411: 	    if (pts == i && pts != "") {
                   2412: 		radioButton[i].checked=true;
                   2413: 	    }
                   2414: 	}
                   2415: 	updateSelect(formname,id);
1.125     ng       2416: 	formname["stores"+id].value = "0";
1.41      ng       2417:     }
1.5       albertel 2418: 
1.72      ng       2419:     function writeBox(formname,id,pts) {
1.125     ng       2420: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2421: 	if (checkSolved(formname,id) == 'update') {
                   2422: 	    gradeBox.value = pts;
                   2423: 	} else {
1.125     ng       2424: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       2425: 	    gradeBox.value = oldpts;
1.125     ng       2426: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       2427: 	    for (var i=0; i<radioButton.length; i++) {
                   2428: 		radioButton[i].checked=false;
1.72      ng       2429: 		if (i == oldpts) {
1.71      ng       2430: 		    radioButton[i].checked=true;
                   2431: 		}
                   2432: 	    }
1.41      ng       2433: 	}
1.125     ng       2434: 	formname["stores"+id].value = "0";
1.71      ng       2435: 	updateSelect(formname,id);
                   2436: 	return;
1.41      ng       2437:     }
1.44      ng       2438: 
1.71      ng       2439:     function clearRadBox(formname,id) {
                   2440: 	if (checkSolved(formname,id) == 'noupdate') {
                   2441: 	    updateSelect(formname,id);
                   2442: 	    return;
                   2443: 	}
1.125     ng       2444: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       2445: 	for (var i=0; i<gradeSelect.length; i++) {
                   2446: 	    if (gradeSelect[i].selected) {
                   2447: 		var selectx=i;
                   2448: 	    }
                   2449: 	}
1.125     ng       2450: 	var stores = formname["stores"+id];
1.71      ng       2451: 	if (selectx == stores.value) { return };
1.125     ng       2452: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2453: 	gradeBox.value = "";
1.125     ng       2454: 	var radioButton = formname["RADVAL"+id];
1.71      ng       2455: 	for (var i=0; i<radioButton.length; i++) {
                   2456: 	    radioButton[i].checked=false;
                   2457: 	}
                   2458: 	stores.value = selectx;
                   2459:     }
1.5       albertel 2460: 
1.71      ng       2461:     function checkSolved(formname,id) {
1.125     ng       2462: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       2463: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   2464: 	    if (!reply) {return "noupdate";}
1.120     ng       2465: 	    formname.overRideScore.value = 'yes';
1.41      ng       2466: 	}
1.71      ng       2467: 	return "update";
1.13      albertel 2468:     }
1.71      ng       2469: 
                   2470:     function updateSelect(formname,id) {
1.125     ng       2471: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       2472: 	return;
1.41      ng       2473:     }
1.33      ng       2474: 
1.121     ng       2475: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       2476:     function checksubmit(formname,val,total,parttot) {
1.121     ng       2477: 	formname.gradeOpt.value = val;
1.71      ng       2478: 	if (val == "Save & Next") {
                   2479: 	    for (i=0;i<=total;i++) {
                   2480: 		for (j=0;j<parttot;j++) {
1.125     ng       2481: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       2482: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2483: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       2484: 			if (points == "") {
1.125     ng       2485: 			    var name = formname["name"+i].value;
1.129     ng       2486: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   2487: 			    var resp = confirm("You did not assign a score for "+studentID+
                   2488: 					       ", part "+partid+". Continue?");
1.71      ng       2489: 			    if (resp == false) {
1.125     ng       2490: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       2491: 				return false;
                   2492: 			    }
                   2493: 			}
                   2494: 		    }
                   2495: 		}
                   2496: 	    }
                   2497: 	}
1.120     ng       2498: 	formname.submit();
                   2499:     }
                   2500: 
1.71      ng       2501: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   2502:     function checkSubmitPage(formname,total) {
                   2503: 	noscore = new Array(100);
                   2504: 	var ptr = 0;
                   2505: 	for (i=1;i<total;i++) {
1.125     ng       2506: 	    var partid = formname["q_"+i].value;
1.127     ng       2507: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2508: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   2509: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       2510: 		if (points == "" && status != "correct_by_student") {
                   2511: 		    noscore[ptr] = i;
                   2512: 		    ptr++;
                   2513: 		}
                   2514: 	    }
                   2515: 	}
                   2516: 	if (ptr != 0) {
                   2517: 	    var sense = ptr == 1 ? ": " : "s: ";
                   2518: 	    var prolist = "";
                   2519: 	    if (ptr == 1) {
                   2520: 		prolist = noscore[0];
                   2521: 	    } else {
                   2522: 		var i = 0;
                   2523: 		while (i < ptr-1) {
                   2524: 		    prolist += noscore[i]+", ";
                   2525: 		    i++;
                   2526: 		}
                   2527: 		prolist += "and "+noscore[i];
                   2528: 	    }
                   2529: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   2530: 	    if (resp == false) {
                   2531: 		return false;
                   2532: 	    }
                   2533: 	}
1.45      ng       2534: 
1.71      ng       2535: 	formname.submit();
                   2536:     }
                   2537: SUBJAVASCRIPT
                   2538: }
1.45      ng       2539: 
1.773     raeburn  2540: #--- javascript for grading message center
                   2541: sub sub_grademessage_js {
1.71      ng       2542:     my $request = shift;
1.80      ng       2543:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       2544:     &commonJSfunctions($request);
1.350     albertel 2545: 
1.629     www      2546:     my $inner_js_msg_central= (<<INNERJS);
                   2547: <script type="text/javascript">
1.350     albertel 2548:     function checkInput() {
                   2549:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   2550:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   2551:       var usrctr = document.msgcenter.usrctr.value;
                   2552:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   2553:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   2554: 
                   2555:       var msgchk = "";
                   2556:       if (document.msgcenter.subchk.checked) {
                   2557:          msgchk = "msgsub,";
                   2558:       }
                   2559:       var includemsg = 0;
                   2560:       for (var i=1; i<=nmsg; i++) {
                   2561:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   2562:           var frmmsg = document.msgcenter["msg"+i];
                   2563:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   2564:           var showflg = opener.document.SCORE["shownOnce"+i];
                   2565:           showflg.value = "1";
                   2566:           var chkbox = document.msgcenter["msgn"+i];
                   2567:           if (chkbox.checked) {
                   2568:              msgchk += "savemsg"+i+",";
                   2569:              includemsg = 1;
                   2570:           }
                   2571:       }
                   2572:       if (document.msgcenter.newmsgchk.checked) {
                   2573:          msgchk += "newmsg"+usrctr;
                   2574:          includemsg = 1;
                   2575:       }
                   2576:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   2577:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   2578:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   2579:       includemsg.value = msgchk;
                   2580: 
                   2581:       self.close()
                   2582: 
                   2583:     }
1.629     www      2584: </script>
1.350     albertel 2585: INNERJS
                   2586: 
1.773     raeburn  2587:     my $start_page_msg_central =
1.351     albertel 2588:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   2589: 				       {'js_ready'  => 1,
                   2590: 					'only_body' => 1,
                   2591: 					'bgcolor'   =>'#FFFFFF',});
1.773     raeburn  2592:     my $end_page_msg_central =
1.350     albertel 2593: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   2594: 
1.219     www      2595:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 2596:     $docopen=~s/^document\.//;
1.773     raeburn  2597: 
1.736     damieng  2598:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  2599:                 comp => 'Compose Message for: ',
                   2600:                 incl => 'Include',
1.656     raeburn  2601:                 type => 'Type',
1.652     raeburn  2602:                 subj => 'Subject',
                   2603:                 mesa => 'Message',
                   2604:                 new  => 'New',
                   2605:                 save => 'Save',
                   2606:                 canc => 'Cancel',
                   2607:              );
1.736     damieng  2608:     &html_escape(\%html_js_lt);
                   2609:     &js_escape(\%html_js_lt);
1.597     wenzelju 2610:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       2611: 
1.44      ng       2612: //===================== Script to view submitted by ==================
                   2613:   function viewSubmitter(submitter) {
                   2614:     document.SCORE.refresh.value = "on";
                   2615:     document.SCORE.NCT.value = "1";
                   2616:     document.SCORE.unamedom0.value = submitter;
                   2617:     document.SCORE.submit();
                   2618:     return;
                   2619:   }
                   2620: 
                   2621: //====================== Script for composing message ==============
1.80      ng       2622:    // preload images
                   2623:    img1 = new Image();
                   2624:    img1.src = "$iconpath/mailbkgrd.gif";
                   2625:    img2 = new Image();
                   2626:    img2.src = "$iconpath/mailto.gif";
                   2627: 
1.44      ng       2628:   function msgCenter(msgform,usrctr,fullname) {
                   2629:     var Nmsg  = msgform.savemsgN.value;
                   2630:     savedMsgHeader(Nmsg,usrctr,fullname);
                   2631:     var subject = msgform.msgsub.value;
1.127     ng       2632:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       2633:     re = /msgsub/;
                   2634:     var shwsel = "";
                   2635:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       2636:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   2637:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       2638:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       2639: 	var testmsg = "savemsg"+i+",";
                   2640: 	re = new RegExp(testmsg,"g");
1.44      ng       2641: 	shwsel = "";
                   2642: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       2643: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       2644: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       2645: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   2646: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       2647:     }
1.125     ng       2648:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       2649:     shwsel = "";
                   2650:     re = /newmsg/;
                   2651:     if (re.test(msgchk)) { shwsel = "checked" }
                   2652:     newMsg(newmsg,shwsel);
                   2653:     msgTail(); 
                   2654:     return;
                   2655:   }
                   2656: 
1.123     ng       2657:   function checkEntities(strx) {
                   2658:     if (strx.length == 0) return strx;
                   2659:     var orgStr = ["&", "<", ">", '"']; 
                   2660:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   2661:     var counter = 0;
                   2662:     while (counter < 4) {
                   2663: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   2664: 	counter++;
                   2665:     }
                   2666:     return strx;
                   2667:   }
                   2668: 
                   2669:   function strReplace(strx, orgStr, newStr) {
                   2670:     return strx.split(orgStr).join(newStr);
                   2671:   }
                   2672: 
1.44      ng       2673:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       2674:     var height = 70*Nmsg+250;
1.44      ng       2675:     if (height > 600) {
                   2676: 	height = 600;
                   2677:     }
1.118     ng       2678:     var xpos = (screen.width-600)/2;
                   2679:     xpos = (xpos < 0) ? '0' : xpos;
                   2680:     var ypos = (screen.height-height)/2-30;
                   2681:     ypos = (ypos < 0) ? '0' : ypos;
                   2682: 
1.668     www      2683:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       2684:     pWin.focus();
                   2685:     pDoc = pWin.document;
1.219     www      2686:     pDoc.$docopen;
1.351     albertel 2687:     pDoc.write('$start_page_msg_central');
1.76      ng       2688: 
                   2689:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   2690:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  2691:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       2692: 
1.676     golterma 2693:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  2694:     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       2695: }
                   2696:     function displaySubject(msg,shwsel) {
1.76      ng       2697:     pDoc = pWin.document;
1.676     golterma 2698:     pDoc.write("<tr>");
                   2699:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2700:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 2701:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       2702: }
                   2703: 
1.72      ng       2704:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       2705:     pDoc = pWin.document;
1.676     golterma 2706:     pDoc.write("<tr>");
                   2707:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 2708:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   2709:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2710: }
                   2711: 
                   2712:   function newMsg(newmsg,shwsel) {
1.76      ng       2713:     pDoc = pWin.document;
1.676     golterma 2714:     pDoc.write("<tr>");
                   2715:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2716:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 2717:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2718: }
                   2719: 
                   2720:   function msgTail() {
1.76      ng       2721:     pDoc = pWin.document;
1.676     golterma 2722:     //pDoc.write("<\\/table>");
1.465     albertel 2723:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  2724:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   2725:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 2726:     pDoc.write("<\\/form>");
1.351     albertel 2727:     pDoc.write('$end_page_msg_central');
1.128     ng       2728:     pDoc.close();
1.44      ng       2729: }
                   2730: 
1.773     raeburn  2731: SUBJAVASCRIPT
                   2732: }
                   2733: 
                   2734: #--- javascript for essay type problem --
                   2735: sub sub_page_kw_js {
                   2736:     my $request = shift;
                   2737: 
                   2738:     unless ($env{'form.compmsg'}) {
                   2739:         &commonJSfunctions($request);
                   2740:     }
                   2741: 
                   2742:     my $inner_js_highlight_central= (<<INNERJS);
                   2743: <script type="text/javascript">
                   2744:     function updateChoice(flag) {
                   2745:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   2746:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   2747:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   2748:       opener.document.SCORE.refresh.value = "on";
                   2749:       if (opener.document.SCORE.keywords.value!=""){
                   2750:          opener.document.SCORE.submit();
                   2751:       }
                   2752:       self.close()
                   2753:     }
                   2754: </script>
                   2755: INNERJS
                   2756: 
                   2757:     my $start_page_highlight_central =
                   2758:         &Apache::loncommon::start_page('Highlight Central',
                   2759:                                        $inner_js_highlight_central,
                   2760:                                        {'js_ready'  => 1,
                   2761:                                         'only_body' => 1,
                   2762:                                         'bgcolor'   =>'#FFFFFF',});
                   2763:     my $end_page_highlight_central =
                   2764:         &Apache::loncommon::end_page({'js_ready' => 1});
                   2765: 
                   2766:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   2767:     $docopen=~s/^document\.//;
                   2768: 
                   2769:     my %js_lt = &Apache::lonlocal::texthash(
                   2770:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   2771:                 plse => 'Please select a word or group of words from document and then click this link.',
                   2772:                 adds => 'Add selection to keyword list? Edit if desired.',
                   2773:                 col1 => 'red',
                   2774:                 col2 => 'green',
                   2775:                 col3 => 'blue',
                   2776:                 siz1 => 'normal',
                   2777:                 siz2 => '+1',
                   2778:                 siz3 => '+2',
                   2779:                 sty1 => 'normal',
                   2780:                 sty2 => 'italic',
                   2781:                 sty3 => 'bold',
                   2782:              );
                   2783:     my %html_js_lt = &Apache::lonlocal::texthash(
                   2784:                 save => 'Save',
                   2785:                 canc => 'Cancel',
                   2786:                 kehi => 'Keyword Highlight Options',
                   2787:                 txtc => 'Text Color',
                   2788:                 font => 'Font Size',
                   2789:                 fnst => 'Font Style',
                   2790:              );
                   2791:     &js_escape(\%js_lt);
                   2792:     &html_escape(\%html_js_lt);
                   2793:     &js_escape(\%html_js_lt);
                   2794:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   2795: 
                   2796: //===================== Show list of keywords ====================
                   2797:   function keywords(formname) {
                   2798:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   2799:     if (nret==null) return;
                   2800:     formname.keywords.value = nret;
                   2801: 
                   2802:     if (formname.keywords.value != "") {
                   2803:         formname.refresh.value = "on";
                   2804:         formname.submit();
                   2805:     }
                   2806:     return;
                   2807:   }
                   2808: 
                   2809: //===================== Script to add keyword(s) ==================
                   2810:   function getSel() {
                   2811:     if (document.getSelection) txt = document.getSelection();
                   2812:     else if (document.selection) txt = document.selection.createRange().text;
                   2813:     else return;
                   2814:     if (typeof(txt) != 'string') {
                   2815:         txt = String(txt);
                   2816:     }
                   2817:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   2818:     if (cleantxt=="") {
                   2819:         alert("$js_lt{'plse'}");
                   2820:         return;
                   2821:     }
                   2822:     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   2823:     if (nret==null) return;
                   2824:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   2825:     if (document.SCORE.keywords.value != "") {
                   2826:         document.SCORE.refresh.value = "on";
                   2827:         document.SCORE.submit();
                   2828:     }
                   2829:     return;
                   2830:   }
                   2831: 
1.44      ng       2832: //====================== Script for keyword highlight options ==============
                   2833:   function kwhighlight() {
                   2834:     var kwclr    = document.SCORE.kwclr.value;
                   2835:     var kwsize   = document.SCORE.kwsize.value;
                   2836:     var kwstyle  = document.SCORE.kwstyle.value;
                   2837:     var redsel = "";
                   2838:     var grnsel = "";
                   2839:     var blusel = "";
1.736     damieng  2840:     var txtcol1 = "$js_lt{'col1'}";
                   2841:     var txtcol2 = "$js_lt{'col2'}";
                   2842:     var txtcol3 = "$js_lt{'col3'}";
                   2843:     var txtsiz1 = "$js_lt{'siz1'}";
                   2844:     var txtsiz2 = "$js_lt{'siz2'}";
                   2845:     var txtsiz3 = "$js_lt{'siz3'}";
                   2846:     var txtsty1 = "$js_lt{'sty1'}";
                   2847:     var txtsty2 = "$js_lt{'sty2'}";
                   2848:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   2849:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   2850:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   2851:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       2852:     var sznsel = "";
                   2853:     var sz1sel = "";
                   2854:     var sz2sel = "";
1.718     bisitz   2855:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   2856:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   2857:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       2858:     var synsel = "";
                   2859:     var syisel = "";
                   2860:     var sybsel = "";
1.718     bisitz   2861:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   2862:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   2863:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       2864:     highlightCentral();
1.718     bisitz   2865:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   2866:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   2867:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       2868:     highlightend();
                   2869:     return;
                   2870:   }
                   2871: 
                   2872:   function highlightCentral() {
1.76      ng       2873: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       2874:     var xpos = (screen.width-400)/2;
                   2875:     xpos = (xpos < 0) ? '0' : xpos;
                   2876:     var ypos = (screen.height-330)/2-30;
                   2877:     ypos = (ypos < 0) ? '0' : ypos;
                   2878: 
1.206     albertel 2879:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       2880:     hwdWin.focus();
                   2881:     var hDoc = hwdWin.document;
1.219     www      2882:     hDoc.$docopen;
1.351     albertel 2883:     hDoc.write('$start_page_highlight_central');
1.76      ng       2884:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  2885:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       2886: 
1.718     bisitz   2887:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  2888:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       2889:   }
                   2890: 
                   2891:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       2892:     var hDoc = hwdWin.document;
1.718     bisitz   2893:     hDoc.write("<tr>");
1.76      ng       2894:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2895:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       2896:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2897:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       2898:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2899:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 2900:     hDoc.write("<\\/tr>");
1.44      ng       2901:   }
                   2902: 
                   2903:   function highlightend() { 
1.76      ng       2904:     var hDoc = hwdWin.document;
1.718     bisitz   2905:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  2906:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   2907:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 2908:     hDoc.write("<\\/form>");
1.351     albertel 2909:     hDoc.write('$end_page_highlight_central');
1.128     ng       2910:     hDoc.close();
1.44      ng       2911:   }
                   2912: 
                   2913: SUBJAVASCRIPT
                   2914: }
                   2915: 
1.349     albertel 2916: sub get_increment {
1.348     bowersj2 2917:     my $increment = $env{'form.increment'};
                   2918:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   2919:         $increment != .1) {
                   2920:         $increment = 1;
                   2921:     }
                   2922:     return $increment;
                   2923: }
                   2924: 
1.585     bisitz   2925: sub gradeBox_start {
                   2926:     return (
                   2927:         &Apache::loncommon::start_data_table()
                   2928:        .&Apache::loncommon::start_data_table_header_row()
                   2929:        .'<th>'.&mt('Part').'</th>'
                   2930:        .'<th>'.&mt('Points').'</th>'
                   2931:        .'<th>&nbsp;</th>'
                   2932:        .'<th>'.&mt('Assign Grade').'</th>'
                   2933:        .'<th>'.&mt('Weight').'</th>'
                   2934:        .'<th>'.&mt('Grade Status').'</th>'
                   2935:        .&Apache::loncommon::end_data_table_header_row()
                   2936:     );
                   2937: }
                   2938: 
                   2939: sub gradeBox_end {
                   2940:     return (
                   2941:         &Apache::loncommon::end_data_table()
                   2942:     );
                   2943: }
1.71      ng       2944: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   2945: sub gradeBox {
1.322     albertel 2946:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 2947:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2948: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2949:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2950:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2951:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2952:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2953:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2954: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   2955:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2956:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2957:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2958: 				       [$partid]);
                   2959:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2960:     if ($last_resets{$partid}) {
                   2961:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2962:     }
1.695     bisitz   2963:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2964:     my $ctr = 0;
1.348     bowersj2 2965:     my $thisweight = 0;
1.349     albertel 2966:     my $increment = &get_increment();
1.485     albertel 2967: 
                   2968:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2969:     while ($thisweight<=$wgt) {
1.532     bisitz   2970: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2971:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2972: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2973: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2974: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2975:         $thisweight += $increment;
1.71      ng       2976: 	$ctr++;
                   2977:     }
1.485     albertel 2978:     $radio.='</tr></table>';
                   2979: 
                   2980:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2981: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2982: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2983: 	$wgt.')" /></td>'."\n";
1.485     albertel 2984:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2985: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2986: 	' </td>'."\n";
                   2987:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2988: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2989:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2990: 	$line.='<option></option>'.
                   2991: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2992:     } else {
1.485     albertel 2993: 	$line.='<option selected="selected"></option>'.
                   2994: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2995:     }
1.485     albertel 2996:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2997: 
                   2998: 
                   2999:     $result .= 
1.695     bisitz   3000: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   3001:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   3002:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       3003:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   3004: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   3005: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  3006: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   3007:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   3008:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   3009:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   3010:         $aggtries.'" />'."\n";
1.582     raeburn  3011:     my $res_error;
                   3012:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   3013:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  3014:     if ($res_error) {
                   3015:         return &navmap_errormsg();
                   3016:     }
1.318     banghart 3017:     return $result;
                   3018: }
1.322     albertel 3019: 
                   3020: sub handback_box {
1.623     www      3021:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773     raeburn  3022:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   3023:     return unless ($numessay);
1.323     banghart 3024:     my (@respids);
1.652     raeburn  3025:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 3026:     foreach my $part_response_id (@part_response_id) {
                   3027:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 3028:         if ($part eq $partid) {
1.375     albertel 3029:             push(@respids,$resp);
1.323     banghart 3030:         }
                   3031:     }
1.318     banghart 3032:     my $result;
1.323     banghart 3033:     foreach my $respid (@respids) {
1.322     albertel 3034: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   3035: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3036: 	next if (!@$files);
1.654     raeburn  3037: 	my $file_counter = 0;
1.313     banghart 3038: 	foreach my $file (@$files) {
1.368     banghart 3039: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  3040:                 $file_counter++;
1.368     banghart 3041:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  3042:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 3043:     	        $file_disp = "$name.$ext";
                   3044:     	        $file = $file_path.$file_disp;
                   3045:     	        $result.=&mt('Return commented version of [_1] to student.',
                   3046:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   3047:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  3048:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 3049: 	    }
1.322     albertel 3050: 	}
1.654     raeburn  3051:         if ($file_counter) {
                   3052:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   3053:                        '<span class="LC_info">'.
                   3054:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   3055:         }
1.313     banghart 3056:     }
1.318     banghart 3057:     return $result;    
1.71      ng       3058: }
1.44      ng       3059: 
1.58      albertel 3060: sub show_problem {
1.382     albertel 3061:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 3062:     my $rendered;
1.382     albertel 3063:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 3064:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 3065:     if ($mode eq 'both' or $mode eq 'text') {
                   3066: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 3067: 						       $env{'request.course.id'},
                   3068: 						       undef,\%form);
1.144     albertel 3069:     }
1.58      albertel 3070:     if ($removeform) {
                   3071: 	$rendered=~s|<form(.*?)>||g;
                   3072: 	$rendered=~s|</form>||g;
1.374     albertel 3073: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 3074:     }
1.144     albertel 3075:     my $companswer;
                   3076:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 3077: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 3078: 	$companswer=
                   3079: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   3080: 						    $env{'request.course.id'},
                   3081: 						    %form);
1.144     albertel 3082:     }
1.58      albertel 3083:     if ($removeform) {
                   3084: 	$companswer=~s|<form(.*?)>||g;
                   3085: 	$companswer=~s|</form>||g;
1.144     albertel 3086: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 3087:     }
1.671     raeburn  3088:     my $renderheading = &mt('View of the problem');
                   3089:     my $answerheading = &mt('Correct answer');
                   3090:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   3091:         my $stu_fullname = $env{'form.fullname'};
                   3092:         if ($stu_fullname eq '') {
                   3093:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3094:         }
                   3095:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   3096:         if ($forwhom ne '') {
                   3097:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   3098:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   3099:         }
                   3100:     }
1.468     albertel 3101:     $rendered=
1.588     bisitz   3102:         '<div class="LC_Box">'
1.671     raeburn  3103:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   3104:        .$rendered
                   3105:        .'</div>';
1.468     albertel 3106:     $companswer=
1.588     bisitz   3107:         '<div class="LC_Box">'
1.671     raeburn  3108:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   3109:        .$companswer
                   3110:        .'</div>';
1.468     albertel 3111:     my $result;
1.144     albertel 3112:     if ($mode eq 'both') {
1.588     bisitz   3113:         $result=$rendered.$companswer;
1.144     albertel 3114:     } elsif ($mode eq 'text') {
1.588     bisitz   3115:         $result=$rendered;
1.144     albertel 3116:     } elsif ($mode eq 'answer') {
1.588     bisitz   3117:         $result=$companswer;
1.144     albertel 3118:     }
1.71      ng       3119:     return $result;
1.58      albertel 3120: }
1.397     albertel 3121: 
1.396     banghart 3122: sub files_exist {
                   3123:     my ($r, $symb) = @_;
                   3124:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   3125:     foreach my $student (@students) {
                   3126:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 3127:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3128: 					      $udom,$uname);
1.792     raeburn  3129:         my ($string)= &get_last_submission(\%record);
1.397     albertel 3130:         foreach my $submission (@$string) {
                   3131:             my ($partid,$respid) =
                   3132: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3133:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   3134: 					   \%record);
                   3135:             return 1 if (@$files);
1.396     banghart 3136:         }
                   3137:     }
1.397     albertel 3138:     return 0;
1.396     banghart 3139: }
1.397     albertel 3140: 
1.394     banghart 3141: sub download_all_link {
                   3142:     my ($r,$symb) = @_;
1.621     www      3143:     unless (&files_exist($r, $symb)) {
1.766     raeburn  3144:         $r->print(&mt('There are currently no submitted documents.'));
                   3145:         return;
1.621     www      3146:     }
1.395     albertel 3147:     my $all_students = 
                   3148: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   3149: 
                   3150:     my $parts =
                   3151: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   3152: 
1.394     banghart 3153:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  3154:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   3155:                              'cgi.'.$identifier.'.symb' => $symb,
                   3156:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 3157:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   3158: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      3159:     return;
                   3160: }
                   3161: 
                   3162: sub submit_download_link {
                   3163:     my ($request,$symb) = @_;
                   3164:     if (!$symb) { return ''; }
1.750     raeburn  3165:     my $res_error;
1.773     raeburn  3166:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   3167:         &response_type($symb,\$res_error);
                   3168:     if ($res_error) {
                   3169:         $request->print(&mt('An error occurred retrieving response types'));
                   3170:         return;
                   3171:     }
                   3172:     unless ($numessay) {
                   3173:         $request->print(&mt('No essayresponse items found'));
                   3174:         return;
1.750     raeburn  3175:     }
1.773     raeburn  3176:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3177:     if (@chosenparts) {
                   3178:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   3179:                                           undef,undef,1));
1.750     raeburn  3180:     }
1.773     raeburn  3181:     if ($numessay) {
1.750     raeburn  3182:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   3183:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3184:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   3185:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   3186:         if (ref($fullname) eq 'HASH') {
                   3187:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   3188:             if (@students) {
                   3189:                 @{$env{'form.stuinfo'}} = @students;
1.773     raeburn  3190:                 if ($numdropbox) {
1.750     raeburn  3191:                     &download_all_link($request,$symb);
1.773     raeburn  3192:                 } else {
                   3193:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  3194:                 }
1.773     raeburn  3195: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  3196: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   3197:             } else {
                   3198:                 $request->print(&mt('No students match the criteria you selected'));
                   3199:             }
                   3200:         } else {
                   3201:             $request->print(&mt('Could not retrieve student information'));
                   3202:         }
                   3203:     } else {
                   3204:         $request->print(&mt('No essayresponse items found'));
                   3205:     }
                   3206:     return;
1.394     banghart 3207: }
1.395     albertel 3208: 
1.432     banghart 3209: sub build_section_inputs {
                   3210:     my $section_inputs;
                   3211:     if ($env{'form.section'} eq '') {
                   3212:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   3213:     } else {
                   3214:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 3215:         foreach my $section (@sections) {
1.432     banghart 3216:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   3217:         }
                   3218:     }
                   3219:     return $section_inputs;
                   3220: }
                   3221: 
1.44      ng       3222: # --------------------------- show submissions of a student, option to grade 
                   3223: sub submission {
1.773     raeburn  3224:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 3225:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   3226:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   3227:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3228:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      3229: 
1.324     albertel 3230:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773     raeburn  3231:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  3232:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  3233:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 3234: 
                   3235:     if (!&canview($usec)) {
1.712     bisitz   3236:         $request->print(
                   3237:             '<span class="LC_warning">'.
1.713     bisitz   3238:             &mt('Unable to view requested student.').
1.712     bisitz   3239:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3240:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3241:             '</span>');
1.104     albertel 3242: 	return;
                   3243:     }
                   3244: 
1.773     raeburn  3245:     my $res_error;
                   3246:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   3247:         &response_type($symb,\$res_error);
                   3248:     if ($res_error) {
                   3249:         $request->print(&navmap_errormsg());
                   3250:         return;
                   3251:     }
                   3252: 
1.257     albertel 3253:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  3254:     unless ($is_tool) { 
                   3255:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   3256:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   3257:     }
1.773     raeburn  3258:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   3259:         $env{'form.compmsg'} = 1;
                   3260:     }
1.257     albertel 3261:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 3262:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   3263: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       3264: 	'/check.gif" height="16" border="0" />';
1.41      ng       3265: 
                   3266:     # header info
                   3267:     if ($counter == 0) {
1.773     raeburn  3268:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3269:         if (@chosenparts) {
                   3270:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   3271:         } elsif ($divforres) {
                   3272:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   3273:         } else {
                   3274:             $request->print('<br clear="all" />');
                   3275:         }
1.41      ng       3276: 	&sub_page_js($request);
1.773     raeburn  3277:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   3278: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       3279: 
1.44      ng       3280: 	# option to display problem, only once else it cause problems 
                   3281:         # with the form later since the problem has a form.
1.257     albertel 3282: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 3283: 	    my $mode;
1.257     albertel 3284: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 3285: 		$mode='both';
1.257     albertel 3286: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 3287: 		$mode='text';
1.257     albertel 3288: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 3289: 		$mode='answer';
                   3290: 	    }
1.329     albertel 3291: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 3292: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       3293: 	}
1.441     www      3294: 
1.41      ng       3295: 	my %keyhash = ();
1.773     raeburn  3296: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       3297: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 3298: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   3299: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773     raeburn  3300: 	}
                   3301: 	# kwclr is the only variable that is guaranteed not to be blank
                   3302: 	# if this subroutine has been called once.
                   3303: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 3304: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3305: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   3306: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   3307: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   3308: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773     raeburn  3309: 	}
                   3310: 	if ($env{'form.compmsg'}) {
                   3311: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      3312: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 3313: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       3314: 	}
1.773     raeburn  3315: 
1.257     albertel 3316: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 3317: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 3318: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       3319: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 3320: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       3321: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       3322: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       3323: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   3324: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 3325: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3326: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   3327: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   3328: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773     raeburn  3329: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 3330: 			&build_section_inputs().
1.326     albertel 3331: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       3332: 			'<input type="hidden" name="NCT"'.
1.257     albertel 3333: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773     raeburn  3334: 	if ($env{'form.compmsg'}) {
                   3335: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   3336: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   3337: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   3338: 	}
                   3339: 	if ($numessay) {
1.257     albertel 3340: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   3341: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   3342: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773     raeburn  3343: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       3344: 	}
1.773     raeburn  3345: 
1.41      ng       3346: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 3347: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       3348: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       3349: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 3350: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       3351: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       3352: 		'" />'."\n".
                   3353: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       3354: 	    $cts++;
                   3355: 	}
                   3356: 	$request->print($prnmsg);
1.32      ng       3357: 
1.773     raeburn  3358: 	if ($numessay) {
1.652     raeburn  3359: 
                   3360:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   3361:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  3362:                           keyw => 'Keyword Options',
1.655     raeburn  3363:                           list => 'List',
1.652     raeburn  3364:                           past => 'Paste Selection to List',
1.661     www      3365:                           high => 'Highlight Attribute',
1.773     raeburn  3366:                      );
1.88      www      3367: #
                   3368: # Print out the keyword options line
                   3369: #
1.718     bisitz   3370: 	    $request->print(
                   3371:                 '<div class="LC_columnSection">'
                   3372:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   3373:                .&Apache::lonhtmlcommon::funclist_from_array(
                   3374:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   3375:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   3376:  class="page">'.$lt{'past'}.'</a>',
                   3377:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   3378:                     {legend => $lt{'keyw'}})
                   3379:                .'</fieldset></div>'
                   3380:             );
                   3381: 
1.88      www      3382: #
                   3383: # Load the other essays for similarity check
                   3384: #
1.753     raeburn  3385:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   3386:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3387:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3388:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3389:                 if ($cdom ne '' && $cnum ne '') {
                   3390:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   3391:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   3392:                         my $apath = $1.'_'.$id;
                   3393:                         $apath=~s/\W/\_/gs;
                   3394:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   3395:                     }
                   3396:                 }
                   3397:             } else {
                   3398: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   3399: 	        $apath=&escape($apath);
                   3400: 	        $apath=~s/\W/\_/gs;
                   3401:                 &init_old_essays($symb,$apath,$adom,$aname);
                   3402:             }
1.41      ng       3403:         }
                   3404:     }
1.44      ng       3405: 
1.441     www      3406: # This is where output for one specific student would start
1.592     bisitz   3407:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   3408:     $request->print(
                   3409:         "\n\n"
                   3410:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   3411:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   3412:        ."\n"
                   3413:     );
1.441     www      3414: 
1.592     bisitz   3415:     # Show additional functions if allowed
                   3416:     if ($perm{'vgr'}) {
                   3417:         $request->print(
                   3418:             &Apache::loncommon::track_student_link(
1.708     bisitz   3419:                 'View recent activity',
1.592     bisitz   3420:                 $uname,$udom,'check')
                   3421:            .' '
                   3422:         );
                   3423:     }
                   3424:     if ($perm{'opa'}) {
                   3425:         $request->print(
                   3426:             &Apache::loncommon::pprmlink(
                   3427:                 &mt('Set/Change parameters'),
                   3428:                 $uname,$udom,$symb,'check'));
                   3429:     }
                   3430: 
                   3431:     # Show Problem
1.257     albertel 3432:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 3433: 	my $mode;
1.257     albertel 3434: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 3435: 	    $mode='both';
1.257     albertel 3436: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 3437: 	    $mode='text';
1.257     albertel 3438: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 3439: 	    $mode='answer';
                   3440: 	}
1.329     albertel 3441: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 3442: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 3443:     }
1.144     albertel 3444: 
1.257     albertel 3445:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       3446: 
1.44      ng       3447:     # Display student info
1.41      ng       3448:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   3449: 
1.745     raeburn  3450:     my $boxtitle = &mt('Submissions');
                   3451:     if ($is_tool) {
                   3452:         $boxtitle = &mt('Transactions')
                   3453:     }
1.590     bisitz   3454:     my $result='<div class="LC_Box">'
1.745     raeburn  3455:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       3456:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   3457:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773     raeburn  3458:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   3459:         $result.='<p class="LC_info">'
                   3460:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   3461:                 ."</p>\n";
1.469     albertel 3462:     }
                   3463: 
1.773     raeburn  3464:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 3465:     my $fullname;
                   3466:     my $col_fullnames = [];
1.773     raeburn  3467:     if ($numessay) {
1.464     albertel 3468: 	(my $sub_result,$fullname,$col_fullnames)=
                   3469: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   3470: 				 $counter);
                   3471: 	$result.=$sub_result;
1.41      ng       3472:     }
1.44      ng       3473:     $request->print($result."\n");
1.773     raeburn  3474: 
1.44      ng       3475:     # print student answer/submission
1.773     raeburn  3476:     # Options are (1) Last submission only
                   3477:     #             (2) Last submission (with detailed information for that submission)
                   3478:     #             (3) All transactions (by date)
                   3479:     #             (4) The whole record (with detailed information for all transactions)
                   3480: 
1.793     raeburn  3481:     my ($lastsubonly,$partinfo) =
                   3482:         &show_last_submission($uname,$udom,$symb,$essayurl,$responseType,$env{'form.lastSub'},
                   3483:                               $is_tool,$fullname,\%record,\%coursedesc_by_cid);
                   3484:     $request->print($partinfo);
                   3485:     $request->print($lastsubonly);
                   3486: 
                   3487:     if ($env{'form.lastSub'} eq 'datesub') {
                   3488:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3489: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
                   3490:     }
                   3491:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   3492:         my $identifier = (&canmodify($usec)? $counter : '');
                   3493:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
                   3494: 								 $env{'request.course.id'},
                   3495: 								 $last,'.submission',
                   3496: 								 'Apache::grades::keywords_highlight',
                   3497:                                                                  $usec,$identifier));
                   3498:     }
                   3499:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   3500: 	.$udom.'" />'."\n");
                   3501:     # return if view submission with no grading option
                   3502:     if (!&canmodify($usec)) {
                   3503: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   3504: 	return;
                   3505:     } else {
                   3506: 	$request->print('</div>'."\n");
                   3507:     }
                   3508: 
                   3509:     # grading message center
                   3510: 
                   3511:     if ($env{'form.compmsg'}) {
                   3512:         my $result='<div class="LC_Box">'.
                   3513:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   3514:                    '<div class="LC_grade_message_center_body">';
                   3515:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   3516:         my $msgfor = $givenn.' '.$lastname;
                   3517:         if (scalar(@$col_fullnames) > 0) {
                   3518:             my $lastone = pop(@$col_fullnames);
                   3519:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   3520:         }
                   3521:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   3522:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   3523:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   3524:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   3525:                  ',\''.$msgfor.'\');" target="_self">'.
                   3526:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   3527:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   3528:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   3529:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   3530:                  '<br />&nbsp;('.
                   3531:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   3532:                  '</div></div>';
                   3533:         $request->print($result);
                   3534:     }
                   3535: 
                   3536:     my %seen = ();
                   3537:     my @partlist;
                   3538:     my @gradePartRespid;
                   3539:     my @part_response_id;
                   3540:     if ($is_tool) {
                   3541:         @part_response_id = ([0,'']);
                   3542:     } else {
                   3543:         @part_response_id = &flatten_responseType($responseType);
                   3544:     }
                   3545:     $request->print(
                   3546:         '<div class="LC_Box">'
                   3547:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
                   3548:     );
                   3549:     $request->print(&gradeBox_start());
                   3550:     foreach my $part_response_id (@part_response_id) {
                   3551:     	my ($partid,$respid) = @{ $part_response_id };
                   3552: 	my $part_resp = join('_',@{ $part_response_id });
                   3553: 	next if ($seen{$partid} > 0);
                   3554: 	$seen{$partid}++;
                   3555: 	push(@partlist,$partid);
                   3556: 	push(@gradePartRespid,$partid.'.'.$respid);
                   3557: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
                   3558:     }
                   3559:     $request->print(&gradeBox_end()); # </div>
                   3560:     $request->print('</div>');
                   3561: 
                   3562:     $request->print('<div class="LC_grade_info_links">');
                   3563:     $request->print('</div>');
                   3564: 
                   3565:     $result='<input type="hidden" name="partlist'.$counter.
                   3566: 	'" value="'.(join ":",@partlist).'" />'."\n";
                   3567:     $result.='<input type="hidden" name="gradePartRespid'.
                   3568: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
                   3569:     my $ctr = 0;
                   3570:     while ($ctr < scalar(@partlist)) {
                   3571: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   3572: 	    $partlist[$ctr].'" />'."\n";
                   3573: 	$ctr++;
                   3574:     }
                   3575:     $request->print($result.''."\n");
                   3576: 
                   3577: # Done with printing info for one student
                   3578: 
                   3579:     $request->print('</div>');#LC_grade_show_user
                   3580: 
                   3581: 
                   3582:     # print end of form
                   3583:     if ($counter == $total) {
                   3584:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
                   3585: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
                   3586: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
                   3587: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
                   3588: 	my $ntstu ='<select name="NTSTU">'.
                   3589: 	    '<option>1</option><option>2</option>'.
                   3590: 	    '<option>3</option><option>5</option>'.
                   3591: 	    '<option>7</option><option>10</option></select>'."\n";
                   3592: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
                   3593: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
                   3594:         $endform.=&mt('[_1]student(s)',$ntstu);
                   3595: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
                   3596: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
                   3597: 	    '<input type="button" value="'.&mt('Next').'" '.
                   3598: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
                   3599:         $endform.='<span class="LC_warning">'.
                   3600:                   &mt('(Next and Previous (student) do not save the scores.)').
                   3601:                   '</span>'."\n" ;
                   3602:         $endform.="<input type='hidden' value='".&get_increment().
                   3603:             "' name='increment' />";
                   3604: 	$endform.='</td></tr></table></form>';
                   3605: 	$request->print($endform);
                   3606:     }
                   3607:     return '';
                   3608: }
                   3609: 
                   3610: sub show_last_submission {
                   3611:     my ($uname,$udom,$symb,$essayurl,$responseType,$viewtype,$is_tool,$fullname,
                   3612:         $record,$coursedesc_by_cid) = @_;
1.792     raeburn  3613:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
1.793     raeburn  3614:         &get_last_submission($record,$is_tool);
1.468     albertel 3615: 
1.793     raeburn  3616:     my ($lastsubonly,$partinfo);
1.792     raeburn  3617:     if ($timestamp eq '') {
1.793     raeburn  3618:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>';
1.745     raeburn  3619:     } elsif ($is_tool) {
                   3620:         $lastsubonly =
                   3621:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3622:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$timestamp."</div>\n";
1.702     kruse    3623:     } else {
1.792     raeburn  3624:         my ($shownsubmdate,$showngradedate);
                   3625:         if ($lastsubmittime && $lastgradetime) {
                   3626:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
                   3627:             if ($lastgradetime > $lastsubmittime) {
                   3628:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
                   3629:              }
                   3630:         } else {
                   3631:             $shownsubmdate = $timestamp;
                   3632:         }
1.702     kruse    3633:         $lastsubonly =
                   3634:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3635:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
                   3636:         if ($showngradedate) {
                   3637:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
                   3638:         }
1.702     kruse    3639: 
1.793     raeburn  3640:         my %seenparts;
                   3641:         my @part_response_id = &flatten_responseType($responseType);
                   3642:         foreach my $part (@part_response_id) {
                   3643:             my ($partid,$respid) = @{ $part };
                   3644:             my $display_part=&get_display_part($partid,$symb);
                   3645:             if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   3646:                 if (exists($seenparts{$partid})) { next; }
                   3647:                 $seenparts{$partid}=1;
                   3648:                 $partinfo .=
1.702     kruse    3649:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3650:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   3651:                                '<a href="javascript:viewSubmitter(\''.
                   3652:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   3653:                                '\');" target="_self">'.
                   3654:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
1.793     raeburn  3655:                     '<br />';
                   3656:                 next;
                   3657:             }
                   3658:             my $responsetype = $responseType->{$partid}->{$respid};
                   3659:             if (!exists($record->{"resource.$partid.$respid.submission"})) {
1.702     kruse    3660:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   3661:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3662:                     ' <span class="LC_internal_info">'.
                   3663:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   3664:                     '</span>&nbsp; &nbsp;'.
1.793     raeburn  3665:                     '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   3666:                 next;
                   3667:             }
                   3668:             foreach my $submission (@$string) {
                   3669:                 my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3670:                 if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   3671:                 my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   3672:                 # Similarity check
1.702     kruse    3673:                 my $similar='';
                   3674:                 my ($type,$trial,$rndseed);
                   3675:                 if ($hide eq 'rand') {
                   3676:                     $type = 'randomizetry';
1.793     raeburn  3677:                     $trial = $record->{"resource.$partid.tries"};
                   3678:                     $rndseed = $record->{"resource.$partid.rndseed"};
1.702     kruse    3679:                 }
1.793     raeburn  3680:                 if ($env{'form.checkPlag'}) {
                   3681:                     my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   3682:                     &most_similar($uname,$udom,$symb,$subval);
                   3683:                     if ($osim) {
                   3684:                         $osim=int($osim*100.0);
1.702     kruse    3685:                         if ($hide eq 'anon') {
                   3686:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   3687:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   3688:                         } else {
1.793     raeburn  3689:                             $similar='<hr />';
1.753     raeburn  3690:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3691:                                 $similar .= '<h3><span class="LC_warning">'.
                   3692:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   3693:                                                 $osim,
                   3694:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3695:                                             '</span></h3>';
                   3696:                             } else {
                   3697:                                 my %old_course_desc;
                   3698:                                 if ($ocrsid ne '') {
1.793     raeburn  3699:                                     if (ref($coursedesc_by_cid->{$ocrsid}) eq 'HASH') {
                   3700:                                         %old_course_desc = %{$coursedesc_by_cid->{$ocrsid}};
1.753     raeburn  3701:                                     } else {
                   3702:                                         my $args;
                   3703:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   3704:                                             $args = {'one_time' => 1};
                   3705:                                         }
                   3706:                                         %old_course_desc =
                   3707:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
1.793     raeburn  3708:                                         $coursedesc_by_cid->{$ocrsid} = \%old_course_desc;
1.753     raeburn  3709:                                     }
                   3710:                                     $similar .=
                   3711:                                         '<h3><span class="LC_warning">'.
                   3712:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   3713:                                             $osim,
                   3714:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   3715:                                             $old_course_desc{'description'},
                   3716:                                             $old_course_desc{'num'},
                   3717:                                             $old_course_desc{'domain'}).
                   3718:                                         '</span></h3>';
                   3719:                                 } else {
                   3720:                                     $similar .=
                   3721:                                         '<h3><span class="LC_warning">'.
                   3722:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   3723:                                             $osim,
                   3724:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3725:                                         '</span></h3>';
                   3726:                                 }
                   3727:                             }
                   3728:                             $similar .= '<blockquote><i>'.
                   3729:                                         &keywords_highlight($oessay).
                   3730:                                         '</i></blockquote><hr />';
1.702     kruse    3731:                         }
1.793     raeburn  3732:                     }
                   3733:                 }
                   3734:                 my $order=&get_order($partid,$respid,$symb,$uname,$udom,
1.702     kruse    3735:                                      undef,$type,$trial,$rndseed);
1.793     raeburn  3736:                 if (($viewtype eq 'lastonly') ||
                   3737:                     ($viewtype eq 'datesub')  ||
                   3738:                     ($viewtype =~ /^(last|all)$/)) {
                   3739:                     my $display_part=&get_display_part($partid,$symb);
1.702     kruse    3740:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   3741:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3742:                         ' <span class="LC_internal_info">'.
                   3743:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   3744:                         '</span>&nbsp; &nbsp;';
1.793     raeburn  3745:                     my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3746:                     if (@$files) {
1.702     kruse    3747:                         if ($hide eq 'anon') {
                   3748:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   3749:                         } else {
                   3750:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   3751:                                         .'<br /><span class="LC_warning">';
                   3752:                             if(@$files == 1) {
                   3753:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  3754:                             } else {
1.702     kruse    3755:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   3756:                             }
1.774     raeburn  3757:                             $lastsubonly .= '</span>';
1.702     kruse    3758:                             foreach my $file (@$files) {
                   3759:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   3760:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  3761:                             }
                   3762:                         }
1.793     raeburn  3763:                         $lastsubonly.='<br />';
1.702     kruse    3764:                     }
                   3765:                     if ($hide eq 'anon') {
1.793     raeburn  3766:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
1.702     kruse    3767:                     } else {
1.774     raeburn  3768:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  3769:                         if ($draft) {
                   3770:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   3771:                         }
                   3772:                         $subval =
1.793     raeburn  3773:                             &cleanRecord($subval,$responsetype,$symb,$partid,
                   3774:                                          $respid,$record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  3775:                         if ($responsetype eq 'essay') {
                   3776:                             $subval =~ s{\n}{<br />}g;
                   3777:                         }
                   3778:                         $lastsubonly.=$subval."\n";
1.702     kruse    3779:                     }
1.774     raeburn  3780:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.793     raeburn  3781:                     $lastsubonly.='</div>';
                   3782:                 }
1.702     kruse    3783:             }
1.773     raeburn  3784:         }
1.793     raeburn  3785:         $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.118     ng       3786:     }
1.793     raeburn  3787:     return ($lastsubonly,$partinfo);
1.38      ng       3788: }
                   3789: 
1.464     albertel 3790: sub check_collaborators {
                   3791:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   3792:     my ($result,@col_fullnames);
                   3793:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   3794:     foreach my $part (keys(%$handgrade)) {
                   3795: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   3796: 					'.maxcollaborators',
                   3797: 					$symb,$udom,$uname);
                   3798: 	next if ($ncol <= 0);
                   3799: 	$part =~ s/\_/\./g;
                   3800: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   3801: 	my (@good_collaborators, @bad_collaborators);
                   3802: 	foreach my $possible_collaborator
1.630     www      3803: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 3804: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   3805: 	    next if ($possible_collaborator eq '');
1.631     www      3806: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 3807: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   3808: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   3809: 	    # Doing this grep allows 'fuzzy' specification
                   3810: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   3811: 			       keys(%$classlist));
                   3812: 	    if (! scalar(@matches)) {
                   3813: 		push(@bad_collaborators, $possible_collaborator);
                   3814: 	    } else {
                   3815: 		push(@good_collaborators, @matches);
                   3816: 	    }
                   3817: 	}
                   3818: 	if (scalar(@good_collaborators) != 0) {
1.630     www      3819: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 3820: 	    foreach my $name (@good_collaborators) {
                   3821: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   3822: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      3823: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 3824: 	    }
1.630     www      3825: 	    $result.='</ol><br />'."\n";
1.466     albertel 3826: 	    my ($part)=split(/\./,$part);
1.464     albertel 3827: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   3828: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   3829: 		"\n";
                   3830: 	}
                   3831: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 3832: 	    $result.='<div class="LC_warning">';
1.464     albertel 3833: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   3834: 	    $result .= '</div>';
                   3835: 	}         
                   3836: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 3837: 	    $result .= '<div class="LC_warning">';
1.464     albertel 3838: 	    $result .= &mt('This student has submitted too many '.
                   3839: 		'collaborators.  Maximum is [_1].',$ncol);
                   3840: 	    $result .= '</div>';
                   3841: 	}
                   3842:     }
                   3843:     return ($result,$fullname,\@col_fullnames);
                   3844: }
                   3845: 
1.44      ng       3846: #--- Retrieve the last submission for all the parts
1.38      ng       3847: sub get_last_submission {
1.745     raeburn  3848:     my ($returnhash,$is_tool)=@_;
1.792     raeburn  3849:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
1.119     ng       3850:     if ($$returnhash{'version'}) {
1.46      ng       3851: 	my %lasthash=();
1.792     raeburn  3852:         my %prevsolved=();
                   3853:         my %solved=();
                   3854: 	my $version;
1.119     ng       3855: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.792     raeburn  3856:             my %handgraded = ();
1.397     albertel 3857: 	    foreach my $key (sort(split(/\:/,
                   3858: 					$$returnhash{$version.':keys'}))) {
                   3859: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
1.792     raeburn  3860:                 if ($key =~ /\.([^.]+)\.regrader$/) {
                   3861:                     $handgraded{$1} = 1;
                   3862:                 } elsif ($key =~ /\.portfiles$/) {
                   3863:                     if (($$returnhash{$version.':'.$key} ne '') &&
                   3864:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
                   3865:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3866:                     }
                   3867:                 } elsif ($key =~ /\.submission$/) {
                   3868:                     if ($$returnhash{$version.':'.$key} ne '') {
                   3869:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3870:                     }
                   3871:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
                   3872:                     $prevsolved{$1} = $solved{$1};
                   3873:                     $solved{$1} = $lasthash{$key};
                   3874:                 }
                   3875:             }
                   3876:             foreach my $partid (keys(%handgraded)) {
                   3877:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
                   3878:                     (($solved{$partid} eq 'incorrect_by_override') ||
                   3879:                      ($solved{$partid} eq 'correct_by_override'))) {
                   3880:                     $lastgradetime = $$returnhash{$version.':timestamp'};
                   3881:                 }
                   3882:                 if ($solved{$partid} ne '') {
                   3883:                     $prevsolved{$partid} = $solved{$partid};
                   3884:                 }
1.46      ng       3885: 	    }
                   3886: 	}
1.795     raeburn  3887: #
                   3888: # Timestamp is for last transaction for this resource, which does not
                   3889: # necessarily correspond to the time of last submission for problem (or part).
                   3890: #
                   3891:         if ($lasthash{'timestamp'} ne '') {
                   3892:             $timestamp = &Apache::lonlocal::locallocaltime($lasthash{'timestamp'});
                   3893:         }
1.640     raeburn  3894:         my (%typeparts,%randombytry);
1.596     raeburn  3895:         my $showsurv = 
                   3896:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   3897:         foreach my $key (sort(keys(%lasthash))) {
                   3898:             if ($key =~ /\.type$/) {
                   3899:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  3900:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   3901:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  3902:                     my ($ign,@parts) = split(/\./,$key);
                   3903:                     pop(@parts);
1.641     raeburn  3904:                     my $id = join('.',@parts);
1.640     raeburn  3905:                     if ($lasthash{$key} eq 'randomizetry') {
                   3906:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   3907:                     } else {
                   3908:                         unless ($showsurv) {
                   3909:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   3910:                         }
1.596     raeburn  3911:                     }
                   3912:                     delete($lasthash{$key});
                   3913:                 }
                   3914:             }
                   3915:         }
                   3916:         my @hidden = keys(%typeparts);
1.640     raeburn  3917:         my @randomize = keys(%randombytry);
1.397     albertel 3918: 	foreach my $key (keys(%lasthash)) {
                   3919: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  3920:             my $hide;
                   3921:             if (@hidden) {
                   3922:                 foreach my $id (@hidden) {
                   3923:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  3924:                         $hide = 'anon';
1.596     raeburn  3925:                         last;
                   3926:                     }
                   3927:                 }
                   3928:             }
1.640     raeburn  3929:             unless ($hide) {
                   3930:                 if (@randomize) {
1.732     raeburn  3931:                     foreach my $id (@randomize) {
1.640     raeburn  3932:                         if ($key =~ /^\Q$id\E/) {
                   3933:                             $hide = 'rand';
                   3934:                             last;
                   3935:                         }
                   3936:                     }
                   3937:                 }
                   3938:             }
1.397     albertel 3939: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  3940: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   3941:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   3942:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   3943:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       3944: 	}
                   3945:     }
1.397     albertel 3946:     if (!@string) {
1.745     raeburn  3947:         my $msg;
                   3948:         if ($is_tool) {
1.747     raeburn  3949:             $msg = &mt('No grade passed back.');
1.745     raeburn  3950:         } else {
                   3951:             $msg = &mt('Nothing submitted - no attempts.');
                   3952:         }
1.397     albertel 3953: 	$string[0] =
1.745     raeburn  3954: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 3955:     }
1.792     raeburn  3956:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       3957: }
1.35      ng       3958: 
1.44      ng       3959: #--- High light keywords, with style choosen by user.
1.38      ng       3960: sub keywords_highlight {
1.44      ng       3961:     my $string    = shift;
1.257     albertel 3962:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   3963:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       3964:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 3965:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 3966:     foreach my $keyword (@keylist) {
                   3967: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       3968:     }
                   3969:     return $string;
1.38      ng       3970: }
1.36      ng       3971: 
1.671     raeburn  3972: # For Tasks provide a mechanism to display previous version for one specific student
                   3973: 
                   3974: sub show_previous_task_version {
                   3975:     my ($request,$symb) = @_;
                   3976:     if ($symb eq '') {
1.717     bisitz   3977:         $request->print(
                   3978:             '<span class="LC_error">'.
                   3979:             &mt('Unable to handle ambiguous references.').
                   3980:             '</span>');
1.671     raeburn  3981:         return '';
                   3982:     }
                   3983:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3984:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3985:     if (!&canview($usec)) {
1.712     bisitz   3986:         $request->print(
                   3987:             '<span class="LC_warning">'.
1.713     bisitz   3988:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   3989:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3990:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3991:             '</span>');
1.671     raeburn  3992:         return;
                   3993:     }
                   3994:     my $mode = 'both';
                   3995:     my $isTask = ($symb =~/\.task$/);
                   3996:     if ($isTask) {
                   3997:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   3998:             if ($env{'form.fullname'} eq '') {
                   3999:                 $env{'form.fullname'} =
                   4000:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   4001:             }
                   4002:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   4003:             $request->print("\n\n".
                   4004:                             '<div class="LC_grade_show_user">'.
                   4005:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   4006:                             '</h2>'."\n");
                   4007:             &Apache::lonxml::clear_problem_counter();
                   4008:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   4009:                             {'previousversion' => $env{'form.previousversion'} }));
                   4010:             $request->print("\n</div>");
                   4011:         }
                   4012:     }
                   4013:     return;
                   4014: }
                   4015: 
                   4016: sub choose_task_version_form {
                   4017:     my ($symb,$uname,$udom,$nomenu) = @_;
                   4018:     my $isTask = ($symb =~/\.task$/);
                   4019:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   4020:     if ($isTask) {
                   4021:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4022:                                               $udom,$uname);
                   4023:         if (($record{'resource.0.version'} eq '') ||
                   4024:             ($record{'resource.0.version'} < 2)) {
                   4025:             return ($record{'resource.0.version'},
                   4026:                     $record{'resource.0.version'},$result,$js);
                   4027:         } else {
                   4028:             $current = $record{'resource.0.version'};
                   4029:         }
                   4030:         if ($env{'form.previousversion'}) {
                   4031:             $displayed = $env{'form.previousversion'};
                   4032:             $rowtitle = &mt('Choose another version:')
                   4033:         } else {
                   4034:             $displayed = $current;
                   4035:             $rowtitle = &mt('Show earlier version:');
                   4036:         }
                   4037:         $result = '<div class="LC_left_float">';
                   4038:         my $list;
                   4039:         my $numversions = 0;
                   4040:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   4041:             if ($i == $current) {
                   4042:                 if (!$env{'form.previousversion'} || $nomenu) {
                   4043:                     next;
                   4044:                 } else {
                   4045:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   4046:                     $numversions ++;
                   4047:                 }
                   4048:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   4049:                 unless ($i == $env{'form.previousversion'}) {
                   4050:                     $numversions ++;
                   4051:                 }
                   4052:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   4053:             }
                   4054:         }
                   4055:         if ($numversions) {
                   4056:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   4057:             $result .=
                   4058:                 '<form name="getprev" method="post" action=""'.
                   4059:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   4060:                 &Apache::loncommon::start_data_table().
                   4061:                 &Apache::loncommon::start_data_table_row().
                   4062:                 '<th align="left">'.$rowtitle.'</th>'.
                   4063:                 '<td><select name="version">'.
                   4064:                 '<option>'.&mt('Select').'</option>'.
                   4065:                 $list.
                   4066:                 '</select></td>'.
                   4067:                 &Apache::loncommon::end_data_table_row();
                   4068:             unless ($nomenu) {
                   4069:                 $result .= &Apache::loncommon::start_data_table_row().
                   4070:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   4071:                 '<td><span class="LC_nobreak">'.
                   4072:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   4073:                 &mt('Yes').'</label>'.
                   4074:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   4075:                 '</span></td>'.
                   4076:                 &Apache::loncommon::end_data_table_row();
                   4077:             }
                   4078:             $result .=
                   4079:                 &Apache::loncommon::start_data_table_row().
                   4080:                 '<th align="left">&nbsp;</th>'.
                   4081:                 '<td>'.
                   4082:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   4083:                 '</td>'.
                   4084:                 &Apache::loncommon::end_data_table_row().
                   4085:                 &Apache::loncommon::end_data_table().
                   4086:                 '</form>';
                   4087:             $js = &previous_display_javascript($nomenu,$current);
                   4088:         } elsif ($displayed && $nomenu) {
                   4089:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   4090:         } else {
                   4091:             $result .= &mt('No previous versions to show for this student');
                   4092:         }
                   4093:         $result .= '</div>';
                   4094:     }
                   4095:     return ($current,$displayed,$result,$js);
                   4096: }
                   4097: 
                   4098: sub previous_display_javascript {
                   4099:     my ($nomenu,$current) = @_;
                   4100:     my $js = <<"JSONE";
                   4101: <script type="text/javascript">
                   4102: // <![CDATA[
                   4103: function previousVersion(uname,udom,symb) {
                   4104:     var current = '$current';
                   4105:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   4106:     var prevstr = new RegExp("^\\\\d+\$");
                   4107:     if (!prevstr.test(version)) {
                   4108:         return false;
                   4109:     }
                   4110:     var url = '';
                   4111:     if (version == current) {
                   4112:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   4113:     } else {
                   4114:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   4115:     }
                   4116: JSONE
                   4117:     if ($nomenu) {
                   4118:         $js .= <<"JSTWO";
                   4119:     document.location.href = url;
                   4120: JSTWO
                   4121:     } else {
                   4122:         $js .= <<"JSTHREE";
                   4123:     var newwin = 0;
                   4124:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   4125:         if (document.getprev.prevwin[i].checked == true) {
                   4126:             newwin = document.getprev.prevwin[i].value;
                   4127:         }
                   4128:     }
                   4129:     if (newwin == 1) {
                   4130:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   4131:         url = url+'&inhibitmenu=yes';
                   4132:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   4133:             previousWin = window.open(url,'',options,1);
                   4134:         } else {
                   4135:             previousWin.location.href = url;
                   4136:         }
                   4137:         previousWin.focus();
                   4138:         return false;
                   4139:     } else {
                   4140:         document.location.href = url;
                   4141:         return false;
                   4142:     }
                   4143: JSTHREE
                   4144:     }
                   4145:     $js .= <<"ENDJS";
                   4146:     return false;
                   4147: }
                   4148: // ]]>
                   4149: </script>
                   4150: ENDJS
                   4151: 
                   4152: }
                   4153: 
1.44      ng       4154: #--- Called from submission routine
1.38      ng       4155: sub processHandGrade {
1.608     www      4156:     my ($request,$symb) = @_;
1.324     albertel 4157:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 4158:     my $button = $env{'form.gradeOpt'};
                   4159:     my $ngrade = $env{'form.NCT'};
                   4160:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 4161:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4162:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.786     raeburn  4163:     my ($res_error,%queueable);
                   4164:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   4165:     if ($res_error) {
                   4166:         $request->print(&navmap_errormsg());
                   4167:         return;
                   4168:     } else {
                   4169:         foreach my $part (@{$partlist}) {
                   4170:             if (ref($responseType->{$part}) eq 'HASH') {
                   4171:                 foreach my $id (keys(%{$responseType->{$part}})) {
                   4172:                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   4173:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   4174:                         $queueable{$part} = 1;
                   4175:                         last;
                   4176:                     }
                   4177:                 }
                   4178:             }
                   4179:         }
                   4180:     }
1.301     albertel 4181: 
1.44      ng       4182:     if ($button eq 'Save & Next') {
1.798     raeburn  4183:         my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   4184:         my (%skip_passback,%pbsave,%pbcollab);
1.44      ng       4185: 	my $ctr = 0;
                   4186: 	while ($ctr < $ngrade) {
1.257     albertel 4187: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  4188: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
1.798     raeburn  4189:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable,\%needpb,\%skip_passback,\%pbsave);
1.71      ng       4190: 	    if ($errorflag eq 'no_score') {
                   4191: 		$ctr++;
                   4192: 		next;
                   4193: 	    }
1.104     albertel 4194: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   4195: 		$request->print(
                   4196:                     '<span class="LC_error">'
                   4197:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   4198:                    .'</span>');
1.104     albertel 4199: 		$ctr++;
                   4200: 		next;
                   4201: 	    }
1.726     raeburn  4202:             if ($numhidden) {
                   4203:                 $request->print(
                   4204:                     '<span class="LC_info">'
                   4205:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   4206:                    .'</span><br />');
                   4207:             }
1.257     albertel 4208: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       4209: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 4210: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   4211:             my ($feedurl,$showsymb) =
                   4212: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   4213: 	    my $messagetail;
1.62      albertel 4214: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      4215: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      4216: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  4217: 		$subject.=' ['.$restitle.']';
1.44      ng       4218: 		my (@msgnum) = split(/,/,$includemsg);
                   4219: 		foreach (@msgnum) {
1.257     albertel 4220: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       4221: 		}
1.80      ng       4222: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      4223: 		if ($env{'form.withgrades'.$ctr}) {
                   4224: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  4225: 		    $messagetail = " for <a href=\"".
1.605     www      4226: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  4227: 		}
                   4228: 		$msgstatus = 
                   4229:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   4230: 						     $message.$messagetail,
1.418     albertel 4231:                                                      undef,$feedurl,undef,
1.386     raeburn  4232:                                                      undef,undef,$showsymb,
                   4233:                                                      $restitle);
1.574     bisitz   4234: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  4235: 				$msgstatus.'<br />');
1.44      ng       4236: 	    }
1.257     albertel 4237: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 4238: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 4239: 		foreach my $collabstr (@collabstrs) {
                   4240: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 4241: 		    foreach my $collaborator (@collaborators) {
1.803     raeburn  4242: 			my ($errorflag,$pts,$wgt,$numchg,$numupdate) = 
1.324     albertel 4243: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.803     raeburn  4244: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 4245: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 4246: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 4247: 			    next;
1.798     raeburn  4248: 			} else {
1.803     raeburn  4249:                             if ($numchg || $numupdate) { 
                   4250:                                 $pbcollab{$collaborator}{$part} = [$pts,$wgt];
                   4251:                             }
1.798     raeburn  4252:                             if ($message ne '') {
1.800     raeburn  4253: 			        my ($baseurl,$showsymb) = 
                   4254: 				    &get_feedurl_and_symb($symb,$collaborator,
1.801     raeburn  4255: 						          $udom);
1.800     raeburn  4256: 			        if ($env{'form.withgrades'.$ctr}) {
                   4257: 				    $messagetail = " for <a href=\"".
                   4258:                                         $baseurl."?symb=$showsymb\">$restitle</a>";
                   4259: 			        }
                   4260: 			        $msgstatus =
                   4261: 				    &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.150     albertel 4262: 			    }
1.800     raeburn  4263: 		        }
1.44      ng       4264: 		    }
                   4265: 		}
                   4266: 	    }
                   4267: 	    $ctr++;
                   4268: 	}
1.798     raeburn  4269:         if ((keys(%pbcollab)) && (keys(%needpb))) {
1.803     raeburn  4270:             foreach my $user (keys(%pbcollab)) {
                   4271:                 my ($clbuname,$clbudom) = split(/:/,$user);
                   4272:                 my $clbusec = &Apache::lonnet::getsection($clbudom,$clbuname,$cdom.'_'.$cnum); 
                   4273:                 if (ref($pbcollab{$user}) eq 'HASH') {
                   4274:                     my @clparts = keys(%{$pbcollab{$user}});
                   4275:                     if (@clparts) {
                   4276:                         my $navmap = Apache::lonnavmaps::navmap->new($clbuname,$clbudom,$clbusec);
                   4277:                         if (ref($navmap)) {
                   4278:                             my $res = $navmap->getBySymb($symb);
                   4279:                             if (ref($res)) {
                   4280:                                 my $partlist = $res->parts();
                   4281:                                 if (ref($partlist) eq 'ARRAY') {
                   4282:                                     my (%weights,%awardeds,%excuseds);
                   4283:                                     foreach my $part (@{$partlist}) {
                   4284:                                         if ($res->status($part) eq $res->EXCUSED) {
                   4285:                                             $excuseds{$symb}{$part} = 1;
                   4286:                                         } else { 
                   4287:                                             $excuseds{$symb}{$part} = '';
                   4288:                                         }
                   4289:                                         if ((exists($pbcollab{$user}{$part})) && (ref($pbcollab{$user}{$part}) eq 'ARRAY')) {
                   4290:                                             my $pts = $pbcollab{$user}{$part}[0];
                   4291:                                             my $wt = $pbcollab{$user}{$part}[1];
                   4292:                                             if ($wt) {
                   4293:                                                 $awardeds{$symb}{$part} = $pts/$wt;
                   4294:                                                 $weights{$symb}{$part} = $wt;
                   4295:                                             } else {
                   4296:                                                 $awardeds{$symb}{$part} = 0;
                   4297:                                                 $weights{$symb}{$part} = 0;
                   4298:                                             }
                   4299:                                         } else {
                   4300:                                             $awardeds{$symb}{$part} = $res->awarded($part);
                   4301:                                             $weights{$symb}{$part} = $res->weight($part);
                   4302:                                         }
                   4303:                                     }
                   4304:                                     &process_passbacks('handgrade',[$symb],$cdom,$cnum,$clbudom,$clbuname,$clbusec,\%weights,
                   4305:                                                        \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   4306:                                 }
                   4307:                             }
                   4308:                         }
                   4309:                     }
                   4310:                 }
                   4311:             }
1.798     raeburn  4312:         }
1.44      ng       4313:     }
                   4314: 
1.773     raeburn  4315:     my %keyhash = ();
                   4316:     if ($numessay) {
1.119     ng       4317: 	# Keywords sorted in alphabatical order
1.257     albertel 4318: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   4319: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  4320: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 4321: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   4322: 	$env{'form.keywords'} = join(' ',@keywords);
                   4323: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   4324: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   4325: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   4326: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   4327: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  4328:     }
1.119     ng       4329: 
1.773     raeburn  4330:     if ($env{'form.compmsg'}) {
1.119     ng       4331: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 4332: 	# New messages are saved in env for the next student.
1.119     ng       4333: 	# All messages are saved in nohist_handgrade.db
                   4334: 	my ($ctr,$idx) = (1,1);
1.257     albertel 4335: 	while ($ctr <= $env{'form.savemsgN'}) {
                   4336: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   4337: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       4338: 		$idx++;
                   4339: 	    }
                   4340: 	    $ctr++;
1.41      ng       4341: 	}
1.119     ng       4342: 	$ctr = 0;
                   4343: 	while ($ctr < $ngrade) {
1.257     albertel 4344: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  4345: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4346: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4347: 	        $idx++;
1.119     ng       4348: 	    }
                   4349: 	    $ctr++;
1.41      ng       4350: 	}
1.257     albertel 4351: 	$env{'form.savemsgN'} = --$idx;
                   4352: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       4353:     }
1.773     raeburn  4354:     if (($numessay) || ($env{'form.compmsg'})) {
                   4355:         my $putresult = &Apache::lonnet::put
                   4356:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   4357:     }
                   4358: 
1.44      ng       4359:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 4360:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   4361:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       4362: 	my ($ctr,$total) = (0,0);
                   4363: 	while ($ctr < $ngrade) {
1.257     albertel 4364: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       4365: 	    $ctr++;
                   4366: 	}
1.257     albertel 4367: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       4368: 	$ctr = 0;
                   4369: 	while ($ctr < $total) {
1.257     albertel 4370: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   4371: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   4372: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      4373: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       4374: 	    $ctr++;
                   4375: 	}
                   4376: 	return '';
                   4377:     }
1.36      ng       4378: 
1.44      ng       4379:     # Get the next/previous one or group of students
1.257     albertel 4380:     my $firststu = $env{'form.unamedom0'};
                   4381:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       4382:     my $ctr = 2;
1.41      ng       4383:     while ($laststu eq '') {
1.257     albertel 4384: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       4385: 	$ctr++;
                   4386: 	$laststu = $firststu if ($ctr > $ngrade);
                   4387:     }
1.44      ng       4388: 
1.41      ng       4389:     my (@parsedlist,@nextlist);
                   4390:     my ($nextflg) = 0;
1.524     raeburn  4391:     foreach my $item (sort 
1.294     albertel 4392: 	     {
                   4393: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4394: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4395: 		 }
                   4396: 		 return $a cmp $b;
                   4397: 	     } (keys(%$fullname))) {
1.41      ng       4398: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  4399: 	    push(@parsedlist,$item);
1.41      ng       4400: 	}
1.524     raeburn  4401: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       4402: 	if ($button eq 'Previous') {
1.524     raeburn  4403: 	    last if ($item eq $firststu);
                   4404: 	    push(@parsedlist,$item);
1.41      ng       4405: 	}
                   4406:     }
                   4407:     $ctr = 0;
                   4408:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   4409:     foreach my $student (@parsedlist) {
1.257     albertel 4410: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       4411: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 4412: 	
                   4413: 	if ($submitonly eq 'queued') {
                   4414: 	    my %queue_status = 
                   4415: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4416: 							$udom,$uname);
                   4417: 	    next if (!defined($queue_status{'gradingqueue'}));
                   4418: 	}
                   4419: 
1.156     albertel 4420: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 4421: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 4422: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 4423: 	    my $submitted = 0;
1.248     albertel 4424: 	    my $ungraded = 0;
                   4425: 	    my $incorrect = 0;
1.524     raeburn  4426: 	    foreach my $item (keys(%status)) {
                   4427: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   4428: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   4429: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   4430: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 4431: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   4432: 		    $submitted = 0;
                   4433: 		}
1.41      ng       4434: 	    }
1.156     albertel 4435: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   4436: 				     $submitonly eq 'incorrect' ||
                   4437: 				     $submitonly eq 'graded'));
1.248     albertel 4438: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   4439: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       4440: 	}
1.524     raeburn  4441: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       4442: 	last if ($ctr == $ntstu);
1.41      ng       4443: 	$ctr++;
                   4444:     }
1.36      ng       4445: 
1.41      ng       4446:     $ctr = 0;
                   4447:     my $total = scalar(@nextlist)-1;
1.39      ng       4448: 
1.524     raeburn  4449:     foreach (sort(@nextlist)) {
1.41      ng       4450: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 4451: 	$env{'form.student'}  = $uname;
                   4452: 	$env{'form.userdom'}  = $udom;
                   4453: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      4454: 	&submission($request,$ctr,$total,$symb);
1.41      ng       4455: 	$ctr++;
                   4456:     }
                   4457:     if ($total < 0) {
1.653     raeburn  4458: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       4459: 	$request->print($the_end);
                   4460:     }
                   4461:     return '';
1.38      ng       4462: }
1.36      ng       4463: 
1.44      ng       4464: #---- Save the score and award for each student, if changed
1.38      ng       4465: sub saveHandGrade {
1.798     raeburn  4466:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable,$needpb,$skip_passback,$pbsave) = @_;
1.342     banghart 4467:     my @version_parts;
1.104     albertel 4468:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 4469: 					   $env{'request.course.id'});
1.104     albertel 4470:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 4471:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 4472:     my @parts_graded;
1.77      ng       4473:     my %newrecord  = ();
1.803     raeburn  4474:     my ($pts,$wgt,$totchg,$sendupdate) = ('','',0,0);
1.269     raeburn  4475:     my %aggregate = ();
                   4476:     my $aggregateflag = 0;
1.726     raeburn  4477:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  4478:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  4479:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  4480:         $totchg += $numchgs;
                   4481:     }
1.798     raeburn  4482:     my (%weights,%awardeds,%excuseds);
1.301     albertel 4483:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   4484:     foreach my $new_part (@parts) {
1.803     raeburn  4485: 	#collaborator ($submitter may vary for different parts)
1.259     banghart 4486: 	if ($submitter && $new_part ne $part) { next; }
                   4487: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.798     raeburn  4488:         if ($env{'form.WGT'.$newflg.'_'.$new_part} eq '') {
                   4489:             $weights{$symb}{$new_part} = 1;
                   4490:         } else {
                   4491:             $weights{$symb}{$new_part} = $env{'form.WGT'.$newflg.'_'.$new_part};
                   4492:         }
1.125     ng       4493: 	if ($dropMenu eq 'excused') {
1.798     raeburn  4494:             $excuseds{$symb}{$new_part} = 1;
                   4495:             $awardeds{$symb}{$new_part} = '';
1.259     banghart 4496: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   4497: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   4498: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   4499: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 4500: 		}
1.364     banghart 4501: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.803     raeburn  4502:                 $sendupdate ++;
1.58      albertel 4503: 	    }
1.125     ng       4504: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 4505: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  4506: 	    foreach my $key (keys(%record)) {
1.259     banghart 4507: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 4508: 	    }
1.259     banghart 4509: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4510: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 4511:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   4512: 
                   4513:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   4514: 					       [$new_part]);
                   4515:             my $aggtries =$totaltries;
1.269     raeburn  4516:             if ($last_resets{$new_part}) {
1.270     albertel 4517:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   4518: 					   $new_part);
1.269     raeburn  4519:             }
1.270     albertel 4520: 
                   4521:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  4522:             if ($aggtries > 0) {
1.327     albertel 4523:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  4524:                 $aggregateflag = 1;
                   4525:             }
1.803     raeburn  4526:             $sendupdate ++;
1.798     raeburn  4527:             $excuseds{$symb}{$new_part} = '';
                   4528:             $awardeds{$symb}{$new_part} = '';
1.125     ng       4529: 	} elsif ($dropMenu eq '') {
1.259     banghart 4530: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   4531: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   4532: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   4533: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 4534: 		next;
                   4535: 	    }
1.259     banghart 4536: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   4537: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       4538: 	    my $partial= $pts/$wgt;
1.798     raeburn  4539:             $awardeds{$symb}{$new_part} = $partial;
                   4540:             $excuseds{$symb}{$new_part} = '';
1.259     banghart 4541: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 4542: 		#do not update score for part if not changed.
1.346     banghart 4543:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 4544: 		next;
1.251     banghart 4545: 	    } else {
1.524     raeburn  4546: 	        push(@parts_graded,$new_part);
1.803     raeburn  4547:                 $sendupdate ++;
1.153     albertel 4548: 	    }
1.259     banghart 4549: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   4550: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 4551: 	    }
1.259     banghart 4552: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       4553: 	    if ($partial == 0) {
1.153     albertel 4554: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   4555: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   4556: 		}
1.41      ng       4557: 	    } else {
1.153     albertel 4558: 		if ($record{$reckey} ne 'correct_by_override') {
                   4559: 		    $newrecord{$reckey} = 'correct_by_override';
                   4560: 		}
                   4561: 	    }	    
                   4562: 	    if ($submitter && 
1.259     banghart 4563: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   4564: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       4565: 	    }
1.259     banghart 4566: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4567: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       4568: 	}
1.259     banghart 4569: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 4570: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   4571: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   4572: 	        $dropMenu eq 'reset status')
                   4573: 	   {
1.524     raeburn  4574: 	    push(@version_parts,$new_part);
1.259     banghart 4575: 	}
1.41      ng       4576:     }
1.301     albertel 4577:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4578:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4579: 
1.344     albertel 4580:     if (%newrecord) {
                   4581:         if (@version_parts) {
1.364     banghart 4582:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   4583:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 4584: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 4585: 	    foreach my $new_part (@version_parts) {
                   4586: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   4587: 				$new_part,\%newrecord);
                   4588: 	    }
1.259     banghart 4589:         }
1.44      ng       4590: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 4591: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 4592: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.786     raeburn  4593: 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       4594:     }
1.269     raeburn  4595:     if ($aggregateflag) {
                   4596:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4597: 			      $cdom,$cnum);
1.269     raeburn  4598:     }
1.803     raeburn  4599:     if (($sendupdate || $totchg) && (!$submitter)) {
1.798     raeburn  4600:         if ((ref($needpb) eq 'HASH') &&
                   4601:             (keys(%{$needpb}))) {
1.802     raeburn  4602:             &process_passbacks('handgrade',[$symb],$cdom,$cnum,$domain,$stuname,$usec,\%weights,
1.798     raeburn  4603:                                \%awardeds,\%excuseds,$needpb,$skip_passback,$pbsave);
                   4604:         }
                   4605:     }
1.803     raeburn  4606:     return ('',$pts,$wgt,$totchg,$sendupdate);
1.726     raeburn  4607: }
                   4608: 
                   4609: sub makehidden {
1.728     raeburn  4610:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  4611:     return unless (ref($record) eq 'HASH');
                   4612:     my %modified;
                   4613:     my $numchanged = 0;
                   4614:     if (exists($record->{$version.':keys'})) {
                   4615:         my $partsregexp = $parts;
                   4616:         $partsregexp =~ s/,/|/g;
                   4617:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   4618:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   4619:                  my $item = $1;
                   4620:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   4621:                      $modified{$key} = $record->{$version.':'.$key};
                   4622:                  }
                   4623:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   4624:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   4625:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   4626:                 $modified{$key} = $record->{$version.':'.$key};
                   4627:             }
                   4628:         }
                   4629:         if (keys(%modified)) {
                   4630:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  4631:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  4632:                 $numchanged ++;
                   4633:             }
                   4634:         }
                   4635:     }
                   4636:     return $numchanged;
1.36      ng       4637: }
1.322     albertel 4638: 
1.380     albertel 4639: sub check_and_remove_from_queue {
1.786     raeburn  4640:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 4641:     my @ungraded_parts;
                   4642:     foreach my $part (@{$parts}) {
                   4643: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   4644: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   4645: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   4646: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   4647: 		) {
1.786     raeburn  4648:             if ($queueable->{$part}) {
                   4649: 	        push(@ungraded_parts, $part);
                   4650:             }
1.380     albertel 4651: 	}
                   4652:     }
                   4653:     if ( !@ungraded_parts ) {
                   4654: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   4655: 					       $cnum,$domain,$stuname);
                   4656:     }
                   4657: }
                   4658: 
1.337     banghart 4659: sub handback_files {
                   4660:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  4661:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  4662:     my $res_error;
                   4663:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4664:     if ($res_error) {
                   4665:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   4666:         return;
                   4667:     }
1.654     raeburn  4668:     my @handedback;
                   4669:     my $file_msg;
1.375     albertel 4670:     my @part_response_id = &flatten_responseType($responseType);
                   4671:     foreach my $part_response_id (@part_response_id) {
                   4672:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   4673: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  4674:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   4675:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   4676:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   4677:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   4678:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 4679:                     my ($directory,$answer_file) = 
1.654     raeburn  4680:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 4681:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  4682: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 4683: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  4684:                     my $getpropath = 1;
1.773     raeburn  4685:                     my ($dir_list,$listerror) =
1.662     raeburn  4686:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   4687:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  4688: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   4689:                     # fix filename
1.355     banghart 4690:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   4691:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  4692:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 4693:             	                                $save_file_name);
1.337     banghart 4694:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  4695:                         $request->print('<br /><span class="LC_error">'.
                   4696:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  4697:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  4698:                                         '</span>');
1.356     banghart 4699:                     } else {
1.360     banghart 4700:                         # mark the file as read only
1.654     raeburn  4701:                         push(@handedback,$save_file_name);
1.367     albertel 4702: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   4703: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   4704: 			}
                   4705:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  4706: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 4707:                     }
1.686     bisitz   4708:                     $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 4709:                 }
                   4710:             }
                   4711:         }
1.654     raeburn  4712:     }
                   4713:     if (@handedback > 0) {
                   4714:         $request->print('<br />');
                   4715:         my @what = ($symb,$env{'request.course.id'},'handback');
                   4716:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   4717:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   4718:         my ($subject,$message);
                   4719:         if (scalar(@handedback) == 1) {
                   4720:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   4721:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   4722:         } else {
                   4723:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   4724:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   4725:         }
                   4726:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   4727:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   4728:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   4729:         my ($feedurl,$showsymb) =
                   4730:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   4731:         my $restitle = &Apache::lonnet::gettitle($symb);
                   4732:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   4733:         my $msgstatus =
                   4734:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   4735:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   4736:                  $restitle);
                   4737:         if ($msgstatus) {
                   4738:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   4739:         }
                   4740:     }
1.338     banghart 4741:     return;
1.337     banghart 4742: }
                   4743: 
1.418     albertel 4744: sub get_feedurl_and_symb {
                   4745:     my ($symb,$uname,$udom) = @_;
                   4746:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   4747:     $url = &Apache::lonnet::clutter($url);
                   4748:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   4749: 					$symb,$udom,$uname);
                   4750:     if ($encrypturl =~ /^yes$/i) {
                   4751: 	&Apache::lonenc::encrypted(\$url,1);
                   4752: 	&Apache::lonenc::encrypted(\$symb,1);
                   4753:     }
                   4754:     return ($url,$symb);
                   4755: }
                   4756: 
1.313     banghart 4757: sub get_submitted_files {
                   4758:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   4759:     my @files;
                   4760:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   4761:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   4762:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   4763:     	    push(@files,$file_url.$file);
                   4764:         }
                   4765:     }
                   4766:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   4767:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   4768:     }
                   4769:     return (\@files);
                   4770: }
1.322     albertel 4771: 
1.269     raeburn  4772: # ----------- Provides number of tries since last reset.
                   4773: sub get_num_tries {
                   4774:     my ($record,$last_reset,$part) = @_;
                   4775:     my $timestamp = '';
                   4776:     my $num_tries = 0;
                   4777:     if ($$record{'version'}) {
                   4778:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   4779:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   4780:                 $timestamp = $$record{$version.':timestamp'};
                   4781:                 if ($timestamp > $last_reset) {
                   4782:                     $num_tries ++;
                   4783:                 } else {
                   4784:                     last;
                   4785:                 }
                   4786:             }
                   4787:         }
                   4788:     }
                   4789:     return $num_tries;
                   4790: }
                   4791: 
                   4792: # ----------- Determine decrements required in aggregate totals 
                   4793: sub decrement_aggs {
                   4794:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   4795:     my %decrement = (
                   4796:                         attempts => 0,
                   4797:                         users => 0,
                   4798:                         correct => 0
                   4799:                     );
                   4800:     $decrement{'attempts'} = $aggtries;
                   4801:     if ($solvedstatus =~ /^correct/) {
                   4802:         $decrement{'correct'} = 1;
                   4803:     }
                   4804:     if ($aggtries == $totaltries) {
                   4805:         $decrement{'users'} = 1;
                   4806:     }
1.524     raeburn  4807:     foreach my $type (keys(%decrement)) {
1.269     raeburn  4808:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   4809:     }
                   4810:     return;
                   4811: }
                   4812: 
                   4813: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   4814: sub get_last_resets {
1.270     albertel 4815:     my ($symb,$courseid,$partids) =@_;
                   4816:     my %last_resets;
1.269     raeburn  4817:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   4818:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 4819:     my @keys;
                   4820:     foreach my $part (@{$partids}) {
                   4821: 	push(@keys,"$symb\0$part\0resettime");
                   4822:     }
                   4823:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   4824: 				     $cdom,$cname);
                   4825:     foreach my $part (@{$partids}) {
                   4826: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  4827:     }
1.270     albertel 4828:     return %last_resets;
1.269     raeburn  4829: }
                   4830: 
1.251     banghart 4831: # ----------- Handles creating versions for portfolio files as answers
                   4832: sub version_portfiles {
1.343     banghart 4833:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 4834:     my $version_parts = join('|',@$v_flag);
1.343     banghart 4835:     my @returned_keys;
1.255     banghart 4836:     my $parts = join('|', @$parts_graded);
1.277     albertel 4837:     foreach my $key (keys(%$record)) {
1.259     banghart 4838:         my $new_portfiles;
1.263     banghart 4839:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 4840:             my @versioned_portfiles;
1.367     albertel 4841:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  4842:             if (@portfiles) {
                   4843:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   4844:                                                       \@versioned_portfiles);
1.252     banghart 4845:             }
1.343     banghart 4846:             $$record{$key} = join(',',@versioned_portfiles);
                   4847:             push(@returned_keys,$key);
1.251     banghart 4848:         }
1.794     raeburn  4849:     }
                   4850:     return (@returned_keys);
1.305     banghart 4851: }
                   4852: 
1.44      ng       4853: #--------------------------------------------------------------------------------------
                   4854: #
                   4855: #-------------------------- Next few routines handles grading by section or whole class
                   4856: #
                   4857: #--- Javascript to handle grading by section or whole class
1.42      ng       4858: sub viewgrades_js {
                   4859:     my ($request) = shift;
                   4860: 
1.539     riegler  4861:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  4862:     &js_escape(\$alertmsg);
1.597     wenzelju 4863:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       4864:    function writePoint(partid,weight,point) {
1.125     ng       4865: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   4866: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       4867: 	if (point == "textval") {
1.125     ng       4868: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  4869: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4870: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       4871: 		var resetbox = false;
                   4872: 		for (var i=0; i<radioButton.length; i++) {
                   4873: 		    if (radioButton[i].checked) {
                   4874: 			textbox.value = i;
                   4875: 			resetbox = true;
                   4876: 		    }
                   4877: 		}
                   4878: 		if (!resetbox) {
                   4879: 		    textbox.value = "";
                   4880: 		}
                   4881: 		return;
                   4882: 	    }
1.109     matthew  4883: 	    if (parseFloat(point) > parseFloat(weight)) {
                   4884: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4885: 				   ") greater than the weight for the part. Accept?");
                   4886: 		if (resp == false) {
                   4887: 		    textbox.value = "";
                   4888: 		    return;
                   4889: 		}
                   4890: 	    }
1.42      ng       4891: 	    for (var i=0; i<radioButton.length; i++) {
                   4892: 		radioButton[i].checked=false;
1.109     matthew  4893: 		if (parseFloat(point) == i) {
1.42      ng       4894: 		    radioButton[i].checked=true;
                   4895: 		}
                   4896: 	    }
1.41      ng       4897: 
1.42      ng       4898: 	} else {
1.125     ng       4899: 	    textbox.value = parseFloat(point);
1.42      ng       4900: 	}
1.41      ng       4901: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4902: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 4903: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4904: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4905: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4906: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4907: 	    if (saveval != "correct") {
                   4908: 		scorename.value = point;
1.43      ng       4909: 		if (selname[0].selected != true) {
                   4910: 		    selname[0].selected = true;
                   4911: 		}
1.42      ng       4912: 	    }
                   4913: 	}
1.125     ng       4914: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       4915:     }
                   4916: 
                   4917:     function writeRadText(partid,weight) {
1.125     ng       4918: 	var selval   = document.classgrade["SELVAL_"+partid];
                   4919: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      4920:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       4921: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   4922: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       4923: 	    for (var i=0; i<radioButton.length; i++) {
                   4924: 		radioButton[i].checked=false;
                   4925: 
                   4926: 	    }
                   4927: 	    textbox.value = "";
                   4928: 
                   4929: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4930: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4931: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4932: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4933: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4934: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4935: 		if ((saveval != "correct") || override) {
1.42      ng       4936: 		    scorename.value = "";
1.125     ng       4937: 		    if (selval[1].selected) {
                   4938: 			selname[1].selected = true;
                   4939: 		    } else {
                   4940: 			selname[2].selected = true;
                   4941: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   4942: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   4943: 		    }
1.42      ng       4944: 		}
                   4945: 	    }
1.43      ng       4946: 	} else {
                   4947: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4948: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4949: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4950: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4951: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4952: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4953: 		if ((saveval != "correct") || override) {
1.125     ng       4954: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       4955: 		    selname[0].selected = true;
                   4956: 		}
                   4957: 	    }
                   4958: 	}	    
1.42      ng       4959:     }
                   4960: 
                   4961:     function changeSelect(partid,user) {
1.125     ng       4962: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4963: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       4964: 	var point  = textbox.value;
1.125     ng       4965: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       4966: 
1.109     matthew  4967: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4968: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       4969: 	    textbox.value = "";
                   4970: 	    return;
                   4971: 	}
1.109     matthew  4972: 	if (parseFloat(point) > parseFloat(weight)) {
                   4973: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4974: 			       ") greater than the weight of the part. Accept?");
                   4975: 	    if (resp == false) {
                   4976: 		textbox.value = "";
                   4977: 		return;
                   4978: 	    }
                   4979: 	}
1.42      ng       4980: 	selval[0].selected = true;
                   4981:     }
                   4982: 
                   4983:     function changeOneScore(partid,user) {
1.125     ng       4984: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4985: 	if (selval[1].selected || selval[2].selected) {
                   4986: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   4987: 	    if (selval[2].selected) {
                   4988: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   4989: 	    }
1.269     raeburn  4990:         }
1.42      ng       4991:     }
                   4992: 
                   4993:     function resetEntry(numpart) {
                   4994: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       4995: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   4996: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   4997: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   4998: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       4999: 	    for (var i=0; i<radioButton.length; i++) {
                   5000: 		radioButton[i].checked=false;
                   5001: 
                   5002: 	    }
                   5003: 	    textbox.value = "";
                   5004: 	    selval[0].selected = true;
                   5005: 
                   5006: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       5007: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 5008: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       5009: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   5010: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   5011: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   5012: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   5013: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   5014: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       5015: 		if (saveselval == "excused") {
1.43      ng       5016: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       5017: 		} else {
1.43      ng       5018: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       5019: 		}
                   5020: 	    }
1.41      ng       5021: 	}
1.42      ng       5022:     }
                   5023: 
1.41      ng       5024: VIEWJAVASCRIPT
1.42      ng       5025: }
                   5026: 
1.44      ng       5027: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       5028: sub viewgrades {
1.608     www      5029:     my ($request,$symb) = @_;
1.745     raeburn  5030:     my ($is_tool,$toolsymb);
                   5031:     if ($symb =~ /ext\.tool$/) {
                   5032:         $is_tool = 1;
                   5033:         $toolsymb = $symb;
                   5034:     }
1.42      ng       5035:     &viewgrades_js($request);
1.41      ng       5036: 
1.168     albertel 5037:     #need to make sure we have the correct data for later EXT calls, 
                   5038:     #thus invalidate the cache
                   5039:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5040:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5041:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5042:     &Apache::lonnet::clear_EXT_cache_status();
                   5043: 
1.398     albertel 5044:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       5045: 
                   5046:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 5047:     $result.=&jscriptNform($symb);
1.41      ng       5048: 
1.44      ng       5049:     #beginning of class grading form
1.442     banghart 5050:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       5051:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 5052: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       5053: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 5054: 	&build_section_inputs().
1.442     banghart 5055: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       5056: 
1.738     raeburn  5057:     #retrieve selected groups
                   5058:     my (@groups,$group_display);
                   5059:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   5060:     if (grep(/^all$/,@groups)) {
                   5061:         @groups = ('all');
                   5062:     } elsif (grep(/^none$/,@groups)) {
                   5063:         @groups = ('none');
                   5064:     } elsif (@groups > 0) {
                   5065:         $group_display = join(', ',@groups);
                   5066:     }
                   5067: 
                   5068:     my ($common_header,$specific_header,@sections,$section_display);
1.780     raeburn  5069:     if ($env{'request.course.sec'} ne '') {
                   5070:         @sections = ($env{'request.course.sec'});
                   5071:     } else {
                   5072:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   5073:     }
                   5074: 
                   5075: # Check if Save button should be usable
                   5076:     my $disabled = ' disabled="disabled"';
                   5077:     if ($perm{'mgr'}) {
                   5078:         if (grep(/^all$/,@sections)) {
                   5079:             undef($disabled);
                   5080:         } else {
                   5081:             foreach my $sec (@sections) {
                   5082:                 if (&canmodify($sec)) {
                   5083:                     undef($disabled);
                   5084:                     last;
                   5085:                 }
                   5086:             }
                   5087:         }
                   5088:     }
1.738     raeburn  5089:     if (grep(/^all$/,@sections)) {
                   5090:         @sections = ('all');
                   5091:         if ($group_display) {
                   5092:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   5093:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   5094:         } elsif (grep(/^none$/,@groups)) {
                   5095:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   5096:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   5097:         } else {
                   5098: 	    $common_header = &mt('Assign Common Grade to Class');
                   5099:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   5100:         }
                   5101:     } elsif (grep(/^none$/,@sections)) {
                   5102:         @sections = ('none');
                   5103:         if ($group_display) {
                   5104:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   5105:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   5106:         } elsif (grep(/^none$/,@groups)) {
                   5107:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   5108:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   5109:         } else {
                   5110:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   5111: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   5112:         }
                   5113:     } else {
                   5114:         $section_display = join (", ",@sections);
                   5115:         if ($group_display) {
                   5116:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   5117:                                  $section_display,$group_display);
                   5118:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   5119:                                    $section_display,$group_display);
                   5120:         } elsif (grep(/^none$/,@groups)) {
                   5121:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   5122:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   5123:         } else {
                   5124:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   5125: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   5126:         }
                   5127:     }
                   5128:     my %submit_types = &substatus_options();
                   5129:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   5130: 
                   5131:     if ($env{'form.submitonly'} eq 'all') {
                   5132:         $result.= '<h3>'.$common_header.'</h3>';
                   5133:     } else {
1.745     raeburn  5134:         my $text;
                   5135:         if ($is_tool) {
                   5136:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5137:         } else {
                   5138:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5139:         }
                   5140:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 5141:     }
1.738     raeburn  5142:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       5143:     #radio buttons/text box for assigning points for a section or class.
                   5144:     #handles different parts of a problem
1.582     raeburn  5145:     my $res_error;
                   5146:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   5147:     if ($res_error) {
                   5148:         return &navmap_errormsg();
                   5149:     }
1.42      ng       5150:     my %weight = ();
                   5151:     my $ctsparts = 0;
1.45      ng       5152:     my %seen = ();
1.745     raeburn  5153:     my @part_response_id;
                   5154:     if ($is_tool) {
                   5155:         @part_response_id = ([0,'']);
                   5156:     } else {
                   5157:         @part_response_id = &flatten_responseType($responseType);
                   5158:     }
1.375     albertel 5159:     foreach my $part_response_id (@part_response_id) {
                   5160:     	my ($partid,$respid) = @{ $part_response_id };
                   5161: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       5162: 	next if $seen{$partid};
                   5163: 	$seen{$partid}++;
1.42      ng       5164: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   5165: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   5166: 
1.324     albertel 5167: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 5168: 	my $radio.='<table border="0"><tr>';  
1.41      ng       5169: 	my $ctr = 0;
1.42      ng       5170: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 5171: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 5172: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 5173: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       5174: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   5175: 	    $ctr++;
                   5176: 	}
1.485     albertel 5177: 	$radio.='</tr></table>';
                   5178: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   5179: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 5180: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  5181: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   5182:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   5183:             '<select name="SELVAL_'.$partid.'" '.
                   5184:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   5185:                 $weight{$partid}.')"> '.
1.401     albertel 5186: 	    '<option selected="selected"> </option>'.
1.485     albertel 5187: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   5188: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   5189: 	    '</select></td>'.
                   5190:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   5191: 	$line.='<input type="hidden" name="partid_'.
                   5192: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   5193: 	$line.='<input type="hidden" name="weight_'.
                   5194: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   5195: 
                   5196: 	$result.=
                   5197: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   5198: 	    '<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 5199: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       5200: 	$ctsparts++;
1.41      ng       5201:     }
1.474     albertel 5202:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 5203: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 5204:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   5205: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       5206: 
1.44      ng       5207:     #table listing all the students in a section/class
                   5208:     #header of table
1.738     raeburn  5209:     if ($env{'form.submitonly'} eq 'all') {
                   5210:         $result.= '<h3>'.$specific_header.'</h3>';
                   5211:     } else {
1.745     raeburn  5212:         my $text;
                   5213:         if ($is_tool) {
                   5214:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5215:         } else {
                   5216:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5217:         }
                   5218:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  5219:     }
                   5220:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  5221: 	      &Apache::loncommon::start_data_table_header_row().
                   5222: 	      '<th>'.&mt('No.').'</th>'.
                   5223: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  5224:     my $partserror;
                   5225:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5226:     if ($partserror) {
                   5227:         return &navmap_errormsg();
                   5228:     }
1.324     albertel 5229:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  5230:     my @partids = ();
1.41      ng       5231:     foreach my $part (@parts) {
1.745     raeburn  5232: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  5233:         my $narrowtext = &mt('Tries');
                   5234: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  5235: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 5236: 	my ($partid) = &split_part_type($part);
1.524     raeburn  5237:         push(@partids,$partid);
1.628     www      5238: #
                   5239: # FIXME: Looks like $display looks at English text
                   5240: #
1.324     albertel 5241: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       5242: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 5243: 	    $result.='<th>'.
1.697     bisitz   5244: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   5245: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       5246: 	    next;
1.485     albertel 5247: 	    
1.207     albertel 5248: 	} else {
1.485     albertel 5249: 	    if ($display =~ /Problem Status/) {
                   5250: 		my $grade_status_mt = &mt('Grade Status');
                   5251: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   5252: 	    }
                   5253: 	    my $part_mt = &mt('Part:');
                   5254: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       5255: 	}
1.485     albertel 5256: 
1.474     albertel 5257: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       5258:     }
1.474     albertel 5259:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       5260: 
1.270     albertel 5261:     my %last_resets = 
                   5262: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  5263: 
1.41      ng       5264:     #get info for each student
1.44      ng       5265:     #list all the students - with points and grade status
1.738     raeburn  5266:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       5267:     my $ctr = 0;
1.294     albertel 5268:     foreach (sort 
                   5269: 	     {
                   5270: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5271: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5272: 		 }
                   5273: 		 return $a cmp $b;
                   5274: 	     } (keys(%$fullname))) {
1.324     albertel 5275: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  5276: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       5277:     }
1.474     albertel 5278:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       5279:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.780     raeburn  5280:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5281: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  5282:     if ($ctr == 0) {
1.442     banghart 5283:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  5284:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   5285:                 '<span class="LC_warning">';
                   5286:         if ($env{'form.submitonly'} eq 'all') {
                   5287:             if (grep(/^all$/,@sections)) {
                   5288:                 if (grep(/^all$/,@groups)) {
                   5289:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   5290:                                    $stu_status);
                   5291:                 } elsif (grep(/^none$/,@groups)) {
                   5292:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   5293:                                    $stu_status); 
                   5294:                 } else {
                   5295:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5296:                                    $group_display,$stu_status);
                   5297:                 }
                   5298:             } elsif (grep(/^none$/,@sections)) {
                   5299:                 if (grep(/^all$/,@groups)) {
                   5300:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   5301:                                    $stu_status);
                   5302:                 } elsif (grep(/^none$/,@groups)) {
                   5303:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   5304:                                    $stu_status);
                   5305:                 } else {
                   5306:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5307:                                    $group_display,$stu_status);
                   5308:                 }
                   5309:             } else {
                   5310:                 if (grep(/^all$/,@groups)) {
                   5311:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   5312:                                    $section_display,$stu_status);
                   5313:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  5314:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  5315:                                    $section_display,$stu_status);
                   5316:                 } else {
                   5317:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   5318:                                    $section_display,$group_display,$stu_status);
                   5319:                 }
                   5320:             }
                   5321:         } else {
                   5322:             if (grep(/^all$/,@sections)) {
                   5323:                 if (grep(/^all$/,@groups)) {
                   5324:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5325:                                    $stu_status,$submission_status);
                   5326:                 } elsif (grep(/^none$/,@groups)) {
                   5327:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5328:                                    $stu_status,$submission_status);
                   5329:                 } else {
                   5330:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5331:                                    $group_display,$stu_status,$submission_status);
                   5332:                 }
                   5333:             } elsif (grep(/^none$/,@sections)) {
                   5334:                 if (grep(/^all$/,@groups)) {
                   5335:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5336:                                    $stu_status,$submission_status);
                   5337:                 } elsif (grep(/^none$/,@groups)) {
                   5338:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5339:                                    $stu_status,$submission_status);
                   5340:                 } else {
                   5341:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5342:                                    $group_display,$stu_status,$submission_status);
                   5343:                 }
                   5344:             } else {
                   5345:                 if (grep(/^all$/,@groups)) {
                   5346: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5347: 	                           $section_display,$stu_status,$submission_status);
                   5348:                 } elsif (grep(/^none$/,@groups)) {
                   5349:                     $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.',
                   5350:                                    $section_display,$stu_status,$submission_status);
                   5351:                 } else {
                   5352:                     $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.',
                   5353:                                    $section_display,$group_display,$stu_status,$submission_status);
                   5354:                 }
                   5355:             }
                   5356:         }
                   5357: 	$result .= '</span><br />';
1.96      albertel 5358:     }
1.41      ng       5359:     return $result;
                   5360: }
                   5361: 
1.738     raeburn  5362: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       5363: sub viewstudentgrade {
1.745     raeburn  5364:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       5365:     my ($uname,$udom) = split(/:/,$student);
                   5366:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  5367:     my $submitonly = $env{'form.submitonly'};
                   5368:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   5369:         my %partstatus = ();
                   5370:         if (ref($parts) eq 'ARRAY') {
                   5371:             foreach my $apart (@{$parts}) {
                   5372:                 my ($part,$type) = &split_part_type($apart);
                   5373:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   5374:                 $status = 'nothing' if ($status eq '');
                   5375:                 $partstatus{$part}      = $status;
                   5376:                 my $subkey = "resource.$part.submitted_by";
                   5377:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   5378:             }
                   5379:             my $submitted = 0;
                   5380:             my $graded = 0;
                   5381:             my $incorrect = 0;
                   5382:             foreach my $key (keys(%partstatus)) {
                   5383:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   5384:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   5385:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   5386: 
                   5387:                 my $partid = (split(/\./,$key))[1];
                   5388:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   5389:                     $submitted = 0;
                   5390:                 }
                   5391:             }
                   5392:             return if (!$submitted && ($submitonly eq 'yes' ||
                   5393:                                        $submitonly eq 'incorrect' ||
                   5394:                                        $submitonly eq 'graded'));
                   5395:             return if (!$graded && ($submitonly eq 'graded'));
                   5396:             return if (!$incorrect && $submitonly eq 'incorrect');
                   5397:         }
                   5398:     }
                   5399:     if ($submitonly eq 'queued') {
                   5400:         my ($cdom,$cnum) = split(/_/,$courseid);
                   5401:         my %queue_status =
                   5402:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   5403:                                                     $udom,$uname);
                   5404:         return if (!defined($queue_status{'gradingqueue'}));
                   5405:     }
                   5406:     $$ctr++;
                   5407:     my %aggregates = ();
1.474     albertel 5408:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  5409: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   5410: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       5411: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 5412: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 5413: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 5414:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 5415:     foreach my $apart (@$parts) {
                   5416: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       5417: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 5418:         $result.='<td align="center">';
1.269     raeburn  5419:         my ($aggtries,$totaltries);
                   5420:         unless (exists($aggregates{$part})) {
1.270     albertel 5421: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   5422: 	    $aggtries = $totaltries;
1.269     raeburn  5423:             if ($$last_resets{$part}) {  
1.270     albertel 5424:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   5425: 					   $part);
                   5426:             }
1.269     raeburn  5427:             $result.='<input type="hidden" name="'.
                   5428:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   5429:             $result.='<input type="hidden" name="'.
                   5430:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   5431:             $aggregates{$part} = 1;
                   5432:         }
1.41      ng       5433: 	if ($type eq 'awarded') {
1.320     albertel 5434: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       5435: 	    $result.='<input type="hidden" name="'.
1.89      albertel 5436: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 5437: 	    $result.='<input type="text" name="'.
1.89      albertel 5438: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   5439:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       5440: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       5441: 	} elsif ($type eq 'solved') {
                   5442: 	    my ($status,$foo)=split(/_/,$score,2);
                   5443: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 5444: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 5445: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 5446: 	    $result.='&nbsp;<select name="'.
1.89      albertel 5447: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   5448:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 5449: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   5450: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   5451: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       5452: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       5453: 	} else {
                   5454: 	    $result.='<input type="hidden" name="'.
                   5455: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   5456: 		    "\n";
1.233     albertel 5457: 	    $result.='<input type="text" name="'.
1.122     ng       5458: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   5459: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       5460: 	}
                   5461:     }
1.474     albertel 5462:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       5463:     return $result;
1.38      ng       5464: }
                   5465: 
1.44      ng       5466: #--- change scores for all the students in a section/class
                   5467: #    record does not get update if unchanged
1.38      ng       5468: sub editgrades {
1.608     www      5469:     my ($request,$symb) = @_;
1.745     raeburn  5470:     my $toolsymb;
                   5471:     if ($symb =~ /ext\.tool$/) {
                   5472:         $toolsymb = $symb;
                   5473:     }
1.41      ng       5474: 
1.433     banghart 5475:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 5476:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  5477:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       5478: 
1.477     albertel 5479:     my $result= &Apache::loncommon::start_data_table().
                   5480: 	&Apache::loncommon::start_data_table_header_row().
                   5481: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   5482: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       5483:     my %scoreptr = (
                   5484: 		    'correct'  =>'correct_by_override',
                   5485: 		    'incorrect'=>'incorrect_by_override',
                   5486: 		    'excused'  =>'excused',
                   5487: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  5488:                     'credited' =>'credit_attempted',
1.43      ng       5489: 		    'nothing'  => '',
                   5490: 		    );
1.257     albertel 5491:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       5492: 
1.798     raeburn  5493:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5494:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5495:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   5496: 
1.44      ng       5497:     my (@partid);
                   5498:     my %weight = ();
1.54      albertel 5499:     my %columns = ();
1.44      ng       5500:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 5501: 
1.582     raeburn  5502:     my $partserror;
                   5503:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5504:     if ($partserror) {
                   5505:         return &navmap_errormsg();
                   5506:     }
1.54      albertel 5507:     my $header;
1.257     albertel 5508:     while ($ctr < $env{'form.totalparts'}) {
                   5509: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  5510: 	push(@partid,$partid);
1.257     albertel 5511: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       5512: 	$ctr++;
1.54      albertel 5513:     }
1.324     albertel 5514:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  5515:     my $totcolspan = 0;
1.54      albertel 5516:     foreach my $partid (@partid) {
1.478     albertel 5517: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   5518: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 5519: 	$columns{$partid}=2;
                   5520: 	foreach my $stores (@parts) {
                   5521: 	    my ($part,$type) = &split_part_type($stores);
                   5522: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   5523: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  5524: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  5525: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  5526:             my $narrowtext = &mt('Tries');
                   5527: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   5528: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   5529: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 5530: 	    $columns{$partid}+=2;
                   5531: 	}
1.748     raeburn  5532:         $totcolspan += $columns{$partid};
1.54      albertel 5533:     }
                   5534:     foreach my $partid (@partid) {
1.324     albertel 5535: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 5536: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   5537: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   5538: 	    '</th>';
1.54      albertel 5539: 
1.44      ng       5540:     }
1.477     albertel 5541:     $result .= &Apache::loncommon::end_data_table_header_row().
                   5542: 	&Apache::loncommon::start_data_table_header_row().
                   5543: 	$header.
                   5544: 	&Apache::loncommon::end_data_table_header_row();
                   5545:     my @noupdate;
1.126     ng       5546:     my ($updateCtr,$noupdateCtr) = (1,1);
1.798     raeburn  5547:     my ($got_types,%queueable,%pbsave,%skip_passback);
1.257     albertel 5548:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   5549: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 5550: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       5551: 	my %newrecord;
                   5552: 	my $updateflag = 0;
1.108     albertel 5553: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  5554: 	my $canmodify = &canmodify($usec);
                   5555: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   5556: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   5557: 	if (!$canmodify) {
1.477     albertel 5558: 	    push(@noupdate,
1.748     raeburn  5559: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   5560: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 5561: 	    next;
                   5562: 	}
1.269     raeburn  5563:         my %aggregate = ();
                   5564:         my $aggregateflag = 0;
1.281     albertel 5565: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.798     raeburn  5566:         my (%weights,%awardeds,%excuseds);
1.44      ng       5567: 	foreach (@partid) {
1.257     albertel 5568: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 5569: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   5570: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 5571: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   5572: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 5573: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   5574: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.798     raeburn  5575:             $awardeds{$symb}{$_} = $partial;
1.44      ng       5576: 	    my $score;
                   5577: 	    if ($partial eq '') {
1.257     albertel 5578: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       5579: 	    } elsif ($partial > 0) {
                   5580: 		$score = 'correct_by_override';
                   5581: 	    } elsif ($partial == 0) {
                   5582: 		$score = 'incorrect_by_override';
                   5583: 	    }
1.257     albertel 5584: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       5585: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   5586: 
1.292     albertel 5587: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   5588: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5589: 	    if ($dropMenu eq 'reset status' &&
                   5590: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 5591: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       5592: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   5593: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 5594: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       5595: 		$updateflag = 1;
1.269     raeburn  5596:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   5597:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   5598:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   5599:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   5600:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5601:                     $aggregateflag = 1;
                   5602:                 }
1.139     albertel 5603: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   5604: 		$updateflag = 1;
                   5605: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   5606: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   5607: 		$rec_update++;
1.125     ng       5608: 	    }
                   5609: 
1.93      albertel 5610: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       5611: 		'<td align="center">'.$awarded.
                   5612: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 5613: 
1.54      albertel 5614: 
                   5615: 	    my $partid=$_;
1.798     raeburn  5616:             if ($score eq 'excused') {
                   5617:                 $excuseds{$symb}{$partid} = 1;
                   5618:             } else {
                   5619:                 $excuseds{$symb}{$partid} = '';
                   5620:             }
1.54      albertel 5621: 	    foreach my $stores (@parts) {
                   5622: 		my ($part,$type) = &split_part_type($stores);
                   5623: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   5624: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 5625: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   5626: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 5627: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   5628: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 5629: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 5630: 		    $updateflag=1;
                   5631: 		}
1.93      albertel 5632: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 5633: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   5634: 	    }
1.44      ng       5635: 	}
1.477     albertel 5636: 	$line.="\n";
1.301     albertel 5637: 
1.44      ng       5638: 	if ($updateflag) {
                   5639: 	    $count++;
1.257     albertel 5640: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 5641: 				    $udom,$uname);
1.301     albertel 5642: 
                   5643: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   5644: 					      $cnum,$udom,$uname)) {
                   5645: 		# need to figure out if should be in queue.
                   5646: 		my %record =  
                   5647: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   5648: 					     $udom,$uname);
                   5649: 		my $all_graded = 1;
                   5650: 		my $none_graded = 1;
1.786     raeburn  5651:                 unless ($got_types) {
                   5652:                     my $error;
                   5653:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   5654:                     unless ($error) {
                   5655:                         foreach my $part (@parts) {
                   5656:                             if (ref($resptype->{$part}) eq 'HASH') {
                   5657:                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   5658:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   5659:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   5660:                                         $queueable{$part} = 1;
                   5661:                                         last;
                   5662:                                     }
                   5663:                                 }
                   5664:                             }
                   5665:                         }
                   5666:                     }
                   5667:                     $got_types = 1;
                   5668:                 }
1.301     albertel 5669: 		foreach my $part (@parts) {
1.786     raeburn  5670:                     if ($queueable{$part}) {
                   5671: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   5672: 			    $all_graded = 0;
                   5673: 		        } else {
                   5674: 			    $none_graded = 0;
                   5675: 		        }
1.301     albertel 5676: 		    }
1.786     raeburn  5677:                 }
1.301     albertel 5678: 		if ($all_graded || $none_graded) {
                   5679: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   5680: 							   $symb,$cdom,$cnum,
                   5681: 							   $udom,$uname);
                   5682: 		}
                   5683: 	    }
                   5684: 
1.477     albertel 5685: 	    $result.=&Apache::loncommon::start_data_table_row().
                   5686: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   5687: 		&Apache::loncommon::end_data_table_row();
1.126     ng       5688: 	    $updateCtr++;
1.798     raeburn  5689:             if (keys(%needpb)) {
                   5690:                 $weights{$symb} = \%weight;
1.802     raeburn  5691:                 &process_passbacks('editgrades',[$symb],$cdom,$cnum,$udom,$uname,$usec,\%weights,
1.798     raeburn  5692:                                    \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   5693:             }
1.93      albertel 5694: 	} else {
1.477     albertel 5695: 	    push(@noupdate,
                   5696: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       5697: 	    $noupdateCtr++;
1.44      ng       5698: 	}
1.269     raeburn  5699:         if ($aggregateflag) {
                   5700:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 5701: 				  $cdom,$cnum);
1.269     raeburn  5702:         }
1.93      albertel 5703:     }
1.477     albertel 5704:     if (@noupdate) {
1.748     raeburn  5705:         my $numcols=$totcolspan+2;
1.477     albertel 5706: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 5707: 	    '<td align="center" colspan="'.$numcols.'">'.
                   5708: 	    &mt('No Changes Occurred For the Students Below').
                   5709: 	    '</td>'.
1.477     albertel 5710: 	    &Apache::loncommon::end_data_table_row();
                   5711: 	foreach my $line (@noupdate) {
                   5712: 	    $result.=
                   5713: 		&Apache::loncommon::start_data_table_row().
                   5714: 		$line.
                   5715: 		&Apache::loncommon::end_data_table_row();
                   5716: 	}
1.44      ng       5717:     }
1.614     www      5718:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 5719:     my $msg = '<p><b>'.
                   5720: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   5721: 	    $rec_update,$count).'</b><br />'.
                   5722: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   5723: 	'</b></p>';
1.44      ng       5724:     return $title.$msg.$result;
1.5       albertel 5725: }
1.54      albertel 5726: 
                   5727: sub split_part_type {
                   5728:     my ($partstr) = @_;
                   5729:     my ($temp,@allparts)=split(/_/,$partstr);
                   5730:     my $type=pop(@allparts);
1.439     albertel 5731:     my $part=join('_',@allparts);
1.54      albertel 5732:     return ($part,$type);
                   5733: }
                   5734: 
1.44      ng       5735: #------------- end of section for handling grading by section/class ---------
                   5736: #
                   5737: #----------------------------------------------------------------------------
                   5738: 
1.5       albertel 5739: 
1.44      ng       5740: #----------------------------------------------------------------------------
                   5741: #
                   5742: #-------------------------- Next few routines handles grading by csv upload
                   5743: #
                   5744: #--- Javascript to handle csv upload
1.27      albertel 5745: sub csvupload_javascript_reverse_associate {
1.743     raeburn  5746:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5747:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5748:   &js_escape(\$error1);
                   5749:   &js_escape(\$error2);
1.27      albertel 5750:   return(<<ENDPICK);
                   5751:   function verify(vf) {
                   5752:     var foundsomething=0;
                   5753:     var founduname=0;
1.243     albertel 5754:     var foundID=0;
1.743     raeburn  5755:     var foundclicker=0;
1.27      albertel 5756:     for (i=0;i<=vf.nfields.value;i++) {
                   5757:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5758:       if (i==0 && tw!=0) { foundID=1; }
                   5759:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  5760:       if (i==2 && tw!=0) { foundclicker=1; }
                   5761:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 5762:     }
1.743     raeburn  5763:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 5764: 	alert('$error1');
                   5765: 	return;
1.27      albertel 5766:     }
                   5767:     if (foundsomething==0) {
1.246     albertel 5768: 	alert('$error2');
                   5769: 	return;
1.27      albertel 5770:     }
                   5771:     vf.submit();
                   5772:   }
                   5773:   function flip(vf,tf) {
                   5774:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5775:     var i;
                   5776:     for (i=0;i<=vf.nfields.value;i++) {
                   5777:       //can not pick the same destination field for both name and domain
                   5778:       if (((i ==0)||(i ==1)) && 
                   5779:           ((tf==0)||(tf==1)) && 
                   5780:           (i!=tf) &&
                   5781:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5782:         eval('vf.f'+i+'.selectedIndex=0;')
                   5783:       }
                   5784:     }
                   5785:   }
                   5786: ENDPICK
                   5787: }
                   5788: 
                   5789: sub csvupload_javascript_forward_associate {
1.743     raeburn  5790:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5791:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5792:   &js_escape(\$error1);
                   5793:   &js_escape(\$error2);
1.27      albertel 5794:   return(<<ENDPICK);
                   5795:   function verify(vf) {
                   5796:     var foundsomething=0;
                   5797:     var founduname=0;
1.243     albertel 5798:     var foundID=0;
1.743     raeburn  5799:     var foundclicker=0;
1.27      albertel 5800:     for (i=0;i<=vf.nfields.value;i++) {
                   5801:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5802:       if (tw==1) { foundID=1; }
                   5803:       if (tw==2) { founduname=1; }
1.745     raeburn  5804:       if (tw==3) { foundclicker=1; }
1.743     raeburn  5805:       if (tw>4) { foundsomething=1; }
1.27      albertel 5806:     }
1.743     raeburn  5807:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 5808: 	alert('$error1');
                   5809: 	return;
1.27      albertel 5810:     }
                   5811:     if (foundsomething==0) {
1.246     albertel 5812: 	alert('$error2');
                   5813: 	return;
1.27      albertel 5814:     }
                   5815:     vf.submit();
                   5816:   }
                   5817:   function flip(vf,tf) {
                   5818:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5819:     var i;
                   5820:     //can not pick the same destination field twice
                   5821:     for (i=0;i<=vf.nfields.value;i++) {
                   5822:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5823:         eval('vf.f'+i+'.selectedIndex=0;')
                   5824:       }
                   5825:     }
                   5826:   }
                   5827: ENDPICK
                   5828: }
                   5829: 
1.26      albertel 5830: sub csvuploadmap_header {
1.324     albertel 5831:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       5832:     my $javascript;
1.257     albertel 5833:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       5834: 	$javascript=&csvupload_javascript_reverse_associate();
                   5835:     } else {
                   5836: 	$javascript=&csvupload_javascript_forward_associate();
                   5837:     }
1.45      ng       5838: 
1.418     albertel 5839:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      5840:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   5841:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   5842:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   5843:     my $reverse=&mt("Reverse Association");
1.41      ng       5844:     $request->print(<<ENDPICK);
1.632     www      5845: <br />
                   5846: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 5847: <input type="hidden" name="associate"  value="" />
                   5848: <input type="hidden" name="phase"      value="three" />
                   5849: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 5850: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   5851: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 5852: <input type="hidden" name="upfile_associate" 
1.257     albertel 5853:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 5854: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 5855: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 5856: <hr />
                   5857: ENDPICK
1.597     wenzelju 5858:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       5859:     return '';
1.26      albertel 5860: 
                   5861: }
                   5862: 
                   5863: sub csvupload_fields {
1.582     raeburn  5864:     my ($symb,$errorref) = @_;
1.745     raeburn  5865:     my $toolsymb;
                   5866:     if ($symb =~ /ext\.tool$/) {
                   5867:         $toolsymb = $symb;
                   5868:     }
1.582     raeburn  5869:     my (@parts) = &getpartlist($symb,$errorref);
                   5870:     if (ref($errorref)) {
                   5871:         if ($$errorref) {
                   5872:             return;
                   5873:         }
                   5874:     }
                   5875: 
1.556     weissno  5876:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 5877: 		['username','Student Username'],
1.743     raeburn  5878: 		['clicker','Clicker ID'],
1.243     albertel 5879: 		['domain','Student Domain']);
1.324     albertel 5880:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       5881:     foreach my $part (sort(@parts)) {
                   5882: 	my @datum;
1.745     raeburn  5883: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       5884: 	my $name=$part;
1.745     raeburn  5885: 	if (!$display) { $display = $name; }
1.41      ng       5886: 	@datum=($name,$display);
1.244     albertel 5887: 	if ($name=~/^stores_(.*)_awarded/) {
                   5888: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   5889: 	}
1.41      ng       5890: 	push(@fields,\@datum);
                   5891:     }
                   5892:     return (@fields);
1.26      albertel 5893: }
                   5894: 
                   5895: sub csvuploadmap_footer {
1.41      ng       5896:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   5897:     my $buttontext = &mt('Assign Grades');
1.41      ng       5898:     $request->print(<<ENDPICK);
1.26      albertel 5899: </table>
                   5900: <input type="hidden" name="nfields" value="$i" />
                   5901: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   5902: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 5903: </form>
                   5904: ENDPICK
                   5905: }
                   5906: 
1.283     albertel 5907: sub checkforfile_js {
1.638     www      5908:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  5909:     &js_escape(\$alertmsg);
1.597     wenzelju 5910:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       5911:     function checkUpload(formname) {
                   5912: 	if (formname.upfile.value == "") {
1.539     riegler  5913: 	    alert("$alertmsg");
1.86      ng       5914: 	    return false;
                   5915: 	}
                   5916: 	formname.submit();
                   5917:     }
                   5918: CSVFORMJS
1.283     albertel 5919:     return $result;
                   5920: }
                   5921: 
                   5922: sub upcsvScores_form {
1.608     www      5923:     my ($request,$symb) = @_;
1.283     albertel 5924:     if (!$symb) {return '';}
                   5925:     my $result=&checkforfile_js();
1.632     www      5926:     $result.=&Apache::loncommon::start_data_table().
                   5927:              &Apache::loncommon::start_data_table_header_row().
                   5928:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   5929:              &Apache::loncommon::end_data_table_header_row().
                   5930:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      5931:     my $upload=&mt("Upload Scores");
1.86      ng       5932:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 5933:     my $ignore=&mt('Ignore First Line');
1.418     albertel 5934:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       5935:     $result.=<<ENDUPFORM;
1.106     albertel 5936: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       5937: <input type="hidden" name="symb" value="$symb" />
                   5938: <input type="hidden" name="command" value="csvuploadmap" />
                   5939: $upfile_select
1.589     bisitz   5940: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       5941: </form>
                   5942: ENDUPFORM
1.370     www      5943:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      5944:                            &mt("How do I create a CSV file from a spreadsheet")).
                   5945:              '</td>'.
                   5946:             &Apache::loncommon::end_data_table_row().
                   5947:             &Apache::loncommon::end_data_table();
1.86      ng       5948:     return $result;
                   5949: }
                   5950: 
                   5951: 
1.26      albertel 5952: sub csvuploadmap {
1.768     raeburn  5953:     my ($request,$symb) = @_;
1.41      ng       5954:     if (!$symb) {return '';}
1.72      ng       5955: 
1.41      ng       5956:     my $datatoken;
1.257     albertel 5957:     if (!$env{'form.datatoken'}) {
1.41      ng       5958: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 5959:     } else {
1.742     raeburn  5960: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5961:         if ($datatoken ne '') {
                   5962: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5963:         }
1.26      albertel 5964:     }
1.41      ng       5965:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 5966:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       5967:     my ($i,$keyfields);
                   5968:     if (@records) {
1.582     raeburn  5969:         my $fieldserror;
                   5970: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   5971:         if ($fieldserror) {
                   5972:             $request->print(&navmap_errormsg());
                   5973:             return;
                   5974:         }
1.257     albertel 5975: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       5976: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   5977: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   5978: 							  \@fields);
                   5979: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   5980: 	    chop($keyfields);
                   5981: 	} else {
                   5982: 	    unshift(@fields,['none','']);
                   5983: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   5984: 							    \@fields);
1.311     banghart 5985:             foreach my $rec (@records) {
                   5986:                 my %temp = &Apache::loncommon::record_sep($rec);
                   5987:                 if (%temp) {
                   5988:                     $keyfields=join(',',sort(keys(%temp)));
                   5989:                     last;
                   5990:                 }
                   5991:             }
1.41      ng       5992: 	}
                   5993:     }
                   5994:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       5995: 
1.41      ng       5996:     return '';
1.27      albertel 5997: }
                   5998: 
1.246     albertel 5999: sub csvuploadoptions {
1.608     www      6000:     my ($request,$symb)= @_;
1.632     www      6001:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 6002:     $request->print(<<ENDPICK);
                   6003: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   6004: <input type="hidden" name="command"    value="csvuploadassign" />
                   6005: <p>
                   6006: <label>
                   6007:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      6008:    $overwrite
1.246     albertel 6009: </label>
                   6010: </p>
                   6011: ENDPICK
                   6012:     my %fields=&get_fields();
                   6013:     if (!defined($fields{'domain'})) {
1.257     albertel 6014: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      6015: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 6016:     }
1.257     albertel 6017:     foreach my $key (sort(keys(%env))) {
1.246     albertel 6018: 	if ($key !~ /^form\.(.*)$/) { next; }
                   6019: 	my $cleankey=$1;
                   6020: 	if ($cleankey eq 'command') { next; }
                   6021: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 6022: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 6023:     }
                   6024:     # FIXME do a check for any duplicated user ids...
                   6025:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   6026:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 6027: <hr /></form>'."\n");
1.246     albertel 6028:     return '';
                   6029: }
                   6030: 
                   6031: sub get_fields {
                   6032:     my %fields;
1.257     albertel 6033:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   6034:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   6035: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   6036: 	    if ($env{'form.f'.$i} ne 'none') {
                   6037: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       6038: 	    }
                   6039: 	} else {
1.257     albertel 6040: 	    if ($env{'form.f'.$i} ne 'none') {
                   6041: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       6042: 	    }
                   6043: 	}
1.27      albertel 6044:     }
1.246     albertel 6045:     return %fields;
                   6046: }
                   6047: 
                   6048: sub csvuploadassign {
1.766     raeburn  6049:     my ($request,$symb) = @_;
1.246     albertel 6050:     if (!$symb) {return '';}
1.345     bowersj2 6051:     my $error_msg = '';
1.742     raeburn  6052:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   6053:     if ($datatoken ne '') { 
                   6054:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   6055:     }
1.246     albertel 6056:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   6057:     my %fields=&get_fields();
1.257     albertel 6058:     my $courseid=$env{'request.course.id'};
1.798     raeburn  6059:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6060:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.97      albertel 6061:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 6062:     my @notallowed;
1.41      ng       6063:     my @skipped;
1.657     raeburn  6064:     my @warnings;
1.41      ng       6065:     my $countdone=0;
1.798     raeburn  6066:     my @parts;
                   6067:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   6068:     my $passback;
                   6069:     if (keys(%needpb)) {
                   6070:         $passback = 1;
                   6071:         my $navmap = Apache::lonnavmaps::navmap->new();
                   6072:         if (ref($navmap)) {
                   6073:             my $res = $navmap->getBySymb($symb);
                   6074:             if (ref($res)) {
                   6075:                 my $partlist = $res->parts();
                   6076:                 if (ref($partlist) eq 'ARRAY') {
                   6077:                     @parts = sort(@{$partlist});
                   6078:                 }
                   6079:             }
                   6080:         } else {
                   6081:             return &navmap_errormsg();
                   6082:         }
                   6083:     }
                   6084:     my (%skip_passback,%pbsave,%weights,%awardeds,%excuseds);
                   6085: 
1.41      ng       6086:     foreach my $grade (@gradedata) {
                   6087: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 6088: 	my $domain;
                   6089: 	if ($entries{$fields{'domain'}}) {
                   6090: 	    $domain=$entries{$fields{'domain'}};
                   6091: 	} else {
1.257     albertel 6092: 	    $domain=$env{'form.default_domain'};
1.246     albertel 6093: 	}
1.243     albertel 6094: 	$domain=~s/\s//g;
1.41      ng       6095: 	my $username=$entries{$fields{'username'}};
1.160     albertel 6096: 	$username=~s/\s//g;
1.243     albertel 6097: 	if (!$username) {
                   6098: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 6099: 	    $id=~s/\s//g;
1.737     raeburn  6100:             if ($id ne '') {
                   6101: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   6102: 	        $username=$ids{$id};
                   6103:             } else {
                   6104:                 if ($entries{$fields{'clicker'}}) {
                   6105:                     my $clicker = $entries{$fields{'clicker'}};
                   6106:                     $clicker=~s/\s//g;
                   6107:                     if ($clicker ne '') {
                   6108:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   6109:                         if ($clickers{$clicker} ne '') {  
                   6110:                             my $match = 0;
                   6111:                             my @inclass;
                   6112:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   6113:                                 if (exists($$classlist{"$poss:$domain"})) {
                   6114:                                     $username = $poss;
                   6115:                                     push(@inclass,$poss);
                   6116:                                     $match ++;
                   6117:                                     
                   6118:                                 }
                   6119:                             }
                   6120:                             if ($match > 1) {
                   6121:                                 undef($username); 
                   6122:                                 $request->print('<p class="LC_warning">'.
                   6123:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   6124:                                                 $clicker,join(', ',@inclass)).'</p>');
                   6125:                             }
                   6126:                         }
                   6127:                     }
                   6128:                 }
                   6129:             }
1.243     albertel 6130: 	}
1.41      ng       6131: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 6132: 	    my $id=$entries{$fields{'ID'}};
                   6133: 	    $id=~s/\s//g;
1.737     raeburn  6134:             my $clicker = $entries{$fields{'clicker'}};
                   6135:             $clicker=~s/\s//g;
                   6136:             if ($clicker) {
                   6137:                 push(@skipped,"$clicker:$domain");
                   6138: 	    } elsif ($id) {
1.247     albertel 6139: 		push(@skipped,"$id:$domain");
                   6140: 	    } else {
                   6141: 		push(@skipped,"$username:$domain");
                   6142: 	    }
1.41      ng       6143: 	    next;
                   6144: 	}
1.108     albertel 6145: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 6146: 	if (!&canmodify($usec)) {
                   6147: 	    push(@notallowed,"$username:$domain");
                   6148: 	    next;
                   6149: 	}
1.244     albertel 6150: 	my %points;
1.41      ng       6151: 	my %grades;
                   6152: 	foreach my $dest (keys(%fields)) {
1.244     albertel 6153: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   6154: 		$dest eq 'domain') { next; }
                   6155: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   6156: 	    if ($dest=~/stores_(.*)_points/) {
                   6157: 		my $part=$1;
                   6158: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6159: 					      $symb,$domain,$username);
1.798     raeburn  6160:                 $weights{$symb}{$part} = $wgt;
1.345     bowersj2 6161:                 if ($wgt) {
                   6162:                     $entries{$fields{$dest}}=~s/\s//g;
                   6163:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.798     raeburn  6164:                     if ($passback) {
                   6165:                         $awardeds{$symb}{$part} = $pcr;
                   6166:                         $excuseds{$symb}{$part} = '';
                   6167:                     }
1.463     albertel 6168:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   6169:                                           : 'correct_by_override';
1.638     www      6170:                     if ($pcr>1) {
1.657     raeburn  6171:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      6172:                     }
1.345     bowersj2 6173:                     $grades{"resource.$part.awarded"}=$pcr;
                   6174:                     $grades{"resource.$part.solved"}=$award;
                   6175:                     $points{$part}=1;
                   6176:                 } else {
                   6177:                     $error_msg = "<br />" .
                   6178:                         &mt("Some point values were assigned"
                   6179:                             ." for problems with a weight "
                   6180:                             ."of zero. These values were "
                   6181:                             ."ignored.");
                   6182:                 }
1.244     albertel 6183: 	    } else {
                   6184: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   6185: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   6186: 		my $store_key=$dest;
1.798     raeburn  6187:                 if ($passback) {
                   6188:                     if ($store_key=~/stores_(.*)_(awarded|solved)/) {
                   6189:                         my ($part,$key) = ($1,$2);
                   6190:                         unless ((ref($weights{$symb}) eq 'HASH') && (exists($weights{$symb}{$part}))) {
                   6191:                             $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6192:                                                                           $symb,$domain,$username);
                   6193:                         }
                   6194:                         if ($key eq 'awarded') {
                   6195:                             $awardeds{$symb}{$part} = $entries{$fields{$dest}};
                   6196:                         } elsif ($key eq 'solved') {
                   6197:                             if ($entries{$fields{$dest}} =~ /^excused/) {
                   6198:                                 $excuseds{$symb}{$part} = 1;
                   6199:                             }
                   6200:                         }
                   6201:                     }
                   6202:                 }
1.244     albertel 6203: 		$store_key=~s/^stores/resource/;
                   6204: 		$store_key=~s/_/\./g;
                   6205: 		$grades{$store_key}=$entries{$fields{$dest}};
                   6206: 	    }
1.41      ng       6207: 	}
1.766     raeburn  6208: 	if (! %grades) {
1.508     www      6209:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   6210:         } else {
                   6211: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   6212: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 6213: 					   $env{'request.course.id'},
                   6214: 					   $domain,$username);
1.508     www      6215: 	   if ($result eq 'ok') {
1.627     www      6216: # Successfully stored
1.508     www      6217: 	      $request->print('.');
1.627     www      6218: # Remove from grading queue
1.798     raeburn  6219:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,$cnum,
1.801     raeburn  6220: 						     $domain,$username);
1.627     www      6221:               $countdone++;
1.798     raeburn  6222:               if ($passback) {
                   6223:                   my @parts_in_upload;
                   6224:                   if (ref($weights{$symb}) eq 'HASH') {
                   6225:                       @parts_in_upload = sort(keys(%{$weights{$symb}}));
                   6226:                   }
                   6227:                   my @diffs = &Apache::loncommon::compare_arrays(\@parts_in_upload,\@parts);
                   6228:                   if (@diffs > 0) {
                   6229:                       my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$username);
                   6230:                       foreach my $part (@parts) {
                   6231:                           next if (grep(/^\Q$part\E$/,@parts_in_upload));
                   6232:                           $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6233:                                                                         $symb,$domain,$username);
                   6234:                           if ($record{"resource.$part.solved"} =~/^excused/) {
                   6235:                               $excuseds{$symb}{$part} = 1;
                   6236:                           } else {
                   6237:                               $excuseds{$symb}{$part} = '';
                   6238:                           }
                   6239:                           $awardeds{$symb}{$part} = $record{"resource.$part.awarded"};
                   6240:                       }
                   6241:                   }
1.802     raeburn  6242:                   &process_passbacks('csvupload',[$symb],$cdom,$cnum,$domain,$username,$usec,\%weights,
1.798     raeburn  6243:                                      \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   6244:               }
1.627     www      6245:            } else {
1.508     www      6246: 	      $request->print("<p><span class=\"LC_error\">".
                   6247:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   6248:                                   "$username:$domain",$result)."</span></p>");
                   6249: 	   }
                   6250: 	   $request->rflush();
                   6251:         }
1.41      ng       6252:     }
1.570     www      6253:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  6254:     if (@warnings) {
                   6255:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   6256:         $request->print(join(', ',@warnings));
                   6257:     }
1.41      ng       6258:     if (@skipped) {
1.571     www      6259: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   6260:         $request->print(join(', ',@skipped));
1.106     albertel 6261:     }
                   6262:     if (@notallowed) {
1.571     www      6263: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   6264: 	$request->print(join(', ',@notallowed));
1.41      ng       6265:     }
1.106     albertel 6266:     $request->print("<br />\n");
1.345     bowersj2 6267:     return $error_msg;
1.26      albertel 6268: }
1.44      ng       6269: #------------- end of section for handling csv file upload ---------
                   6270: #
                   6271: #-------------------------------------------------------------------
                   6272: #
1.122     ng       6273: #-------------- Next few routines handle grading by page/sequence
1.72      ng       6274: #
                   6275: #--- Select a page/sequence and a student to grade
1.68      ng       6276: sub pickStudentPage {
1.608     www      6277:     my ($request,$symb) = @_;
1.68      ng       6278: 
1.539     riegler  6279:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  6280:     &js_escape(\$alertmsg);
1.597     wenzelju 6281:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       6282: 
                   6283: function checkPickOne(formname) {
1.76      ng       6284:     if (radioSelection(formname.student) == null) {
1.539     riegler  6285: 	alert("$alertmsg");
1.68      ng       6286: 	return;
                   6287:     }
1.125     ng       6288:     ptr = pullDownSelection(formname.selectpage);
                   6289:     formname.page.value = formname["page"+ptr].value;
                   6290:     formname.title.value = formname["title"+ptr].value;
1.68      ng       6291:     formname.submit();
                   6292: }
                   6293: 
                   6294: LISTJAVASCRIPT
1.118     ng       6295:     &commonJSfunctions($request);
1.608     www      6296: 
1.257     albertel 6297:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6298:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6299:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  6300:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       6301: 
1.398     albertel 6302:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 6303: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       6304: 
1.80      ng       6305:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  6306:     my $map_error;
                   6307:     my ($titles,$symbx) = &getSymbMap($map_error);
                   6308:     if ($map_error) {
                   6309:         $request->print(&navmap_errormsg());
                   6310:         return; 
                   6311:     }
1.137     albertel 6312:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   6313: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   6314: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   6315: 
                   6316:     # Collection of hidden fields
1.70      ng       6317:     my $ctr=0;
1.68      ng       6318:     foreach (@$titles) {
1.700     bisitz   6319:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   6320:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   6321:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   6322:         $ctr++;
1.68      ng       6323:     }
1.700     bisitz   6324:     $result.='<input type="hidden" name="page" />'."\n".
                   6325:         '<input type="hidden" name="title" />'."\n";
                   6326: 
                   6327:     $result.=&build_section_inputs();
                   6328:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   6329:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   6330: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   6331: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 6332: 
1.700     bisitz   6333:     # Show grading options
                   6334:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   6335:     my $select = '<select name="selectpage">'."\n";
1.70      ng       6336:     $ctr=0;
                   6337:     foreach (@$titles) {
                   6338: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   6339: 	$select.='<option value="'.$ctr.'"'.
                   6340: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   6341: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       6342: 	$ctr++;
                   6343:     }
1.700     bisitz   6344:     $select.= '</select>';
1.68      ng       6345: 
1.700     bisitz   6346:     $result.=
                   6347:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   6348:        .$select
                   6349:        .&Apache::lonhtmlcommon::row_closure();
                   6350: 
                   6351:     $result.=
                   6352:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   6353:        .'<label><input type="radio" name="vProb" value="no"'
                   6354:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   6355:        .'<label><input type="radio" name="vProb" value="yes" />'
                   6356:            .&mt('yes').'</label>'."\n"
                   6357:        .&Apache::lonhtmlcommon::row_closure();
                   6358: 
                   6359:     $result.=
                   6360:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   6361:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   6362:            .&mt('none').' </label>'."\n"
                   6363:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   6364:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   6365:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   6366:            .&mt('all submissions with details').' </label>'
                   6367:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 6368:     
1.700     bisitz   6369:     $result.=
                   6370:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   6371:        .'<input type="text" name="CODE" value="" />'
                   6372:        .&Apache::lonhtmlcommon::row_closure(1)
                   6373:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 6374: 
1.700     bisitz   6375:     # Show list of students to select for grading
                   6376:     $result.='<br /><input type="button" '.
1.589     bisitz   6377:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       6378: 
1.68      ng       6379:     $request->print($result);
                   6380: 
1.485     albertel 6381:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 6382: 	&Apache::loncommon::start_data_table().
                   6383: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6384: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6385: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 6386: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6387: 	'<th>'.&nameUserString('header').'</th>'.
                   6388: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       6389:  
1.761     raeburn  6390:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       6391:     my $ptr = 1;
1.294     albertel 6392:     foreach my $student (sort 
                   6393: 			 {
                   6394: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   6395: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   6396: 			     }
                   6397: 			     return $a cmp $b;
                   6398: 			 } (keys(%$fullname))) {
1.68      ng       6399: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 6400: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   6401:                                   : '</td>');
1.126     ng       6402: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 6403: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   6404: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 6405: 	$studentTable.=
                   6406: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   6407:                          : '');
1.68      ng       6408: 	$ptr++;
                   6409:     }
1.484     albertel 6410:     if ($ptr%2 == 0) {
                   6411: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   6412: 	    &Apache::loncommon::end_data_table_row();
                   6413:     }
                   6414:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       6415:     $studentTable.='<input type="button" '.
1.589     bisitz   6416:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       6417: 
                   6418:     $request->print($studentTable);
                   6419: 
                   6420:     return '';
                   6421: }
                   6422: 
                   6423: sub getSymbMap {
1.582     raeburn  6424:     my ($map_error) = @_;
1.132     bowersj2 6425:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6426:     unless (ref($navmap)) {
                   6427:         if (ref($map_error)) {
                   6428:             $$map_error = 'navmap';
                   6429:         }
                   6430:         return;
                   6431:     }
1.68      ng       6432:     my %symbx = ();
                   6433:     my @titles = ();
1.117     bowersj2 6434:     my $minder = 0;
                   6435: 
                   6436:     # Gather every sequence that has problems.
1.240     albertel 6437:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   6438: 					       1,0,1);
1.117     bowersj2 6439:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  6440: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 6441: 	    my $title = $minder.'.'.
                   6442: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   6443: 	    push(@titles, $title); # minder in case two titles are identical
                   6444: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 6445: 	    $minder++;
1.241     albertel 6446: 	}
1.68      ng       6447:     }
                   6448:     return \@titles,\%symbx;
                   6449: }
                   6450: 
1.72      ng       6451: #
                   6452: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       6453: sub displayPage {
1.608     www      6454:     my ($request,$symb) = @_;
1.257     albertel 6455:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6456:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6457:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6458:     my $pageTitle = $env{'form.page'};
1.103     albertel 6459:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6460:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6461:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 6462: 
                   6463:     #need to make sure we have the correct data for later EXT calls, 
                   6464:     #thus invalidate the cache
                   6465:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 6466:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   6467:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 6468:     &Apache::lonnet::clear_EXT_cache_status();
                   6469: 
1.103     albertel 6470:     if (!&canview($usec)) {
1.712     bisitz   6471:         $request->print(
                   6472:             '<span class="LC_warning">'.
                   6473:             &mt('Unable to view requested student. ([_1])',
                   6474:                     $env{'form.student'}).
                   6475:             '</span>');
                   6476:         return;
1.103     albertel 6477:     }
1.398     albertel 6478:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 6479:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       6480: 	'</h3>'."\n";
1.500     albertel 6481:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     6482:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 6483: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 6484:     } else {
                   6485: 	delete($env{'form.CODE'});
                   6486:     }
1.71      ng       6487:     &sub_page_js($request);
                   6488:     $request->print($result);
                   6489: 
1.132     bowersj2 6490:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6491:     unless (ref($navmap)) {
                   6492:         $request->print(&navmap_errormsg());
                   6493:         return;
                   6494:     }
1.257     albertel 6495:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       6496:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6497:     if (!$map) {
1.485     albertel 6498: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 6499: 	return; 
                   6500:     }
1.68      ng       6501:     my $iterator = $navmap->getIterator($map->map_start(),
                   6502: 					$map->map_finish());
                   6503: 
1.71      ng       6504:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       6505: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 6506: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   6507: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       6508: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 6509: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 6510: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      6511: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       6512: 
1.382     albertel 6513:     if (defined($env{'form.CODE'})) {
                   6514: 	$studentTable.=
                   6515: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   6516:     }
1.381     albertel 6517:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 6518: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       6519: 
1.594     bisitz   6520:     $studentTable.='&nbsp;<span class="LC_info">'.
                   6521:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   6522:         '</span>'."\n".
1.484     albertel 6523: 	&Apache::loncommon::start_data_table().
                   6524: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   6525: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 6526: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 6527: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6528: 
1.329     albertel 6529:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 6530:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       6531:     $iterator->next(); # skip the first BEGIN_MAP
                   6532:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 6533:     while ($depth > 0) {
1.68      ng       6534:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6535:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       6536: 
1.745     raeburn  6537:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 6538: 	    my $parts = $curRes->parts();
1.68      ng       6539:             my $title = $curRes->compTitle();
1.71      ng       6540: 	    my $symbx = $curRes->symb();
1.746     raeburn  6541:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 6542: 	    $studentTable.=
                   6543: 		&Apache::loncommon::start_data_table_row().
                   6544: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6545: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  6546: 		                        : '<br />('.&mt('[_1]parts',
                   6547: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 6548: 		 ).
                   6549: 		 '</td>';
1.71      ng       6550: 	    $studentTable.='<td valign="top">';
1.382     albertel 6551: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  6552:             if ($is_tool) {
                   6553:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   6554:             } else {
1.745     raeburn  6555: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   6556: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   6557: 					         undef,'both',\%form);
                   6558: 	        } else {
                   6559: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   6560: 		    $companswer =~ s|<form(.*?)>||g;
                   6561: 		    $companswer =~ s|</form>||g;
                   6562: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   6563: #		        $companswer =~ s/$1/ /ms;
                   6564: #		        $request->print('match='.$1."<br />\n");
                   6565: #		    }
                   6566: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   6567: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   6568: 		}
1.71      ng       6569: 	    }
                   6570: 
1.257     albertel 6571: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       6572: 
1.257     albertel 6573: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       6574: 		if ($record{'version'} eq '') {
1.745     raeburn  6575:                     my $msg = &mt('No recorded submission for this problem.');
                   6576:                     if ($is_tool) {
                   6577:                         $msg = &mt('No recorded transactions for this external tool');
                   6578:                     }
                   6579: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       6580: 		} else {
1.116     ng       6581: 		    my %responseType = ();
                   6582: 		    foreach my $partid (@{$parts}) {
1.147     albertel 6583: 			my @responseIds =$curRes->responseIds($partid);
                   6584: 			my @responseType =$curRes->responseType($partid);
                   6585: 			my %responseIds;
                   6586: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   6587: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   6588: 			}
                   6589: 			$responseType{$partid} = \%responseIds;
1.116     ng       6590: 		    }
1.148     albertel 6591: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       6592: 		}
1.257     albertel 6593: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   6594: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  6595:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       6596: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 6597: 									$env{'request.course.id'},
1.726     raeburn  6598: 									'','.submission',undef,
                   6599:                                                                         $usec,$identifier);
1.71      ng       6600:  
                   6601: 	    }
1.103     albertel 6602: 	    if (&canmodify($usec)) {
1.585     bisitz   6603:             $studentTable.=&gradeBox_start();
1.103     albertel 6604: 		foreach my $partid (@{$parts}) {
                   6605: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   6606: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   6607: 		    $question++;
                   6608: 		}
1.585     bisitz   6609:             $studentTable.=&gradeBox_end();
1.196     albertel 6610: 		$prob++;
1.71      ng       6611: 	    }
                   6612: 	    $studentTable.='</td></tr>';
1.68      ng       6613: 
1.103     albertel 6614: 	}
1.68      ng       6615:         $curRes = $iterator->next();
                   6616:     }
1.780     raeburn  6617:     my $disabled;
                   6618:     unless (&canmodify($usec)) {
                   6619:         $disabled = ' disabled="disabled"';
                   6620:     }
1.68      ng       6621: 
1.589     bisitz   6622:     $studentTable.=
                   6623:         '</table>'."\n".
1.780     raeburn  6624:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   6625:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   6626:         '</form>'."\n";
1.71      ng       6627:     $request->print($studentTable);
                   6628: 
                   6629:     return '';
1.119     ng       6630: }
                   6631: 
                   6632: sub displaySubByDates {
1.148     albertel 6633:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 6634:     my $isCODE=0;
1.335     albertel 6635:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  6636:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 6637:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 6638:     my $studentTable=&Apache::loncommon::start_data_table().
                   6639: 	&Apache::loncommon::start_data_table_header_row().
                   6640: 	'<th>'.&mt('Date/Time').'</th>'.
                   6641: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  6642:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  6643: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 6644: 	'<th>'.&mt('Status').'</th>'.
                   6645: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       6646:     my ($version);
                   6647:     my %mark;
1.148     albertel 6648:     my %orders;
1.119     ng       6649:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 6650:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  6651:         if ($is_tool) {
                   6652:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   6653:         } else {
                   6654:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   6655:         }
1.147     albertel 6656:     }
1.335     albertel 6657: 
                   6658:     my $interaction;
1.525     raeburn  6659:     my $no_increment = 1;
1.735     raeburn  6660:     my (%lastrndseed,%lasttype);
1.119     ng       6661:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 6662: 	my $timestamp = 
                   6663: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 6664: 	if (exists($$record{$version.':resource.0.version'})) {
                   6665: 	    $interaction = $$record{$version.':resource.0.version'};
                   6666: 	}
1.671     raeburn  6667:         if ($isTask && $env{'form.previousversion'}) {
                   6668:             next unless ($interaction == $env{'form.previousversion'});
                   6669:         }
1.335     albertel 6670: 	my $where = ($isTask ? "$version:resource.$interaction"
                   6671: 		             : "$version:resource");
1.467     albertel 6672: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   6673: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 6674: 	if ($isCODE) {
                   6675: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   6676: 	}
1.671     raeburn  6677:         if ($isTask) {
                   6678:             $studentTable.='<td>'.$interaction.'</td>';
                   6679:         }
1.119     ng       6680: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   6681: 	my @displaySub = ();
                   6682: 	foreach my $partid (@{$parts}) {
1.640     raeburn  6683:             my ($hidden,$type);
                   6684:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   6685:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  6686:                 $hidden = 1;
                   6687:             }
1.749     raeburn  6688:             my @matchKey;
                   6689:             if ($isTask) {
1.769     raeburn  6690:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  6691:             } elsif ($is_tool) {
1.769     raeburn  6692:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  6693:             } else {
1.769     raeburn  6694:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  6695:             }
1.122     ng       6696: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 6697: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 6698: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 6699: 		if (exists($$record{$version.':'.$matchKey}) &&
                   6700: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  6701:                     if ($is_tool) {
                   6702:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  6703:                     } else {
1.749     raeburn  6704: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   6705: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   6706:                         $displaySub[0].='<span class="LC_nobreak">';
                   6707:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   6708:                                        .' <span class="LC_internal_info">'
                   6709:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   6710:                                        .'</span>'
                   6711:                                        .' <b>';
                   6712:                         if ($hidden) {
                   6713:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   6714:                         } else {
                   6715:                             my ($trial,$rndseed,$newvariation);
                   6716:                             if ($type eq 'randomizetry') {
                   6717:                                 $trial = $$record{"$where.$partid.tries"};
                   6718:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   6719:                             }
                   6720: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   6721: 			        $displaySub[0].=&mt('Trial not counted');
                   6722: 		            } else {
                   6723: 			        $displaySub[0].=&mt('Trial: [_1]',
                   6724: 					        $$record{"$where.$partid.tries"});
                   6725:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   6726:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   6727:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   6728:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   6729:                                     }
1.640     raeburn  6730:                                 }
1.749     raeburn  6731:                                 $lastrndseed{$partid} = $rndseed;
                   6732:                                 $lasttype{$partid} = $type;
                   6733: 		            }
                   6734: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 6735:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  6736: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   6737: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   6738: 			        $orders{$partid}->{$responseId}=
                   6739: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   6740:                                                $no_increment,$type,$trial,$rndseed);
                   6741: 		            }
                   6742: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   6743: 		            $displaySub[0].='&nbsp; '.
                   6744: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   6745:                         }
1.596     raeburn  6746:                     }
1.147     albertel 6747: 		}
                   6748: 	    }
1.335     albertel 6749: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 6750: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   6751: 				    $$record{"$where.$partid.checkedin"},
                   6752: 				    $$record{"$where.$partid.checkedin.slot"}).
                   6753: 					'<br />';
1.335     albertel 6754: 	    }
                   6755: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 6756: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 6757: 		    lc($$record{"$where.$partid.award"}).' '.
                   6758: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 6759: 		    '<br />';
1.749     raeburn  6760: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   6761: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   6762: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   6763: 		}
1.147     albertel 6764: 	    }
1.335     albertel 6765: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  6766: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   6767: 		unless ($is_tool) {
                   6768: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6769: 		}
1.335     albertel 6770: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   6771: 		$displaySub[2].=
1.749     raeburn  6772: 		    $$record{"$version:resource.$partid.regrader"};
                   6773:                 unless ($is_tool) {
                   6774: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6775:                 }
1.147     albertel 6776: 	    }
                   6777: 	}
                   6778: 	# needed because old essay regrader has not parts info
                   6779: 	if (exists $$record{"$version:resource.regrader"}) {
                   6780: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   6781: 	}
                   6782: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   6783: 	if ($displaySub[2]) {
1.467     albertel 6784: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 6785: 	}
1.467     albertel 6786: 	$studentTable.='&nbsp;</td>'.
                   6787: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       6788:     }
1.467     albertel 6789:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       6790:     return $studentTable;
1.71      ng       6791: }
                   6792: 
                   6793: sub updateGradeByPage {
1.608     www      6794:     my ($request,$symb) = @_;
1.71      ng       6795: 
1.257     albertel 6796:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6797:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6798:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6799:     my $pageTitle = $env{'form.page'};
1.103     albertel 6800:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6801:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6802:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 6803:     if (!&canmodify($usec)) {
1.526     raeburn  6804: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 6805: 	return;
                   6806:     }
1.398     albertel 6807:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  6808:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       6809: 	'</h3>'."\n";
1.70      ng       6810: 
1.68      ng       6811:     $request->print($result);
                   6812: 
1.582     raeburn  6813: 
1.132     bowersj2 6814:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6815:     unless (ref($navmap)) {
                   6816:         $request->print(&navmap_errormsg());
                   6817:         return;
                   6818:     }
1.257     albertel 6819:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       6820:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6821:     if (!$map) {
1.527     raeburn  6822: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 6823: 	return; 
                   6824:     }
1.71      ng       6825:     my $iterator = $navmap->getIterator($map->map_start(),
                   6826: 					$map->map_finish());
1.70      ng       6827: 
1.484     albertel 6828:     my $studentTable=
                   6829: 	&Apache::loncommon::start_data_table().
                   6830: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6831: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   6832: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   6833: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   6834: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 6835: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6836: 
                   6837:     $iterator->next(); # skip the first BEGIN_MAP
                   6838:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  6839:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.798     raeburn  6840:     my (@updates,%weights,%excuseds,%awardeds,@symbs_in_map);
1.101     albertel 6841:     while ($depth > 0) {
1.71      ng       6842:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6843:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       6844: 
1.385     albertel 6845:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 6846: 	    my $parts = $curRes->parts();
1.71      ng       6847:             my $title = $curRes->compTitle();
                   6848: 	    my $symbx = $curRes->symb();
1.798     raeburn  6849:             push(@symbs_in_map,$symbx);
1.484     albertel 6850: 	    $studentTable.=
                   6851: 		&Apache::loncommon::start_data_table_row().
                   6852: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6853: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  6854:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  6855: 		.')').'</td>';
1.71      ng       6856: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   6857: 
                   6858: 	    my %newrecord=();
                   6859: 	    my @displayPts=();
1.269     raeburn  6860:             my %aggregate = ();
                   6861:             my $aggregateflag = 0;
1.787     raeburn  6862:             my %queueable;
1.726     raeburn  6863:             if ($env{'form.HIDE'.$prob}) {
                   6864:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  6865:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  6866:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.798     raeburn  6867:                 if ($numchgs) {
                   6868:                     push(@updates,$symbx);
                   6869:                 }
1.726     raeburn  6870:                 $hideflag += $numchgs;
                   6871:             }
1.71      ng       6872: 	    foreach my $partid (@{$parts}) {
1.257     albertel 6873: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   6874: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.787     raeburn  6875:                 my @types = $curRes->responseType($partid);
1.786     raeburn  6876:                 if (grep(/^essay$/,@types)) {
                   6877:                     $queueable{$partid} = 1;
                   6878:                 } else {
1.787     raeburn  6879:                     my @ids = $curRes->responseIds($partid);
1.786     raeburn  6880:                     for (my $i=0; $i < scalar(@ids); $i++) {
1.787     raeburn  6881:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
1.786     raeburn  6882:                                                           '.handgrade',$symb);
                   6883:                         if (lc($hndgrd) eq 'yes') {
                   6884:                             $queueable{$partid} = 1;
                   6885:                             last;
                   6886:                         }
                   6887:                     }
                   6888:                 }
1.257     albertel 6889: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   6890: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.798     raeburn  6891:                 $weights{$symbx}{$partid} = $wgt;
                   6892:                 $excuseds{$symbx}{$partid} = '';
1.71      ng       6893: 		my $partial = $newpts/$wgt;
                   6894: 		my $score;
                   6895: 		if ($partial > 0) {
                   6896: 		    $score = 'correct_by_override';
1.125     ng       6897: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       6898: 		    $score = 'incorrect_by_override';
                   6899: 		}
1.257     albertel 6900: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       6901: 		if ($dropMenu eq 'excused') {
1.71      ng       6902: 		    $partial = '';
                   6903: 		    $score = 'excused';
1.798     raeburn  6904:                     $excuseds{$symbx}{$partid} = 1;
1.125     ng       6905: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 6906: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       6907: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   6908: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   6909: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   6910: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 6911: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       6912: 		    $changeflag++;
                   6913: 		    $newpts = '';
1.269     raeburn  6914:                     
                   6915:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   6916:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   6917:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   6918:                     if ($aggtries > 0) {
                   6919:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   6920:                         $aggregateflag = 1;
                   6921:                     }
1.71      ng       6922: 		}
1.324     albertel 6923: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 6924: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  6925: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       6926: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 6927: 		    '&nbsp;<br />';
1.526     raeburn  6928: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       6929: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 6930: 		    '&nbsp;<br />';
1.71      ng       6931: 		$question++;
1.798     raeburn  6932:                 if (($newpts eq '') || ($partial eq '')) {
                   6933:                     $awardeds{$symbx}{$partid} = 0;
                   6934:                 } else {
                   6935:                     $awardeds{$symbx}{$partid} = $partial;
                   6936:                 }
1.380     albertel 6937: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       6938: 
1.71      ng       6939: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       6940: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 6941: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       6942: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       6943: 
                   6944: 		$changeflag++;
                   6945: 	    }
                   6946: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 6947: 		my %record = 
                   6948: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   6949: 					     $udom,$uname);
                   6950: 
                   6951: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   6952: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   6953: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   6954: 		    $newrecord{'resource.CODE'} = '';
                   6955: 		}
1.257     albertel 6956: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       6957: 					$udom,$uname);
1.382     albertel 6958: 		%record = &Apache::lonnet::restore($symbx,
                   6959: 						   $env{'request.course.id'},
                   6960: 						   $udom,$uname);
1.380     albertel 6961: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.786     raeburn  6962: 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       6963: 	    }
1.380     albertel 6964: 	    
1.269     raeburn  6965:             if ($aggregateflag) {
                   6966:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   6967:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   6968:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   6969:             }
1.125     ng       6970: 
1.71      ng       6971: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   6972: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 6973: 		&Apache::loncommon::end_data_table_row();
1.68      ng       6974: 
1.196     albertel 6975: 	    $prob++;
1.798     raeburn  6976:             if ($changeflag) {
                   6977:                 push(@updates,$symbx);
                   6978:             }
1.68      ng       6979: 	}
1.71      ng       6980:         $curRes = $iterator->next();
1.68      ng       6981:     }
1.98      albertel 6982: 
1.484     albertel 6983:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  6984:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   6985: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  6986: 		  $changeflag).'<br />');
                   6987:     my $hidemsg=($hideflag == 0 ? '' :
                   6988:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   6989:                      $hideflag).'<br />');
                   6990:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       6991: 
1.798     raeburn  6992:     if (@updates) {
                   6993:         my (@allsymbs,$mapsymb,@recurseup,%parentmapsymbs,%possmappb,%possrespb);
                   6994:         @allsymbs = @updates;
                   6995:         if (ref($map)) {
                   6996:             $mapsymb = $map->symb();
                   6997:             push(@allsymbs,$mapsymb);
                   6998:             @recurseup = $navmap->recurseup_maps($map->src,1);
                   6999:         }
                   7000:         if (@recurseup) {
                   7001:             push(@allsymbs,@recurseup);
                   7002:             map { $parentmapsymbs{$_} = 1; } @recurseup;
                   7003:         }
                   7004:         my %passback = &Apache::lonnet::get('nohist_linkprot_passback',\@allsymbs,$cdom,$cnum);
1.806   ! raeburn  7005:         my (%uniqsymbs,$use_symbs_in_map,%launch_to_symb);
1.798     raeburn  7006:         if (keys(%passback)) {
                   7007:             foreach my $possible (keys(%passback)) {
                   7008:                 if (ref($passback{$possible}) eq 'HASH') {
                   7009:                     if ($possible eq $mapsymb) {
                   7010:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7011:                             $possmappb{$launcher} = 1;
1.806   ! raeburn  7012:                             $launch_to_symb{$launcher} = $possible;
1.798     raeburn  7013:                         }
                   7014:                         $use_symbs_in_map = 1;
                   7015:                     } elsif (exists($parentmapsymbs{$possible})) {
                   7016:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7017:                             my ($linkuri,$linkprotector,$scope) = split(/\0/,$launcher);
                   7018:                             if ($scope eq 'rec') {
                   7019:                                 $possmappb{$launcher} = 1;
                   7020:                                 $use_symbs_in_map = 1;
1.806   ! raeburn  7021:                                 $launch_to_symb{$launcher} = $possible;
1.798     raeburn  7022:                             }
                   7023:                         }
                   7024:                     } elsif (grep(/^\Q$possible$\E$/,@updates)) {
                   7025:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7026:                             $possrespb{$launcher} = 1;
1.806   ! raeburn  7027:                             $launch_to_symb{$launcher} = $possible;
1.798     raeburn  7028:                         }
                   7029:                         $uniqsymbs{$possible} = 1;
                   7030:                     }
                   7031:                 }
                   7032:             }
                   7033:         }
                   7034:         if ($use_symbs_in_map) {
                   7035:             map { $uniqsymbs{$_} = 1; } @symbs_in_map;
                   7036:         }
                   7037:         my @posslaunchers;
                   7038:         if (keys(%possmappb)) {
                   7039:             push(@posslaunchers,keys(%possmappb));
                   7040:         }
                   7041:         if (keys(%possrespb)) {
                   7042:             push(@posslaunchers,keys(%possrespb));
                   7043:         }
                   7044:         if (@posslaunchers) {
                   7045:             my (%pbsave,%skip_passback,%needpb);
                   7046:             my %pbids = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@posslaunchers,$udom,$uname);
                   7047:             foreach my $key (keys(%pbids)) {
                   7048:                 if (ref($pbids{$key}) eq 'ARRAY') {
1.806   ! raeburn  7049:                     if ($launch_to_symb{$key}) {
        !          7050:                         $needpb{$key} = $launch_to_symb{$key};
        !          7051:                     }
1.798     raeburn  7052:                 }
                   7053:             }
                   7054:             my @symbs = keys(%uniqsymbs);
1.802     raeburn  7055:             &process_passbacks('updatebypage',\@symbs,$cdom,$cnum,$udom,$uname,$usec,\%weights,
1.798     raeburn  7056:                                \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave,\%pbids);
1.801     raeburn  7057:             if (@Apache::grades::ltipassback) {
1.798     raeburn  7058:                 unless ($registered_cleanup) {
                   7059:                     my $handlers = $request->get_handlers('PerlCleanupHandler');
                   7060:                     $request->set_handlers('PerlCleanupHandler' =>
1.801     raeburn  7061:                                            [\&Apache::grades::make_passback,@{$handlers}]);
                   7062:                     $registered_cleanup=1;
1.798     raeburn  7063:                 }
                   7064:             }
                   7065:         }
                   7066:     }
1.70      ng       7067:     return '';
                   7068: }
                   7069: 
1.801     raeburn  7070: sub make_passback {
                   7071:     if (@Apache::grades::ltipassback) {
                   7072:         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7073:         my $ip = &Apache::lonnet::get_host_ip($lonhost);
                   7074:         foreach my $item (@Apache::grades::ltipassback) {
                   7075:             &Apache::lonhomework::run_passback($item,$lonhost,$ip);
                   7076:         }
                   7077:         undef(@Apache::grades::ltipassback);
                   7078:     }
                   7079: }
                   7080: 
1.72      ng       7081: #-------- end of section for handling grading by page/sequence ---------
                   7082: #
                   7083: #-------------------------------------------------------------------
                   7084: 
1.581     www      7085: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 7086: #
                   7087: #------ start of section for handling grading by page/sequence ---------
                   7088: 
1.423     albertel 7089: =pod
                   7090: 
                   7091: =head1 Bubble sheet grading routines
                   7092: 
1.424     albertel 7093:   For this documentation:
                   7094: 
                   7095:    'scanline' refers to the full line of characters
                   7096:    from the file that we are parsing that represents one entire sheet
                   7097: 
                   7098:    'bubble line' refers to the data
1.659     raeburn  7099:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 7100: 
                   7101: 
1.659     raeburn  7102: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 7103: into a course. When a user wants to grade, they select a
1.659     raeburn  7104: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 7105: one of the predefined configurations for what each scanline looks
                   7106: like.
                   7107: 
                   7108: Next each scanline is checked for any errors of either 'missing
1.435     foxr     7109: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 7110: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   7111: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  7112: invalid student/employee ID
1.424     albertel 7113: 
                   7114: If the CODE option is used that determines the randomization of the
1.556     weissno  7115: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 7116: username:domain.
                   7117: 
                   7118: During the validation phase the instructor can choose to skip scanlines. 
                   7119: 
1.659     raeburn  7120: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 7121: 
                   7122:   scantron_original_filename (unmodified original file)
                   7123:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   7124:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   7125: 
                   7126: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  7127: correction information that isn't representable in the bubblesheet
1.424     albertel 7128: file (see &scantron_getfile() for more information)
                   7129: 
                   7130: After all scanlines are either valid, marked as valid or skipped, then
                   7131: foreach line foreach problem in the picked sequence, an ssi request is
                   7132: made that simulates a user submitting their selected letter(s) against
                   7133: the homework problem.
1.423     albertel 7134: 
                   7135: =over 4
                   7136: 
                   7137: 
                   7138: 
                   7139: =item defaultFormData
                   7140: 
                   7141:   Returns html hidden inputs used to hold context/default values.
                   7142: 
                   7143:  Arguments:
                   7144:   $symb - $symb of the current resource 
                   7145: 
                   7146: =cut
1.422     foxr     7147: 
1.81      albertel 7148: sub defaultFormData {
1.324     albertel 7149:     my ($symb)=@_;
1.766     raeburn  7150:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 7151: }
                   7152: 
1.447     foxr     7153: 
1.423     albertel 7154: =pod 
                   7155: 
                   7156: =item getSequenceDropDown
                   7157: 
                   7158:    Return html dropdown of possible sequences to grade
                   7159:  
                   7160:  Arguments:
1.582     raeburn  7161:    $symb - $symb of the current resource
                   7162:    $map_error - ref to scalar which will container error if
                   7163:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 7164: 
                   7165: =cut
1.422     foxr     7166: 
1.75      albertel 7167: sub getSequenceDropDown {
1.582     raeburn  7168:     my ($symb,$map_error)=@_;
1.75      albertel 7169:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  7170:     my ($titles,$symbx) = &getSymbMap($map_error);
                   7171:     if (ref($map_error)) {
                   7172:         return if ($$map_error);
                   7173:     }
1.137     albertel 7174:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 7175:     my $ctr=0;
                   7176:     foreach (@$titles) {
                   7177: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   7178: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 7179: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 7180: 	    '>'.$showtitle.'</option>'."\n";
                   7181: 	$ctr++;
                   7182:     }
                   7183:     $result.= '</select>';
                   7184:     return $result;
                   7185: }
                   7186: 
1.495     albertel 7187: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  7188:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 7189: 
                   7190: my %first_bubble_line;             # First bubble line no. for each bubble.
                   7191: 
1.509     raeburn  7192: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   7193:                                    # matchresponse or rankresponse, where 
                   7194:                                    # an individual response can have multiple 
                   7195:                                    # lines
1.503     raeburn  7196: 
                   7197: my %responsetype_per_response;     # responsetype for each response
                   7198: 
1.691     raeburn  7199: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   7200:                                    # numbered response. Needed when randomorder
                   7201:                                    # or randompick are in use. Key is ID, value 
                   7202:                                    # is response number.
                   7203: 
1.495     albertel 7204: # Save and restore the bubble lines array to the form env.
                   7205: 
                   7206: 
                   7207: sub save_bubble_lines {
                   7208:     foreach my $line (keys(%bubble_lines_per_response)) {
                   7209: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   7210: 	$env{"form.scantron.first_bubble_line.$line"} =
                   7211: 	    $first_bubble_line{$line};
1.503     raeburn  7212:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   7213:             $subdivided_bubble_lines{$line};
                   7214:         $env{"form.scantron.responsetype.$line"} =
                   7215:             $responsetype_per_response{$line};
1.495     albertel 7216:     }
1.691     raeburn  7217:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   7218:         my $line = $masterseq_id_responsenum{$resid};
                   7219:         $env{"form.scantron.residpart.$line"} = $resid;
                   7220:     }
1.495     albertel 7221: }
                   7222: 
                   7223: 
                   7224: sub restore_bubble_lines {
                   7225:     my $line = 0;
                   7226:     %bubble_lines_per_response = ();
1.691     raeburn  7227:     %masterseq_id_responsenum = ();
1.495     albertel 7228:     while ($env{"form.scantron.bubblelines.$line"}) {
                   7229: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   7230: 	$bubble_lines_per_response{$line} = $value;
                   7231: 	$first_bubble_line{$line}  =
                   7232: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  7233:         $subdivided_bubble_lines{$line} =
                   7234:             $env{"form.scantron.sub_bubblelines.$line"};
                   7235:         $responsetype_per_response{$line} =
                   7236:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  7237:         my $id = $env{"form.scantron.residpart.$line"};
                   7238:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 7239: 	$line++;
                   7240:     }
                   7241: }
                   7242: 
1.423     albertel 7243: =pod 
                   7244: 
                   7245: =item scantron_filenames
                   7246: 
                   7247:    Returns a list of the scantron files in the current course 
                   7248: 
                   7249: =cut
1.422     foxr     7250: 
1.202     albertel 7251: sub scantron_filenames {
1.257     albertel 7252:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7253:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  7254:     my $getpropath = 1;
1.662     raeburn  7255:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   7256:                                                         $cname,$getpropath);
1.202     albertel 7257:     my @possiblenames;
1.662     raeburn  7258:     if (ref($dirlist) eq 'ARRAY') {
                   7259:         foreach my $filename (sort(@{$dirlist})) {
                   7260: 	    ($filename)=split(/&/,$filename);
                   7261: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   7262: 	    $filename=~s/^scantron_orig_//;
                   7263: 	    push(@possiblenames,$filename);
                   7264:         }
1.202     albertel 7265:     }
                   7266:     return @possiblenames;
                   7267: }
                   7268: 
1.423     albertel 7269: =pod 
                   7270: 
                   7271: =item scantron_uploads
                   7272: 
                   7273:    Returns  html drop-down list of scantron files in current course.
                   7274: 
                   7275:  Arguments:
                   7276:    $file2grade - filename to set as selected in the dropdown
                   7277: 
                   7278: =cut
1.422     foxr     7279: 
1.202     albertel 7280: sub scantron_uploads {
1.209     ng       7281:     my ($file2grade) = @_;
1.202     albertel 7282:     my $result=	'<select name="scantron_selectfile">';
                   7283:     $result.="<option></option>";
                   7284:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 7285: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 7286:     }
                   7287:     $result.="</select>";
                   7288:     return $result;
                   7289: }
                   7290: 
1.423     albertel 7291: =pod 
                   7292: 
                   7293: =item scantron_scantab
                   7294: 
                   7295:   Returns html drop down of the scantron formats in the scantronformat.tab
                   7296:   file.
                   7297: 
                   7298: =cut
1.422     foxr     7299: 
1.82      albertel 7300: sub scantron_scantab {
                   7301:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 7302:     $result.='<option></option>'."\n";
1.754     raeburn  7303:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  7304:     if (@lines > 0) {
                   7305:         foreach my $line (@lines) {
                   7306:             next if (($line =~ /^\#/) || ($line eq ''));
                   7307: 	    my ($name,$descrip)=split(/:/,$line);
                   7308: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   7309:         }
1.82      albertel 7310:     }
                   7311:     $result.='</select>'."\n";
1.518     raeburn  7312:     return $result;
                   7313: }
                   7314: 
1.423     albertel 7315: =pod 
                   7316: 
                   7317: =item scantron_CODElist
                   7318: 
                   7319:   Returns html drop down of the saved CODE lists from current course,
                   7320:   generated from earlier printings.
                   7321: 
                   7322: =cut
1.422     foxr     7323: 
1.186     albertel 7324: sub scantron_CODElist {
1.257     albertel 7325:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7326:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 7327:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   7328:     my $namechoice='<option></option>';
1.225     albertel 7329:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 7330: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 7331: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 7332: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   7333:     }
                   7334:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   7335:     return $namechoice;
                   7336: }
                   7337: 
1.423     albertel 7338: =pod 
                   7339: 
                   7340: =item scantron_CODEunique
                   7341: 
                   7342:   Returns the html for "Each CODE to be used once" radio.
                   7343: 
                   7344: =cut
1.422     foxr     7345: 
1.186     albertel 7346: sub scantron_CODEunique {
1.532     bisitz   7347:     my $result='<span class="LC_nobreak">
1.272     albertel 7348:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7349:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 7350:                 </span>
1.532     bisitz   7351:                 <span class="LC_nobreak">
1.272     albertel 7352:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7353:                         value="no" />'.&mt('No').' </label>
1.381     albertel 7354:                 </span>';
1.186     albertel 7355:     return $result;
                   7356: }
1.423     albertel 7357: 
                   7358: =pod 
                   7359: 
                   7360: =item scantron_selectphase
                   7361: 
1.659     raeburn  7362:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 7363:   Allows for - starting a grading run.
1.424     albertel 7364:              - downloading existing scan data (original, corrected
1.423     albertel 7365:                                                 or skipped info)
                   7366: 
                   7367:              - uploading new scan data
                   7368: 
                   7369:  Arguments:
                   7370:   $r          - The Apache request object
                   7371:   $file2grade - name of the file that contain the scanned data to score
                   7372: 
                   7373: =cut
1.186     albertel 7374: 
1.75      albertel 7375: sub scantron_selectphase {
1.608     www      7376:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 7377:     if (!$symb) {return '';}
1.582     raeburn  7378:     my $map_error;
                   7379:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   7380:     if ($map_error) {
                   7381:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   7382:         return;
                   7383:     }
1.324     albertel 7384:     my $default_form_data=&defaultFormData($symb);
1.209     ng       7385:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 7386:     my $format_selector=&scantron_scantab();
1.186     albertel 7387:     my $CODE_selector=&scantron_CODElist();
                   7388:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 7389:     my $result;
1.422     foxr     7390: 
1.513     foxr     7391:     $ssi_error = 0;
                   7392: 
1.770     raeburn  7393:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 7394: 
                   7395: 	# Chunk of form to prompt for a scantron file upload.
                   7396: 
                   7397:         $r->print('
1.754     raeburn  7398:     <br />');
1.606     wenzelju 7399:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7400:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  7401:     my $csec= $env{'request.course.sec'};
1.736     damieng  7402:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   7403:     &js_escape(\$alertmsg);
1.754     raeburn  7404:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 7405:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   7406:     function checkUpload(formname) {
                   7407: 	if (formname.upfile.value == "") {
1.736     damieng  7408: 	    alert("'.$alertmsg.'");
1.606     wenzelju 7409: 	    return false;
                   7410: 	}
                   7411: 	formname.submit();
1.756     raeburn  7412:     }'."\n".$formatjs));
1.606     wenzelju 7413:     $r->print('
                   7414:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7415:                 '.$default_form_data.'
                   7416:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  7417:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 7418:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   7419:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  7420:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7421:               '.&Apache::loncommon::start_data_table_header_row().'
                   7422:                 <th>
                   7423:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   7424:                 </th>
                   7425:               '.&Apache::loncommon::end_data_table_header_row().'
                   7426:               '.&Apache::loncommon::start_data_table_row().'
                   7427:             <td>
                   7428:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   7429:     if ($formatoptions) {
                   7430:         $r->print('</td>
                   7431:                  '.&Apache::loncommon::end_data_table_row().'
                   7432:                  '.&Apache::loncommon::start_data_table_row().'
                   7433:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   7434:                  </td>
                   7435:                  '.&Apache::loncommon::end_data_table_row().'
                   7436:                  '.&Apache::loncommon::start_data_table_row().'
                   7437:                  <td>'
                   7438:         );
                   7439:     } else {
                   7440:         $r->print(' <br />');
                   7441:     }
                   7442:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   7443:               </td>
                   7444:              '.&Apache::loncommon::end_data_table_row().'
                   7445:              '.&Apache::loncommon::end_data_table().'
                   7446:              </form>'
                   7447:     );
1.606     wenzelju 7448: 
                   7449:     }
                   7450: 
1.422     foxr     7451:     # Chunk of form to prompt for a file to grade and how:
                   7452: 
1.489     albertel 7453:     $result.= '
                   7454:     <br />
                   7455:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   7456:     <input type="hidden" name="command" value="scantron_warning" />
                   7457:     '.$default_form_data.'
                   7458:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7459:        '.&Apache::loncommon::start_data_table_header_row().'
                   7460:             <th colspan="2">
1.492     albertel 7461:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 7462:             </th>
                   7463:        '.&Apache::loncommon::end_data_table_header_row().'
                   7464:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7465:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 7466:        '.&Apache::loncommon::end_data_table_row().'
                   7467:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      7468:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 7469:        '.&Apache::loncommon::end_data_table_row().'
                   7470:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      7471:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 7472:        '.&Apache::loncommon::end_data_table_row().'
                   7473:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7474:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 7475:        '.&Apache::loncommon::end_data_table_row().'
                   7476:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7477:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 7478:        '.&Apache::loncommon::end_data_table_row().'
                   7479:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7480: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 7481:             <td>
1.492     albertel 7482: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   7483:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   7484:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 7485: 	    </td>
1.489     albertel 7486:        '.&Apache::loncommon::end_data_table_row().'
                   7487:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 7488:             <td colspan="2">
1.572     www      7489:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 7490:             </td>
1.489     albertel 7491:        '.&Apache::loncommon::end_data_table_row().'
                   7492:     '.&Apache::loncommon::end_data_table().'
                   7493:     </form>
                   7494: ';
1.162     albertel 7495:    
                   7496:     $r->print($result);
                   7497: 
1.422     foxr     7498:     # Chunk of the form that prompts to view a scoring office file,
                   7499:     # corrected file, skipped records in a file.
                   7500: 
1.489     albertel 7501:     $r->print('
                   7502:    <br />
                   7503:    <form action="/adm/grades" name="scantron_download">
                   7504:      '.$default_form_data.'
                   7505:      <input type="hidden" name="command" value="scantron_download" />
                   7506:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7507:        '.&Apache::loncommon::start_data_table_header_row().'
                   7508:               <th>
1.492     albertel 7509:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 7510:               </th>
                   7511:        '.&Apache::loncommon::end_data_table_header_row().'
                   7512:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7513:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 7514:                 <br />
1.492     albertel 7515:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 7516:        '.&Apache::loncommon::end_data_table_row().'
                   7517:      '.&Apache::loncommon::end_data_table().'
                   7518:    </form>
                   7519:    <br />
                   7520: ');
1.162     albertel 7521: 
1.457     banghart 7522:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  7523: 
1.694     bisitz   7524:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  7525:              $default_form_data."\n".
                   7526:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   7527:              &Apache::loncommon::start_data_table_header_row()."\n".
                   7528:              '<th colspan="2">
1.572     www      7529:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  7530:              '</th>'."\n".
                   7531:               &Apache::loncommon::end_data_table_header_row()."\n".
                   7532:               &Apache::loncommon::start_data_table_row()."\n".
                   7533:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   7534:               '<td> '.$sequence_selector.' </td>'.
                   7535:               &Apache::loncommon::end_data_table_row()."\n".
                   7536:               &Apache::loncommon::start_data_table_row()."\n".
                   7537:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   7538:               '<td> '.$file_selector.' </td>'."\n".
                   7539:               &Apache::loncommon::end_data_table_row()."\n".
                   7540:               &Apache::loncommon::start_data_table_row()."\n".
                   7541:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   7542:               '<td> '.$format_selector.' </td>'."\n".
                   7543:               &Apache::loncommon::end_data_table_row()."\n".
                   7544:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  7545:               '<td> '.&mt('Options').' </td>'."\n".
                   7546:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   7547:               &Apache::loncommon::end_data_table_row()."\n".
                   7548:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  7549:               '<td colspan="2">'."\n".
                   7550:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      7551:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  7552:               '</td>'."\n".
                   7553:               &Apache::loncommon::end_data_table_row()."\n".
                   7554:               &Apache::loncommon::end_data_table()."\n".
                   7555:               '</form><br />');
                   7556:     return;
1.75      albertel 7557: }
                   7558: 
1.423     albertel 7559: =pod 
                   7560: 
                   7561: =item username_to_idmap
                   7562: 
1.556     weissno  7563:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  7564:     student username:domain. If a single ID occurs for more than one student,
                   7565:     the status of the student is checked, and if Active, the value in the hash
                   7566:     will be set to the Active student.
1.423     albertel 7567: 
                   7568:   Arguments:
                   7569: 
                   7570:     $classlist - reference to the class list hash. This is a hash
                   7571:                  keyed by student name:domain  whose elements are references
1.424     albertel 7572:                  to arrays containing various chunks of information
1.423     albertel 7573:                  about the student. (See loncoursedata for more info).
                   7574: 
                   7575:   Returns
                   7576:     %idmap - the constructed hash
                   7577: 
                   7578: =cut
                   7579: 
1.82      albertel 7580: sub username_to_idmap {
                   7581:     my ($classlist)= @_;
                   7582:     my %idmap;
                   7583:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  7584:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   7585:         unless ($id eq '') {
                   7586:             if (!exists($idmap{$id})) {
                   7587:                 $idmap{$id} = $student;
                   7588:             } else {
                   7589:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   7590:                 if ($status eq 'Active') {
                   7591:                     $idmap{$id} = $student;
                   7592:                 }
                   7593:             }
                   7594:         }
1.82      albertel 7595:     }
                   7596:     return %idmap;
                   7597: }
1.423     albertel 7598: 
                   7599: =pod
                   7600: 
1.424     albertel 7601: =item scantron_fixup_scanline
1.423     albertel 7602: 
                   7603:    Process a requested correction to a scanline.
                   7604: 
                   7605:   Arguments:
1.754     raeburn  7606:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 7607:     $scan_data         - hash of correction information 
                   7608:                           (see &scantron_getfile())
                   7609:     $line              - existing scanline
                   7610:     $whichline         - line number of the passed in scanline
                   7611:     $field             - type of change to process 
                   7612:                          (either 
1.573     bisitz   7613:                           'ID'     -> correct the student/employee ID
1.423     albertel 7614:                           'CODE'   -> correct the CODE
                   7615:                           'answer' -> fixup the submitted answers)
                   7616:     
                   7617:    $args               - hash of additional info,
                   7618:                           - 'ID' 
                   7619:                                'newid' -> studentID to use in replacement
1.424     albertel 7620:                                           of existing one
1.423     albertel 7621:                           - 'CODE' 
                   7622:                                'CODE_ignore_dup' - set to true if duplicates
                   7623:                                                    should be ignored.
                   7624: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 7625:                                         if the existing unfound code should
1.423     albertel 7626:                                         be used as is
                   7627:                           - 'answer'
                   7628:                                'response' - new answer or 'none' if blank
                   7629:                                'question' - the bubble line to change
1.503     raeburn  7630:                                'questionnum' - the question identifier,
                   7631:                                                may include subquestion. 
1.423     albertel 7632: 
                   7633:   Returns:
                   7634:     $line - the modified scanline
                   7635: 
                   7636:   Side effects: 
                   7637:     $scan_data - may be updated
                   7638: 
                   7639: =cut
                   7640: 
1.82      albertel 7641: 
1.157     albertel 7642: sub scantron_fixup_scanline {
                   7643:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   7644:     if ($field eq 'ID') {
                   7645: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 7646: 	    return ($line,1,'New value too large');
1.157     albertel 7647: 	}
                   7648: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   7649: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   7650: 				     $args->{'newid'});
                   7651: 	}
                   7652: 	substr($line,$$scantron_config{'IDstart'}-1,
                   7653: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   7654: 	if ($args->{'newid'}=~/^\s*$/) {
                   7655: 	    &scan_data($scan_data,"$whichline.user",
                   7656: 		       $args->{'username'}.':'.$args->{'domain'});
                   7657: 	}
1.186     albertel 7658:     } elsif ($field eq 'CODE') {
1.192     albertel 7659: 	if ($args->{'CODE_ignore_dup'}) {
                   7660: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   7661: 	}
                   7662: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   7663: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 7664: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   7665: 		return ($line,1,'New CODE value too large');
                   7666: 	    }
                   7667: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   7668: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   7669: 	    }
                   7670: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   7671: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 7672: 	}
1.157     albertel 7673:     } elsif ($field eq 'answer') {
1.497     foxr     7674: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 7675: 	my $off=$scantron_config->{'Qoff'};
                   7676: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     7677: 	my $answer=${off}x$length;
                   7678: 	if ($args->{'response'} eq 'none') {
                   7679: 	    &scan_data($scan_data,
1.503     raeburn  7680: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     7681: 	} else {
                   7682: 	    if ($on eq 'letter') {
                   7683: 		my @alphabet=('A'..'Z');
                   7684: 		$answer=$alphabet[$args->{'response'}];
                   7685: 	    } elsif ($on eq 'number') {
                   7686: 		$answer=$args->{'response'}+1;
                   7687: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 7688: 	    } else {
1.497     foxr     7689: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 7690: 	    }
1.497     foxr     7691: 	    &scan_data($scan_data,
1.503     raeburn  7692: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 7693: 	}
1.497     foxr     7694: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   7695: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 7696:     }
                   7697:     return $line;
                   7698: }
1.423     albertel 7699: 
                   7700: =pod
                   7701: 
                   7702: =item scan_data
                   7703: 
                   7704:     Edit or look up  an item in the scan_data hash.
                   7705: 
                   7706:   Arguments:
                   7707:     $scan_data  - The hash (see scantron_getfile)
                   7708:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 7709:                   scantronfilename_key).
1.423     albertel 7710:     $data        - New value of the hash entry.
                   7711:     $delete      - If true, the entry is removed from the hash.
                   7712: 
                   7713:   Returns:
                   7714:     The new value of the hash table field (undefined if deleted).
                   7715: 
                   7716: =cut
                   7717: 
                   7718: 
1.157     albertel 7719: sub scan_data {
                   7720:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 7721:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 7722:     if (defined($value)) {
                   7723: 	$scan_data->{$filename.'_'.$key} = $value;
                   7724:     }
                   7725:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   7726:     return $scan_data->{$filename.'_'.$key};
                   7727: }
1.423     albertel 7728: 
1.495     albertel 7729: # ----- These first few routines are general use routines.----
                   7730: 
                   7731: # Return the number of occurences of a pattern in a string.
                   7732: 
                   7733: sub occurence_count {
                   7734:     my ($string, $pattern) = @_;
                   7735: 
                   7736:     my @matches = ($string =~ /$pattern/g);
                   7737: 
                   7738:     return scalar(@matches);
                   7739: }
                   7740: 
                   7741: 
                   7742: # Take a string known to have digits and convert all the
                   7743: # digits into letters in the range J,A..I.
                   7744: 
                   7745: sub digits_to_letters {
                   7746:     my ($input) = @_;
                   7747: 
                   7748:     my @alphabet = ('J', 'A'..'I');
                   7749: 
                   7750:     my @input    = split(//, $input);
                   7751:     my $output ='';
                   7752:     for (my $i = 0; $i < scalar(@input); $i++) {
                   7753: 	if ($input[$i] =~ /\d/) {
                   7754: 	    $output .= $alphabet[$input[$i]];
                   7755: 	} else {
                   7756: 	    $output .= $input[$i];
                   7757: 	}
                   7758:     }
                   7759:     return $output;
                   7760: }
                   7761: 
1.423     albertel 7762: =pod 
                   7763: 
                   7764: =item scantron_parse_scanline
                   7765: 
1.711     bisitz   7766:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 7767: 
                   7768:  Arguments:
1.711     bisitz   7769:     line             - The text of the bubblesheet file line to process
1.423     albertel 7770:     whichline        - Line number
1.711     bisitz   7771:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 7772:     scan_data        - Hash of extra information about the scanline
                   7773:                        (see scantron_getfile for more information)
                   7774:     just_header      - True if should not process question answers but only
                   7775:                        the stuff to the left of the answers.
1.691     raeburn  7776:     randomorder      - True if randomorder in use
                   7777:     randompick       - True if randompick in use
                   7778:     sequence         - Exam folder URL
                   7779:     master_seq       - Ref to array containing symbs in exam folder
                   7780:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   7781:                        (corresponding values are resource objects)
                   7782:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   7783:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   7784:                        are refs to an array of resource objects, ordered
                   7785:                        according to order used for CODE, when randomorder
                   7786:                        and or randompick are in use.
                   7787:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   7788:                        for current line to question number used for same question
                   7789:                         in "Master Sequence" (as seen by Course Coordinator).
                   7790:     startline        - Ref to hash where key is question number (0 is first)
                   7791:                        and value is number of first bubble line for current 
                   7792:                        student or code-based randompick and/or randomorder.
                   7793:     totalref         - Ref of scalar used to score total number of bubble
                   7794:                        lines needed for responses in a scan line (used when
                   7795:                        randompick in use. 
                   7796:     
1.423     albertel 7797:  Returns:
                   7798:    Hash containing the result of parsing the scanline
                   7799: 
                   7800:    Keys are all proceeded by the string 'scantron.'
                   7801: 
                   7802:        CODE    - the CODE in use for this scanline
                   7803:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   7804:                  by the operator
                   7805:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   7806:                             CODEs were selected, but the usage has been
                   7807:                             forced by the operator
1.556     weissno  7808:        ID  - student/employee ID
1.423     albertel 7809:        PaperID - if used, the ID number printed on the sheet when the 
                   7810:                  paper was scanned
                   7811:        FirstName - first name from the sheet
                   7812:        LastName  - last name from the sheet
                   7813: 
                   7814:      if just_header was not true these key may also exist
                   7815: 
1.447     foxr     7816:        missingerror - a list of bubble ranges that are considered to be answers
                   7817:                       to a single question that don't have any bubbles filled in.
                   7818:                       Of the form questionnumber:firstbubblenumber:count.
                   7819:        doubleerror  - a list of bubble ranges that are considered to be answers
                   7820:                       to a single question that have more than one bubble filled in.
                   7821:                       Of the form questionnumber::firstbubblenumber:count
                   7822:    
                   7823:                 In the above, count is the number of bubble responses in the
                   7824:                 input line needed to represent the possible answers to the question.
                   7825:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   7826:                 per line would have count = 2.
                   7827: 
1.423     albertel 7828:        maxquest     - the number of the last bubble line that was parsed
                   7829: 
                   7830:        (<number> starts at 1)
                   7831:        <number>.answer - zero or more letters representing the selected
                   7832:                          letters from the scanline for the bubble line 
                   7833:                          <number>.
                   7834:                          if blank there was either no bubble or there where
                   7835:                          multiple bubbles, (consult the keys missingerror and
                   7836:                          doubleerror if this is an error condition)
                   7837: 
                   7838: =cut
                   7839: 
1.82      albertel 7840: sub scantron_parse_scanline {
1.691     raeburn  7841:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   7842:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   7843:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     7844: 
1.82      albertel 7845:     my %record;
1.691     raeburn  7846:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 7847:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   7848: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   7849: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   7850: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   7851: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 7852: 	    $record{'scantron.CODE'}=substr($data,
                   7853: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 7854: 					    $$scantron_config{'CODElength'});
1.191     albertel 7855: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   7856: 		$record{'scantron.useCODE'}=1;
                   7857: 	    }
1.192     albertel 7858: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   7859: 		$record{'scantron.CODE_ignore_dup'}=1;
                   7860: 	    }
1.82      albertel 7861: 	} else {
                   7862: 	    #FIXME interpret first N questions
                   7863: 	}
                   7864:     }
1.83      albertel 7865:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   7866: 				  $$scantron_config{'IDlength'});
1.157     albertel 7867:     $record{'scantron.PaperID'}=
                   7868: 	substr($data,$$scantron_config{'PaperID'}-1,
                   7869: 	       $$scantron_config{'PaperIDlength'});
                   7870:     $record{'scantron.FirstName'}=
                   7871: 	substr($data,$$scantron_config{'FirstName'}-1,
                   7872: 	       $$scantron_config{'FirstNamelength'});
                   7873:     $record{'scantron.LastName'}=
                   7874: 	substr($data,$$scantron_config{'LastName'}-1,
                   7875: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 7876:     if ($just_header) { return \%record; }
1.194     albertel 7877: 
1.82      albertel 7878:     my @alphabet=('A'..'Z');
                   7879:     my $questnum=0;
1.447     foxr     7880:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   7881: 
1.691     raeburn  7882:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   7883:     if ($randompick || $randomorder) {
                   7884:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   7885:                                          $master_seq,$symb_to_resource,
                   7886:                                          $partids_by_symb,$orderedforcode,
                   7887:                                          $respnumlookup,$startline);
                   7888:         if ($total) {
                   7889:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   7890:         }
                   7891:         if (ref($totalref)) {
                   7892:             $$totalref = $total;
                   7893:         }
                   7894:     }
                   7895:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     7896:     chomp($questions);		# Get rid of any trailing \n.
                   7897:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   7898:     while (length($questions)) {
1.691     raeburn  7899:         my $answers_needed;
                   7900:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7901:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   7902:         } else {
                   7903: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   7904:         }
1.503     raeburn  7905:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   7906:                              || 1;
                   7907:         $questnum++;
                   7908:         my $quest_id = $questnum;
                   7909:         my $currentquest = substr($questions,0,$answer_length);
                   7910:         $questions       = substr($questions,$answer_length);
                   7911:         if (length($currentquest) < $answer_length) { next; }
                   7912: 
1.691     raeburn  7913:         my $subdivided;
                   7914:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7915:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   7916:         } else {
                   7917:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   7918:         }
                   7919:         if ($subdivided =~ /,/) {
1.503     raeburn  7920:             my $subquestnum = 1;
                   7921:             my $subquestions = $currentquest;
1.691     raeburn  7922:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  7923:             foreach my $subans (@subanswers_needed) {
                   7924:                 my $subans_length =
                   7925:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   7926:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   7927:                 $subquestions   = substr($subquestions,$subans_length);
                   7928:                 $quest_id = "$questnum.$subquestnum";
                   7929:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   7930:                     ($$scantron_config{'Qon'} eq 'number')) {
                   7931:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   7932:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  7933:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7934:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7935:                 } else {
                   7936:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  7937:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   7938:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7939:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7940:                 }
                   7941:                 $subquestnum ++;
                   7942:             }
                   7943:         } else {
                   7944:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   7945:                 ($$scantron_config{'Qon'} eq 'number')) {
                   7946:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   7947:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7948:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7949:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7950:             } else {
                   7951:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   7952:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7953:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7954:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7955:             }
                   7956:         }
                   7957:     }
                   7958:     $record{'scantron.maxquest'}=$questnum;
                   7959:     return \%record;
                   7960: }
1.447     foxr     7961: 
1.691     raeburn  7962: sub get_master_seq {
1.788     raeburn  7963:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
1.691     raeburn  7964:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   7965:                    (ref($symb_to_resource) eq 'HASH'));
1.788     raeburn  7966:     if ($need_symb_in_map) {
                   7967:         return unless (ref($symb_for_examcode) eq 'HASH');
                   7968:     }
1.691     raeburn  7969:     my $resource_error;
                   7970:     foreach my $resource (@{$resources}) {
                   7971:         my $ressymb;
                   7972:         if (ref($resource)) {
                   7973:             $ressymb = $resource->symb();
                   7974:             push(@{$master_seq},$ressymb);
                   7975:             $symb_to_resource->{$ressymb} = $resource;
1.788     raeburn  7976:             if ($need_symb_in_map) {
                   7977:                 unless ($resource->is_map()) {
                   7978:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   7979:                     unless (exists($symb_for_examcode->{$map})) {
                   7980:                         $symb_for_examcode->{$map} = $ressymb;
                   7981:                     }
                   7982:                 }
                   7983:             }
1.691     raeburn  7984:         } else {
                   7985:             $resource_error = 1;
                   7986:             last;
                   7987:         }
                   7988:     }
                   7989:     return $resource_error;
                   7990: }
                   7991: 
                   7992: sub get_respnum_lookups {
                   7993:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   7994:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   7995:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   7996:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   7997:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   7998:                    (ref($startline) eq 'HASH'));
                   7999:     my ($user,$scancode);
                   8000:     if ((exists($record->{'scantron.CODE'})) &&
                   8001:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   8002:         $scancode = $record->{'scantron.CODE'};
                   8003:     } else {
                   8004:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   8005:     }
                   8006:     my @mapresources =
                   8007:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   8008:                      $orderedforcode);
                   8009:     my $total = 0;
                   8010:     my $count = 0;
                   8011:     foreach my $resource (@mapresources) {
                   8012:         my $id = $resource->id();
                   8013:         my $symb = $resource->symb();
                   8014:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   8015:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   8016:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   8017:                 if ($respnum ne '') {
                   8018:                     $respnumlookup->{$count} = $respnum;
                   8019:                     $startline->{$count} = $total;
                   8020:                     $total += $bubble_lines_per_response{$respnum};
                   8021:                     $count ++;
                   8022:                 }
                   8023:             }
                   8024:         }
                   8025:     }
                   8026:     return $total;
                   8027: }
                   8028: 
1.503     raeburn  8029: sub scantron_validator_lettnum {
                   8030:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  8031:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   8032:         $randompick,$respnumlookup) = @_;
1.503     raeburn  8033: 
                   8034:     # Qon 'letter' implies for each slot in currquest we have:
                   8035:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   8036:     #    about anything else (esp. a value of Qoff) for missing
                   8037:     #    bubbles.
                   8038:     #
                   8039:     # Qon 'number' implies each slot gives a digit that indexes the
                   8040:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   8041:     #    and * or ? for double bubbles on a single line.
                   8042:     #
1.447     foxr     8043: 
1.503     raeburn  8044:     my $matchon;
                   8045:     if ($$scantron_config{'Qon'} eq 'letter') {
                   8046:         $matchon = '[A-Z]';
                   8047:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   8048:         $matchon = '\d';
                   8049:     }
                   8050:     my $occurrences = 0;
1.691     raeburn  8051:     my $responsenum = $questnum-1;
                   8052:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   8053:        $responsenum = $respnumlookup->{$questnum-1} 
                   8054:     }
                   8055:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8056:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8057:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8058:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8059:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8060:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8061:         my @singlelines = split('',$currquest);
                   8062:         foreach my $entry (@singlelines) {
                   8063:             $occurrences = &occurence_count($entry,$matchon);
                   8064:             if ($occurrences > 1) {
                   8065:                 last;
                   8066:             }
1.691     raeburn  8067:         }
1.503     raeburn  8068:     } else {
                   8069:         $occurrences = &occurence_count($currquest,$matchon); 
                   8070:     }
                   8071:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   8072:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8073:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8074:             my $bubble = substr($currquest,$ans,1);
                   8075:             if ($bubble =~ /$matchon/ ) {
                   8076:                 if ($$scantron_config{'Qon'} eq 'number') {
                   8077:                     if ($bubble == 0) {
                   8078:                         $bubble = 10; 
                   8079:                     }
                   8080:                     $record->{"scantron.$ansnum.answer"} = 
                   8081:                         $alphabet->[$bubble-1];
                   8082:                 } else {
                   8083:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   8084:                 }
                   8085:             } else {
                   8086:                 $record->{"scantron.$ansnum.answer"}='';
                   8087:             }
                   8088:             $ansnum++;
                   8089:         }
                   8090:     } elsif (!defined($currquest)
                   8091:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   8092:             || (&occurence_count($currquest,$matchon) == 0)) {
                   8093:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8094:             $record->{"scantron.$ansnum.answer"}='';
                   8095:             $ansnum++;
                   8096:         }
                   8097:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8098:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   8099:         }
                   8100:     } else {
                   8101:         if ($$scantron_config{'Qon'} eq 'number') {
                   8102:             $currquest = &digits_to_letters($currquest);            
                   8103:         }
                   8104:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8105:             my $bubble = substr($currquest,$ans,1);
                   8106:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   8107:             $ansnum++;
                   8108:         }
                   8109:     }
                   8110:     return $ansnum;
                   8111: }
1.447     foxr     8112: 
1.503     raeburn  8113: sub scantron_validator_positional {
                   8114:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  8115:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   8116:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     8117: 
1.503     raeburn  8118:     # Otherwise there's a positional notation;
                   8119:     # each bubble line requires Qlength items, and there are filled in
                   8120:     # bubbles for each case where there 'Qon' characters.
                   8121:     #
1.447     foxr     8122: 
1.503     raeburn  8123:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     8124: 
1.503     raeburn  8125:     # If the split only gives us one element.. the full length of the
                   8126:     # answer string, no bubbles are filled in:
1.447     foxr     8127: 
1.507     raeburn  8128:     if ($answers_needed eq '') {
                   8129:         return;
                   8130:     }
                   8131: 
1.503     raeburn  8132:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   8133:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8134:             $record->{"scantron.$ansnum.answer"}='';
                   8135:             $ansnum++;
                   8136:         }
                   8137:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8138:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   8139:         }
                   8140:     } elsif (scalar(@array) == 2) {
                   8141:         my $location = length($array[0]);
                   8142:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   8143:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   8144:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8145:             if ($ans eq $line_num) {
                   8146:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   8147:             } else {
                   8148:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   8149:             }
                   8150:             $ansnum++;
                   8151:          }
                   8152:     } else {
                   8153:         #  If there's more than one instance of a bubble character
                   8154:         #  That's a double bubble; with positional notation we can
                   8155:         #  record all the bubbles filled in as well as the
                   8156:         #  fact this response consists of multiple bubbles.
                   8157:         #
1.691     raeburn  8158:         my $responsenum = $questnum-1;
                   8159:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   8160:             $responsenum = $respnumlookup->{$questnum-1}
                   8161:         }
                   8162:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8163:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8164:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8165:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8166:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8167:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8168:             my $doubleerror = 0;
                   8169:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   8170:                    (!$doubleerror)) {
                   8171:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   8172:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   8173:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   8174:                if (length(@currarray) > 2) {
                   8175:                    $doubleerror = 1;
                   8176:                } 
                   8177:             }
                   8178:             if ($doubleerror) {
                   8179:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8180:             }
                   8181:         } else {
                   8182:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8183:         }
                   8184:         my $item = $ansnum;
                   8185:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8186:             $record->{"scantron.$item.answer"} = '';
                   8187:             $item ++;
                   8188:         }
1.447     foxr     8189: 
1.503     raeburn  8190:         my @ans=@array;
                   8191:         my $i=0;
                   8192:         my $increment = 0;
                   8193:         while ($#ans) {
                   8194:             $i+=length($ans[0]) + $increment;
                   8195:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   8196:             my $bubble = $i%$$scantron_config{'Qlength'};
                   8197:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   8198:             shift(@ans);
                   8199:             $increment = 1;
                   8200:         }
                   8201:         $ansnum += $answers_needed;
1.82      albertel 8202:     }
1.503     raeburn  8203:     return $ansnum;
1.82      albertel 8204: }
                   8205: 
1.423     albertel 8206: =pod
                   8207: 
                   8208: =item scantron_add_delay
                   8209: 
                   8210:    Adds an error message that occurred during the grading phase to a
                   8211:    queue of messages to be shown after grading pass is complete
                   8212: 
                   8213:  Arguments:
1.424     albertel 8214:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 8215:    $scanline    - the scanline that caused the error
                   8216:    $errormesage - the error message
                   8217:    $errorcode   - a numeric code for the error
                   8218: 
                   8219:  Side Effects:
1.424     albertel 8220:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 8221: 
                   8222: =cut
                   8223: 
1.82      albertel 8224: sub scantron_add_delay {
1.140     albertel 8225:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   8226:     push(@$delayqueue,
                   8227: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   8228: 	  'ecode' => $errorcode }
                   8229: 	 );
1.82      albertel 8230: }
                   8231: 
1.423     albertel 8232: =pod
                   8233: 
                   8234: =item scantron_find_student
                   8235: 
1.424     albertel 8236:    Finds the username for the current scanline
                   8237: 
                   8238:   Arguments:
                   8239:    $scantron_record - hash result from scantron_parse_scanline
                   8240:    $scan_data       - hash of correction information 
                   8241:                       (see &scantron_getfile() form more information)
                   8242:    $idmap           - hash from &username_to_idmap()
                   8243:    $line            - number of current scanline
                   8244:  
                   8245:   Returns:
                   8246:    Either 'username:domain' or undef if unknown
                   8247: 
1.423     albertel 8248: =cut
                   8249: 
1.82      albertel 8250: sub scantron_find_student {
1.157     albertel 8251:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 8252:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 8253:     if ($scanID =~ /^\s*$/) {
                   8254:  	return &scan_data($scan_data,"$line.user");
                   8255:     }
1.83      albertel 8256:     foreach my $id (keys(%$idmap)) {
1.157     albertel 8257:  	if (lc($id) eq lc($scanID)) {
                   8258:  	    return $$idmap{$id};
                   8259:  	}
1.83      albertel 8260:     }
                   8261:     return undef;
                   8262: }
                   8263: 
1.423     albertel 8264: =pod
                   8265: 
                   8266: =item scantron_filter
                   8267: 
1.424     albertel 8268:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   8269:    hidden resources was selected
                   8270: 
1.423     albertel 8271: =cut
                   8272: 
1.83      albertel 8273: sub scantron_filter {
                   8274:     my ($curres)=@_;
1.331     albertel 8275: 
                   8276:     if (ref($curres) && $curres->is_problem()) {
                   8277: 	# if the user has asked to not have either hidden
                   8278: 	# or 'randomout' controlled resources to be graded
                   8279: 	# don't include them
                   8280: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   8281: 	    && $curres->randomout) {
                   8282: 	    return 0;
                   8283: 	}
1.83      albertel 8284: 	return 1;
                   8285:     }
                   8286:     return 0;
1.82      albertel 8287: }
                   8288: 
1.423     albertel 8289: =pod
                   8290: 
                   8291: =item scantron_process_corrections
                   8292: 
1.424     albertel 8293:    Gets correction information out of submitted form data and corrects
                   8294:    the scanline
                   8295: 
1.423     albertel 8296: =cut
                   8297: 
1.157     albertel 8298: sub scantron_process_corrections {
                   8299:     my ($r) = @_;
1.754     raeburn  8300:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8301:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8302:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 8303:     my $which=$env{'form.scantron_line'};
1.200     albertel 8304:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 8305:     my ($skip,$err,$errmsg);
1.257     albertel 8306:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 8307: 	$skip=1;
1.257     albertel 8308:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   8309: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   8310: 	    $env{'form.scantron_domain'};
1.157     albertel 8311: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   8312: 	($line,$err,$errmsg)=
                   8313: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   8314: 				     'ID',{'newid'=>$newid,
1.257     albertel 8315: 				    'username'=>$env{'form.scantron_username'},
                   8316: 				    'domain'=>$env{'form.scantron_domain'}});
                   8317:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   8318: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 8319: 	my $newCODE;
1.192     albertel 8320: 	my %args;
1.190     albertel 8321: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 8322: 	    $newCODE='use_unfound';
1.190     albertel 8323: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 8324: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 8325: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 8326: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 8327: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 8328: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 8329: 	}
1.257     albertel 8330: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 8331: 	    $args{'CODE_ignore_dup'}=1;
                   8332: 	}
                   8333: 	$args{'CODE'}=$newCODE;
1.186     albertel 8334: 	($line,$err,$errmsg)=
                   8335: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 8336: 				     'CODE',\%args);
1.257     albertel 8337:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   8338: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 8339: 	    ($line,$err,$errmsg)=
                   8340: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   8341: 					 $which,'answer',
                   8342: 					 { 'question'=>$question,
1.503     raeburn  8343: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   8344:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 8345: 	    if ($err) { last; }
                   8346: 	}
                   8347:     }
                   8348:     if ($err) {
1.703     bisitz   8349:         $r->print(
                   8350:             '<p class="LC_error">'
                   8351:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   8352:                 $errmsg)
1.704     raeburn  8353:            .'</p>');
1.157     albertel 8354:     } else {
1.200     albertel 8355: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 8356: 	&scantron_putfile($scanlines,$scan_data);
                   8357:     }
                   8358: }
                   8359: 
1.423     albertel 8360: =pod
                   8361: 
                   8362: =item reset_skipping_status
                   8363: 
1.424     albertel 8364:    Forgets the current set of remember skipped scanlines (and thus
                   8365:    reverts back to considering all lines in the
                   8366:    scantron_skipped_<filename> file)
                   8367: 
1.423     albertel 8368: =cut
                   8369: 
1.200     albertel 8370: sub reset_skipping_status {
                   8371:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8372:     &scan_data($scan_data,'remember_skipping',undef,1);
                   8373:     &scantron_putfile(undef,$scan_data);
                   8374: }
                   8375: 
1.423     albertel 8376: =pod
                   8377: 
                   8378: =item start_skipping
                   8379: 
1.424     albertel 8380:    Marks a scanline to be skipped. 
                   8381: 
1.423     albertel 8382: =cut
                   8383: 
1.376     albertel 8384: sub start_skipping {
1.200     albertel 8385:     my ($scan_data,$i)=@_;
                   8386:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8387:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   8388: 	$remembered{$i}=2;
                   8389:     } else {
                   8390: 	$remembered{$i}=1;
                   8391:     }
1.200     albertel 8392:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   8393: }
                   8394: 
1.423     albertel 8395: =pod
                   8396: 
                   8397: =item should_be_skipped
                   8398: 
1.424     albertel 8399:    Checks whether a scanline should be skipped.
                   8400: 
1.423     albertel 8401: =cut
                   8402: 
1.200     albertel 8403: sub should_be_skipped {
1.376     albertel 8404:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 8405:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 8406: 	# not redoing old skips
1.376     albertel 8407: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 8408: 	return 0;
                   8409:     }
                   8410:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8411: 
                   8412:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   8413: 	return 0;
                   8414:     }
1.200     albertel 8415:     return 1;
                   8416: }
                   8417: 
1.423     albertel 8418: =pod
                   8419: 
                   8420: =item remember_current_skipped
                   8421: 
1.424     albertel 8422:    Discovers what scanlines are in the scantron_skipped_<filename>
                   8423:    file and remembers them into scan_data for later use.
                   8424: 
1.423     albertel 8425: =cut
                   8426: 
1.200     albertel 8427: sub remember_current_skipped {
                   8428:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8429:     my %to_remember;
                   8430:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8431: 	if ($scanlines->{'skipped'}[$i]) {
                   8432: 	    $to_remember{$i}=1;
                   8433: 	}
                   8434:     }
1.376     albertel 8435: 
1.200     albertel 8436:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   8437:     &scantron_putfile(undef,$scan_data);
                   8438: }
                   8439: 
1.423     albertel 8440: =pod
                   8441: 
                   8442: =item check_for_error
                   8443: 
1.424     albertel 8444:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  8445:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 8446:     something went wrong.
                   8447: 
1.423     albertel 8448: =cut
                   8449: 
1.200     albertel 8450: sub check_for_error {
                   8451:     my ($r,$result)=@_;
                   8452:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 8453: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 8454:     }
                   8455: }
1.157     albertel 8456: 
1.423     albertel 8457: =pod
                   8458: 
                   8459: =item scantron_warning_screen
                   8460: 
1.424     albertel 8461:    Interstitial screen to make sure the operator has selected the
                   8462:    correct options before we start the validation phase.
                   8463: 
1.423     albertel 8464: =cut
                   8465: 
1.203     albertel 8466: sub scantron_warning_screen {
1.650     raeburn  8467:     my ($button_text,$symb)=@_;
1.257     albertel 8468:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  8469:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 8470:     my $CODElist;
1.284     albertel 8471:     if ($scantron_config{'CODElocation'} &&
                   8472: 	$scantron_config{'CODEstart'} &&
                   8473: 	$scantron_config{'CODElength'}) {
                   8474: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   8475: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 8476: 	$CODElist=
1.492     albertel 8477: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 8478: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 8479:     }
1.663     raeburn  8480:     my $lastbubblepoints;
                   8481:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8482:         $lastbubblepoints =
                   8483:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   8484:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   8485:     }
1.770     raeburn  8486:     return '
1.203     albertel 8487: <p>
1.492     albertel 8488: <span class="LC_warning">
1.705     raeburn  8489: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 8490: </p>
                   8491: <table>
1.492     albertel 8492: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   8493: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  8494: '.$CODElist.$lastbubblepoints.'
1.203     albertel 8495: </table>
1.680     raeburn  8496: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  8497: '.&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  8498: ';
1.203     albertel 8499: }
                   8500: 
1.423     albertel 8501: =pod
                   8502: 
                   8503: =item scantron_do_warning
                   8504: 
1.424     albertel 8505:    Check if the operator has picked something for all required
                   8506:    fields. Error out if something is missing.
                   8507: 
1.423     albertel 8508: =cut
                   8509: 
1.203     albertel 8510: sub scantron_do_warning {
1.608     www      8511:     my ($r,$symb)=@_;
1.203     albertel 8512:     if (!$symb) {return '';}
1.324     albertel 8513:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 8514:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 8515:     if ( $env{'form.selectpage'} eq '' ||
                   8516: 	 $env{'form.scantron_selectfile'} eq '' ||
                   8517: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  8518: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 8519: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 8520: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 8521: 	} 
1.257     albertel 8522: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  8523: 	    $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  8524: 	}
1.257     albertel 8525: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  8526: 	    $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  8527: 	}
1.237     albertel 8528:     } else {
1.650     raeburn  8529: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  8530:         my ($checksec,@possibles) = &gradable_sections();
                   8531:         my $gradesections;
                   8532:         if ($checksec) {
                   8533:             my $file=$env{'form.scantron_selectfile'};
                   8534:             if (&valid_file($file)) {
                   8535:                 my %bysec = &scantron_get_sections();
                   8536:                 my $table;
                   8537:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   8538:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   8539:                     $table = &Apache::loncommon::start_data_table()."\n".
                   8540:                              &Apache::loncommon::start_data_table_header_row().
                   8541:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   8542:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   8543:                     if ($bysec{'none'}) {
                   8544:                         $table .= &Apache::loncommon::start_data_table_row().
                   8545:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   8546:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8547:                     }
                   8548:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   8549:                         next if ($sec eq 'none');
                   8550:                         $table .= &Apache::loncommon::start_data_table_row().
                   8551:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   8552:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8553:                     }
                   8554:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   8555:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   8556:                                       '<p>'.$table.'</p>';
                   8557:                     if (@possibles) {
                   8558:                         $gradesections .= '<p>'.
                   8559:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   8560:                                               scalar(@possibles)).'<br />'.
                   8561:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   8562:                                               '<i>'.$checksec.'</i>').' ';
                   8563:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   8564:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   8565:                         }
                   8566:                         $gradesections .= '</p>';
                   8567:                     }
                   8568:                 }
                   8569:             } else {
                   8570:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   8571:             }
                   8572:         }
1.663     raeburn  8573:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 8574: 	$r->print('
1.770     raeburn  8575: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 8576: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 8577: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 8578: ');
1.237     albertel 8579:     }
1.614     www      8580:     $r->print("</form><br />");
1.203     albertel 8581:     return '';
                   8582: }
                   8583: 
1.423     albertel 8584: =pod
                   8585: 
                   8586: =item scantron_form_start
                   8587: 
1.424     albertel 8588:     html hidden input for remembering all selected grading options
                   8589: 
1.423     albertel 8590: =cut
                   8591: 
1.203     albertel 8592: sub scantron_form_start {
                   8593:     my ($max_bubble)=@_;
                   8594:     my $result= <<SCANTRONFORM;
                   8595: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 8596:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   8597:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   8598:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 8599:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 8600:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   8601:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   8602:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   8603:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 8604:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 8605: SCANTRONFORM
1.447     foxr     8606: 
                   8607:   my $line = 0;
                   8608:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   8609:        my $chunk =
                   8610: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     8611:        $chunk .=
                   8612: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  8613:        $chunk .= 
                   8614:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  8615:        $chunk .=
                   8616:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  8617:        $chunk .=
                   8618:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     8619:        $result .= $chunk;
                   8620:        $line++;
1.691     raeburn  8621:     }
1.203     albertel 8622:     return $result;
                   8623: }
                   8624: 
1.423     albertel 8625: =pod
                   8626: 
                   8627: =item scantron_validate_file
                   8628: 
1.659     raeburn  8629:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 8630: 
                   8631:     Also processes any necessary information resets that need to
                   8632:     occur before validation begins (ignore previous corrections,
                   8633:     restarting the skipped records processing)
                   8634: 
1.423     albertel 8635: =cut
                   8636: 
1.157     albertel 8637: sub scantron_validate_file {
1.608     www      8638:     my ($r,$symb) = @_;
1.157     albertel 8639:     if (!$symb) {return '';}
1.324     albertel 8640:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 8641:     
1.703     bisitz   8642:     # do the detection of only doing skipped records first before we delete
1.424     albertel 8643:     # them when doing the corrections reset
1.257     albertel 8644:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 8645: 	&reset_skipping_status();
                   8646:     }
1.257     albertel 8647:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 8648: 	&remember_current_skipped();
1.257     albertel 8649: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 8650:     }
                   8651: 
1.257     albertel 8652:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 8653: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   8654: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   8655: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 8656: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 8657:     }
1.200     albertel 8658: 
1.257     albertel 8659:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 8660: 	&scantron_process_corrections($r);
                   8661:     }
1.770     raeburn  8662: 
                   8663:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   8664:     my ($checksec,@gradable);
                   8665:     if ($env{'request.course.sec'}) {
                   8666:         ($checksec,my @possibles) = &gradable_sections();
                   8667:         if ($checksec) {
                   8668:             if (@possibles) {
                   8669:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   8670:                 if (@chosensecs) {
                   8671:                     foreach my $sec (@chosensecs) {
                   8672:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   8673:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   8674:                                 push(@gradable,$sec);
                   8675:                             }
                   8676:                         }
                   8677:                     }
                   8678:                 }
                   8679:             }
                   8680:             $r->print('<p><table>');
                   8681:             if (@gradable) {
                   8682:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   8683:                 $r->print(
                   8684:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   8685:             } else {
                   8686:                 $r->print(
                   8687:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   8688:             }
                   8689:             $r->print('</table></p>');
                   8690:         }
                   8691:     }
                   8692:     $r->rflush();
                   8693: 
1.157     albertel 8694:     #get the student pick code ready
                   8695:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  8696:     my $nav_error;
1.754     raeburn  8697:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8698:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8699:     if ($nav_error) {
                   8700:         $r->print(&navmap_errormsg());
                   8701:         return '';
                   8702:     }
1.203     albertel 8703:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  8704:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8705:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   8706:     }
1.157     albertel 8707:     $r->print($result);
                   8708:     
1.334     albertel 8709:     my @validate_phases=( 'sequence',
                   8710: 			  'ID',
1.157     albertel 8711: 			  'CODE',
                   8712: 			  'doublebubble',
                   8713: 			  'missingbubbles');
1.257     albertel 8714:     if (!$env{'form.validatepass'}) {
                   8715: 	$env{'form.validatepass'} = 0;
1.157     albertel 8716:     }
1.257     albertel 8717:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  8718:     my %skipbysec=();
1.448     foxr     8719: 
1.157     albertel 8720:     my $stop=0;
                   8721:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  8722: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 8723: 	$r->rflush();
1.691     raeburn  8724:      
1.157     albertel 8725: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   8726: 	{
                   8727: 	    no strict 'refs';
1.770     raeburn  8728:             my @extras=();
                   8729:             if ($validate_phases[$currentphase] eq 'ID') {
                   8730:                 @extras = (\%skipbysec,$checksec,@gradable);
                   8731:             }
                   8732: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 8733: 	}
                   8734:     }
                   8735:     if (!$stop) {
1.650     raeburn  8736: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  8737:         my $secinfo;
                   8738:         if (keys(%skipbysec) > 0) {
                   8739:             my $seclist = '<ul>';
                   8740:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   8741:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   8742:             }
                   8743:             $seclist .= '</ul>';
                   8744:             $secinfo = '<p class="LC_info">'.
                   8745:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   8746:                            $seclist).
                   8747:                        '</p>';
                   8748:         }
1.542     raeburn  8749: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  8750:                   $secinfo.$warning.
1.542     raeburn  8751:                   &mt('Perform verification for each student after storage of submissions?').
                   8752:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   8753:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   8754:                   ('&nbsp;'x3).'<label>'.
                   8755:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   8756:                   '</label></span><br />'.
                   8757:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  8758:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  8759:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   8760:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 8761:     } else {
                   8762: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   8763: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   8764:     }
                   8765:     if ($stop) {
1.334     albertel 8766: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  8767: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 8768: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 8769: 
1.650     raeburn  8770: 	    $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 8771: 	} else {
1.503     raeburn  8772:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  8773: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  8774:             } else {
1.539     riegler  8775:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  8776:             }
1.492     albertel 8777: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   8778: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   8779: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 8780: 	}
1.157     albertel 8781:     }
1.614     www      8782:     $r->print(" </form><br />");
1.157     albertel 8783:     return '';
                   8784: }
                   8785: 
1.423     albertel 8786: 
                   8787: =pod
                   8788: 
                   8789: =item scantron_remove_file
                   8790: 
1.659     raeburn  8791:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 8792:    scantron_original_<filename> is never removed
                   8793: 
                   8794: 
1.423     albertel 8795: =cut
                   8796: 
1.200     albertel 8797: sub scantron_remove_file {
1.192     albertel 8798:     my ($which)=@_;
1.257     albertel 8799:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8800:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8801:     my $file='scantron_';
1.200     albertel 8802:     if ($which eq 'corrected' || $which eq 'skipped') {
                   8803: 	$file.=$which.'_';
1.192     albertel 8804:     } else {
                   8805: 	return 'refused';
                   8806:     }
1.257     albertel 8807:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 8808:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   8809: }
                   8810: 
1.423     albertel 8811: 
                   8812: =pod
                   8813: 
                   8814: =item scantron_remove_scan_data
                   8815: 
1.659     raeburn  8816:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 8817:    data file.  (In the case that both the are doing skipped records we need
                   8818:    to remember the old skipped lines for the time being so that element
                   8819:    persists for a while.)
                   8820: 
1.423     albertel 8821: =cut
                   8822: 
1.200     albertel 8823: sub scantron_remove_scan_data {
1.257     albertel 8824:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8825:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8826:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   8827:     my @todelete;
1.257     albertel 8828:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 8829:     foreach my $key (@keys) {
                   8830: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 8831: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 8832: 		$key=~/remember_skipping/) {
                   8833: 		next;
                   8834: 	    }
1.192     albertel 8835: 	    push(@todelete,$key);
                   8836: 	}
                   8837:     }
1.200     albertel 8838:     my $result;
1.192     albertel 8839:     if (@todelete) {
1.491     albertel 8840: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   8841: 				       \@todelete,$cdom,$cname);
                   8842:     } else {
                   8843: 	$result = 'ok';
1.192     albertel 8844:     }
                   8845:     return $result;
                   8846: }
                   8847: 
1.423     albertel 8848: 
                   8849: =pod
                   8850: 
                   8851: =item scantron_getfile
                   8852: 
1.659     raeburn  8853:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 8854:     the scan_data hash
                   8855:   
                   8856:   Arguments:
                   8857:     None
                   8858: 
                   8859:   Returns:
                   8860:     2 hash references
                   8861: 
                   8862:      - first one has 
                   8863:          orig      -
                   8864:          corrected -
                   8865:          skipped   -  each of which points to an array ref of the specified
                   8866:                       file broken up into individual lines
                   8867:          count     - number of scanlines
                   8868:  
                   8869:      - second is the scan_data hash possible keys are
1.425     albertel 8870:        ($number refers to scanline numbered $number and thus the key affects
                   8871:         only that scanline
                   8872:         $bubline refers to the specific bubble line element and the aspects
                   8873:         refers to that specific bubble line element)
                   8874: 
                   8875:        $number.user - username:domain to use
                   8876:        $number.CODE_ignore_dup 
                   8877:                     - ignore the duplicate CODE error 
                   8878:        $number.useCODE
                   8879:                     - use the CODE in the scanline as is
                   8880:        $number.no_bubble.$bubline
                   8881:                     - it is valid that there is no bubbled in bubble
                   8882:                       at $number $bubline
                   8883:        remember_skipping
                   8884:                     - a frozen hash containing keys of $number and values
                   8885:                       of either 
                   8886:                         1 - we are on a 'do skipped records pass' and plan
                   8887:                             on processing this line
                   8888:                         2 - we are on a 'do skipped records pass' and this
                   8889:                             scanline has been marked to skip yet again
1.424     albertel 8890: 
1.423     albertel 8891: =cut
                   8892: 
1.157     albertel 8893: sub scantron_getfile {
1.200     albertel 8894:     #FIXME really would prefer a scantron directory
1.257     albertel 8895:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8896:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 8897:     my $lines;
                   8898:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8899: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 8900:     my %scanlines;
                   8901:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   8902:     my $temp=$scanlines{'orig'};
                   8903:     $scanlines{'count'}=$#$temp;
                   8904: 
                   8905:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8906: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 8907:     if ($lines eq '-1') {
                   8908: 	$scanlines{'corrected'}=[];
                   8909:     } else {
                   8910: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   8911:     }
                   8912:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8913: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 8914:     if ($lines eq '-1') {
                   8915: 	$scanlines{'skipped'}=[];
                   8916:     } else {
                   8917: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   8918:     }
1.175     albertel 8919:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 8920:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   8921:     my %scan_data = @tmp;
                   8922:     return (\%scanlines,\%scan_data);
                   8923: }
                   8924: 
1.423     albertel 8925: =pod
                   8926: 
                   8927: =item lonnet_putfile
                   8928: 
1.424     albertel 8929:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   8930: 
                   8931:  Arguments:
                   8932:    $contents - data to store
                   8933:    $filename - filename to store $contents into
                   8934: 
                   8935:  Returns:
                   8936:    result value from &Apache::lonnet::finishuserfileupload
                   8937: 
1.423     albertel 8938: =cut
                   8939: 
1.157     albertel 8940: sub lonnet_putfile {
                   8941:     my ($contents,$filename)=@_;
1.257     albertel 8942:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8943:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8944:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 8945:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 8946: 
                   8947: }
                   8948: 
1.423     albertel 8949: =pod
                   8950: 
                   8951: =item scantron_putfile
                   8952: 
1.659     raeburn  8953:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 8954:     scan_data hash. (Does not modify the original version only the
                   8955:     corrected and skipped versions.
                   8956: 
                   8957:  Arguments:
                   8958:     $scanlines - hash ref that looks like the first return value from
                   8959:                  &scantron_getfile()
                   8960:     $scan_data - hash ref that looks like the second return value from
                   8961:                  &scantron_getfile()
                   8962: 
1.423     albertel 8963: =cut
                   8964: 
1.157     albertel 8965: sub scantron_putfile {
                   8966:     my ($scanlines,$scan_data) = @_;
1.200     albertel 8967:     #FIXME really would prefer a scantron directory
1.257     albertel 8968:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8969:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 8970:     if ($scanlines) {
                   8971: 	my $prefix='scantron_';
1.157     albertel 8972: # no need to update orig, shouldn't change
                   8973: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 8974: #		    $env{'form.scantron_selectfile'});
1.200     albertel 8975: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   8976: 			$prefix.'corrected_'.
1.257     albertel 8977: 			$env{'form.scantron_selectfile'});
1.200     albertel 8978: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   8979: 			$prefix.'skipped_'.
1.257     albertel 8980: 			$env{'form.scantron_selectfile'});
1.200     albertel 8981:     }
1.175     albertel 8982:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 8983: }
                   8984: 
1.423     albertel 8985: =pod
                   8986: 
                   8987: =item scantron_get_line
                   8988: 
1.424     albertel 8989:    Returns the correct version of the scanline
                   8990: 
                   8991:  Arguments:
                   8992:     $scanlines - hash ref that looks like the first return value from
                   8993:                  &scantron_getfile()
                   8994:     $scan_data - hash ref that looks like the second return value from
                   8995:                  &scantron_getfile()
                   8996:     $i         - number of the requested line (starts at 0)
                   8997: 
                   8998:  Returns:
                   8999:    A scanline, (either the original or the corrected one if it
                   9000:    exists), or undef if the requested scanline should be
                   9001:    skipped. (Either because it's an skipped scanline, or it's an
                   9002:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   9003:    pass.
                   9004: 
1.423     albertel 9005: =cut
                   9006: 
1.157     albertel 9007: sub scantron_get_line {
1.200     albertel 9008:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 9009:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   9010:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 9011:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   9012:     return $scanlines->{'orig'}[$i]; 
                   9013: }
                   9014: 
1.423     albertel 9015: =pod
                   9016: 
                   9017: =item scantron_todo_count
                   9018: 
1.424     albertel 9019:     Counts the number of scanlines that need processing.
                   9020: 
                   9021:  Arguments:
                   9022:     $scanlines - hash ref that looks like the first return value from
                   9023:                  &scantron_getfile()
                   9024:     $scan_data - hash ref that looks like the second return value from
                   9025:                  &scantron_getfile()
                   9026: 
                   9027:  Returns:
                   9028:     $count - number of scanlines to process
                   9029: 
1.423     albertel 9030: =cut
                   9031: 
1.200     albertel 9032: sub get_todo_count {
                   9033:     my ($scanlines,$scan_data)=@_;
                   9034:     my $count=0;
                   9035:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   9036: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   9037: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9038: 	$count++;
                   9039:     }
                   9040:     return $count;
                   9041: }
                   9042: 
1.423     albertel 9043: =pod
                   9044: 
                   9045: =item scantron_put_line
                   9046: 
1.659     raeburn  9047:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 9048:     data file.
                   9049: 
                   9050:  Arguments:
                   9051:     $scanlines - hash ref that looks like the first return value from
                   9052:                  &scantron_getfile()
                   9053:     $scan_data - hash ref that looks like the second return value from
                   9054:                  &scantron_getfile()
                   9055:     $i         - line number to update
                   9056:     $newline   - contents of the updated scanline
                   9057:     $skip      - if true make the line for skipping and update the
                   9058:                  'skipped' file
                   9059: 
1.423     albertel 9060: =cut
                   9061: 
1.157     albertel 9062: sub scantron_put_line {
1.200     albertel 9063:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 9064:     if ($skip) {
                   9065: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 9066: 	&start_skipping($scan_data,$i);
1.157     albertel 9067: 	return;
                   9068:     }
                   9069:     $scanlines->{'corrected'}[$i]=$newline;
                   9070: }
                   9071: 
1.423     albertel 9072: =pod
                   9073: 
                   9074: =item scantron_clear_skip
                   9075: 
1.424     albertel 9076:    Remove a line from the 'skipped' file
                   9077: 
                   9078:  Arguments:
                   9079:     $scanlines - hash ref that looks like the first return value from
                   9080:                  &scantron_getfile()
                   9081:     $scan_data - hash ref that looks like the second return value from
                   9082:                  &scantron_getfile()
                   9083:     $i         - line number to update
                   9084: 
1.423     albertel 9085: =cut
                   9086: 
1.376     albertel 9087: sub scantron_clear_skip {
                   9088:     my ($scanlines,$scan_data,$i)=@_;
                   9089:     if (exists($scanlines->{'skipped'}[$i])) {
                   9090: 	undef($scanlines->{'skipped'}[$i]);
                   9091: 	return 1;
                   9092:     }
                   9093:     return 0;
                   9094: }
                   9095: 
1.423     albertel 9096: =pod
                   9097: 
                   9098: =item scantron_filter_not_exam
                   9099: 
1.424     albertel 9100:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   9101:    filter out resources that are not marked as 'exam' mode
                   9102: 
1.423     albertel 9103: =cut
                   9104: 
1.334     albertel 9105: sub scantron_filter_not_exam {
                   9106:     my ($curres)=@_;
                   9107:     
                   9108:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   9109: 	# if the user has asked to not have either hidden
                   9110: 	# or 'randomout' controlled resources to be graded
                   9111: 	# don't include them
                   9112: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   9113: 	    && $curres->randomout) {
                   9114: 	    return 0;
                   9115: 	}
                   9116: 	return 1;
                   9117:     }
                   9118:     return 0;
                   9119: }
                   9120: 
1.423     albertel 9121: =pod
                   9122: 
                   9123: =item scantron_validate_sequence
                   9124: 
1.424     albertel 9125:     Validates the selected sequence, checking for resource that are
                   9126:     not set to exam mode.
                   9127: 
1.423     albertel 9128: =cut
                   9129: 
1.334     albertel 9130: sub scantron_validate_sequence {
                   9131:     my ($r,$currentphase) = @_;
                   9132: 
                   9133:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9134:     unless (ref($navmap)) {
                   9135:         $r->print(&navmap_errormsg());
                   9136:         return (1,$currentphase);
                   9137:     }
1.334     albertel 9138:     my (undef,undef,$sequence)=
                   9139: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9140: 
                   9141:     my $map=$navmap->getResourceByUrl($sequence);
                   9142: 
                   9143:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   9144:                                     value="ignore" />');
                   9145:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   9146: 	my @resources=
                   9147: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   9148: 	if (@resources) {
1.675     bisitz   9149: 	    $r->print(
                   9150:                 '<p class="LC_warning">'
                   9151:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   9152:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   9153:                    .' work correctly.')
                   9154:                .'</p>'
                   9155:             );
1.334     albertel 9156: 	    return (1,$currentphase);
                   9157: 	}
                   9158:     }
                   9159: 
                   9160:     return (0,$currentphase+1);
                   9161: }
                   9162: 
1.423     albertel 9163: 
                   9164: 
1.157     albertel 9165: sub scantron_validate_ID {
1.770     raeburn  9166:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 9167:     
                   9168:     #get student info
                   9169:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9170:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  9171:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 9172: 
                   9173:     #get scantron line setup
1.754     raeburn  9174:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9175:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  9176: 
                   9177:     my $nav_error;
1.649     raeburn  9178:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  9179:     if ($nav_error) {
                   9180:         $r->print(&navmap_errormsg());
                   9181:         return(1,$currentphase);
                   9182:     }
1.157     albertel 9183: 
                   9184:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  9185:     my $unsavedskips = 0;
1.157     albertel 9186:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9187: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9188: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9189: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9190: 						 $scan_data);
                   9191: 	my $id=$$scan_record{'scantron.ID'};
                   9192: 	my $found;
                   9193: 	foreach my $checkid (keys(%idmap)) {
                   9194: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   9195: 	}
                   9196: 	if ($found) {
                   9197: 	    my $username=$idmap{$found};
1.770     raeburn  9198:             if ($checksec) {
                   9199:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   9200:                     my $stusec = $classlist->{$username}->[$secidx];
                   9201:                     if ($stusec ne $checksec) {
                   9202:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9203:                             my $skip=1;
                   9204:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9205:                             if (ref($skipbysec) eq 'HASH') {
                   9206:                                 if ($stusec eq '') {
                   9207:                                     $skipbysec->{'none'} ++;
                   9208:                                 } else {
                   9209:                                     $skipbysec->{$stusec} ++;
                   9210:                                 }
                   9211:                             }
                   9212:                             $unsavedskips ++;
                   9213:                             next;
                   9214:                         }
                   9215:                     }
                   9216:                 }
                   9217:             }
1.157     albertel 9218: 	    if ($found{'ids'}{$found}) {
                   9219: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9220: 					 $line,'duplicateID',$found);
1.770     raeburn  9221:                 if ($unsavedskips) {
                   9222:                     &scantron_putfile($scanlines,$scan_data);
                   9223:                     $unsavedskips = 0;
                   9224:                 }
1.194     albertel 9225: 		return(1,$currentphase);
1.157     albertel 9226: 	    } elsif ($found{'usernames'}{$username}) {
                   9227: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9228: 					 $line,'duplicateID',$username);
1.770     raeburn  9229:                 if ($unsavedskips) {
                   9230:                     &scantron_putfile($scanlines,$scan_data);
                   9231:                     $unsavedskips = 0;
                   9232:                 }
1.194     albertel 9233: 		return(1,$currentphase);
1.157     albertel 9234: 	    }
1.186     albertel 9235: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 9236: 	    $found{'ids'}{$found}++;
                   9237: 	    $found{'usernames'}{$username}++;
                   9238: 	} else {
                   9239: 	    if ($id =~ /^\s*$/) {
1.158     albertel 9240: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  9241:                 if (($checksec && $username ne '')) {
                   9242:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   9243:                         my $stusec = $classlist->{$username}->[$secidx];
                   9244:                         if ($stusec ne $checksec) {
                   9245:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9246:                                 my $skip=1;
                   9247:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9248:                                 if (ref($skipbysec) eq 'HASH') {
                   9249:                                     if ($stusec eq '') {
                   9250:                                         $skipbysec->{'none'} ++;
                   9251:                                     } else {
                   9252:                                         $skipbysec->{$stusec} ++;
                   9253:                                     }
                   9254:                                 }
                   9255:                                 $unsavedskips ++;
                   9256:                                 next;
                   9257:                             }
                   9258:                         }
                   9259:                     }
                   9260: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 9261: 		    &scantron_get_correction($r,$i,$scan_record,
                   9262: 					     \%scantron_config,
                   9263: 					     $line,'duplicateID',$username);
1.770     raeburn  9264:                     if ($unsavedskips) {
                   9265:                         &scantron_putfile($scanlines,$scan_data);
                   9266:                         $unsavedskips = 0;
                   9267:                     }
1.194     albertel 9268: 		    return(1,$currentphase);
1.157     albertel 9269: 		} elsif (!defined($username)) {
                   9270: 		    &scantron_get_correction($r,$i,$scan_record,
                   9271: 					     \%scantron_config,
                   9272: 					     $line,'incorrectID');
1.770     raeburn  9273:                     if ($unsavedskips) {
                   9274:                         &scantron_putfile($scanlines,$scan_data);
                   9275:                         $unsavedskips = 0;
                   9276:                     }
1.194     albertel 9277: 		    return(1,$currentphase);
1.157     albertel 9278: 		}
                   9279: 		$found{'usernames'}{$username}++;
                   9280: 	    } else {
                   9281: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9282: 					 $line,'incorrectID');
1.770     raeburn  9283:                 if ($unsavedskips) {
                   9284:                     &scantron_putfile($scanlines,$scan_data);
                   9285:                     $unsavedskips = 0;
                   9286:                 }
1.194     albertel 9287: 		return(1,$currentphase);
1.157     albertel 9288: 	    }
                   9289: 	}
                   9290:     }
1.770     raeburn  9291:     if ($unsavedskips) {
                   9292:         &scantron_putfile($scanlines,$scan_data);
                   9293:         $unsavedskips = 0;
                   9294:     }
1.157     albertel 9295:     return (0,$currentphase+1);
                   9296: }
                   9297: 
1.770     raeburn  9298: sub scantron_get_sections {
                   9299:     my %bysec;
                   9300:     if ($env{'form.scantron_format'} ne '') {
                   9301:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   9302:         my ($scanlines,$scan_data)=&scantron_getfile();
                   9303:         my $classlist=&Apache::loncoursedata::get_classlist();
                   9304:         my %idmap=&username_to_idmap($classlist);
                   9305:         foreach my $key (keys(%idmap)) {
                   9306:             my $lckey = lc($key);
                   9307:             $idmap{$lckey} = $idmap{$key};
                   9308:         }
                   9309:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   9310:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   9311:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   9312:             if ($line=~/^[\s\cz]*$/) { next; }
                   9313:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9314:                                                      $scan_data);
                   9315:             my $id=lc($$scan_record{'scantron.ID'});
                   9316:             if (exists($idmap{$id})) {
                   9317:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9318:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9319:                     if ($stusec eq '') {
                   9320:                         $bysec{'none'} ++;
                   9321:                     } else {
                   9322:                         $bysec{$stusec} ++;
                   9323:                     }
                   9324:                 }
                   9325:             }
                   9326:         }
                   9327:     }
                   9328:     return %bysec;
                   9329: }
1.423     albertel 9330: 
1.157     albertel 9331: sub scantron_get_correction {
1.691     raeburn  9332:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   9333:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 9334: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 9335: #to show both the current line and the previous one and allow skipping
                   9336: #the previous one or the current one
                   9337: 
1.333     albertel 9338:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   9339:         $r->print(
                   9340:             '<p class="LC_warning">'
                   9341:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   9342:                 "<b>$error</b>",
                   9343:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   9344:            ."</p> \n");
1.157     albertel 9345:     } else {
1.658     bisitz   9346:         $r->print(
                   9347:             '<p class="LC_warning">'
                   9348:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   9349:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   9350:            ."</p> \n");
                   9351:     }
                   9352:     my $message =
                   9353:         '<p>'
                   9354:        .&mt('The ID on the form is [_1]',
                   9355:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   9356:        .'<br />'
1.665     raeburn  9357:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   9358:             $$scan_record{'scantron.LastName'},
                   9359:             $$scan_record{'scantron.FirstName'})
                   9360:        .'</p>';
1.242     albertel 9361: 
1.157     albertel 9362:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   9363:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  9364:                            # Array populated for doublebubble or
                   9365:     my @lines_to_correct;  # missingbubble errors to build javascript
                   9366:                            # to validate radio button checking   
                   9367: 
1.157     albertel 9368:     if ($error =~ /ID$/) {
1.186     albertel 9369: 	if ($error eq 'incorrectID') {
1.658     bisitz   9370:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 9371: 		      "</p>\n");
1.157     albertel 9372: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   9373:             $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 9374: 	}
1.242     albertel 9375: 	$r->print($message);
1.492     albertel 9376: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 9377: 	$r->print("\n<ul><li> ");
                   9378: 	#FIXME it would be nice if this sent back the user ID and
                   9379: 	#could do partial userID matches
                   9380: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   9381: 				       'scantron_username','scantron_domain'));
                   9382: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   9383: 	$r->print("\n:\n".
1.257     albertel 9384: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 9385: 
                   9386: 	$r->print('</li>');
1.186     albertel 9387:     } elsif ($error =~ /CODE$/) {
                   9388: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   9389: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 9390: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   9391: 	    $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 9392: 	}
1.658     bisitz   9393: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   9394: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   9395:                  ."</p>\n");
1.242     albertel 9396: 	$r->print($message);
1.658     bisitz   9397: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 9398: 	$r->print("\n<br /> ");
1.194     albertel 9399: 	my $i=0;
1.273     albertel 9400: 	if ($error eq 'incorrectCODE' 
                   9401: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 9402: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 9403: 	    if ($closest > 0) {
                   9404: 		foreach my $testcode (@{$closest}) {
                   9405: 		    my $checked='';
1.569     bisitz   9406: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9407: 		    $r->print("
                   9408:    <label>
1.569     bisitz   9409:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 9410:        ".&mt("Use the similar CODE [_1] instead.",
                   9411: 	    "<b><tt>".$testcode."</tt></b>")."
                   9412:     </label>
                   9413:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 9414: 		    $r->print("\n<br />");
                   9415: 		    $i++;
                   9416: 		}
1.194     albertel 9417: 	    }
                   9418: 	}
1.273     albertel 9419: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   9420: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9421: 	    $r->print("
                   9422:     <label>
1.569     bisitz   9423:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  9424:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 9425: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   9426:     </label>");
1.273     albertel 9427: 	    $r->print("\n<br />");
                   9428: 	}
1.194     albertel 9429: 
1.597     wenzelju 9430: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 9431: function change_radio(field) {
1.190     albertel 9432:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 9433:     var i;
                   9434:     for (i=0;i<slct.length;i++) {
                   9435:         if (slct[i].value==field) { slct[i].checked=true; }
                   9436:     }
                   9437: }
                   9438: ENDSCRIPT
1.187     albertel 9439: 	my $href="/adm/pickcode?".
1.359     www      9440: 	   "form=".&escape("scantronupload").
                   9441: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   9442: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   9443: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   9444: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 9445: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 9446: 	    $r->print("
                   9447:     <label>
                   9448:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   9449:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   9450: 	     "<a target='_blank' href='$href'>","</a>")."
                   9451:     </label> 
1.558     bisitz   9452:     ".&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 9453: 	    $r->print("\n<br />");
                   9454: 	}
1.492     albertel 9455: 	$r->print("
                   9456:     <label>
                   9457:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   9458:        ".&mt("Use [_1] as the CODE.",
                   9459: 	     "</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 9460: 	$r->print("\n<br /><br />");
1.157     albertel 9461:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   9462: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     9463: 
                   9464: 	# The form field scantron_questions is acutally a list of line numbers.
                   9465: 	# represented by this form so:
                   9466: 
1.691     raeburn  9467: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9468:                                                 $respnumlookup,$startline);
1.497     foxr     9469: 
1.157     albertel 9470: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9471: 		  $line_list.'" />');
1.242     albertel 9472: 	$r->print($message);
1.492     albertel 9473: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 9474: 	foreach my $question (@{$arg}) {
1.503     raeburn  9475: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9476:                                                    $scan_record, $error,
                   9477:                                                    $randomorder,$randompick,
                   9478:                                                    $respnumlookup,$startline);
1.524     raeburn  9479:             push(@lines_to_correct,@linenums);
1.157     albertel 9480: 	}
1.503     raeburn  9481:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9482:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   9483: 	$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 9484: 	$r->print($message);
1.492     albertel 9485: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  9486: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     9487: 
1.503     raeburn  9488: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     9489: 	# a list of question numbers. Therefore:
                   9490: 	#
1.691     raeburn  9491: 
                   9492: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9493:                                                 $respnumlookup,$startline);
1.497     foxr     9494: 
1.157     albertel 9495: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9496: 		  $line_list.'" />');
1.157     albertel 9497: 	foreach my $question (@{$arg}) {
1.503     raeburn  9498: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9499:                                                    $scan_record, $error,
                   9500:                                                    $randomorder,$randompick,
                   9501:                                                    $respnumlookup,$startline);
1.524     raeburn  9502:             push(@lines_to_correct,@linenums);
1.157     albertel 9503: 	}
1.503     raeburn  9504:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9505:     } else {
                   9506: 	$r->print("\n<ul>");
                   9507:     }
                   9508:     $r->print("\n</li></ul>");
1.497     foxr     9509: }
                   9510: 
1.503     raeburn  9511: sub verify_bubbles_checked {
                   9512:     my (@ansnums) = @_;
                   9513:     my $ansnumstr = join('","',@ansnums);
                   9514:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  9515:     &js_escape(\$warning);
1.767     raeburn  9516:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  9517: function verify_bubble_radio(form) {
                   9518:     var ansnumArray = new Array ("$ansnumstr");
                   9519:     var need_bubble_count = 0;
                   9520:     for (var i=0; i<ansnumArray.length; i++) {
                   9521:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   9522:             var bubble_picked = 0; 
                   9523:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   9524:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   9525:                     bubble_picked = 1;
                   9526:                 }
                   9527:             }
                   9528:             if (bubble_picked == 0) {
                   9529:                 need_bubble_count ++;
                   9530:             }
                   9531:         }
                   9532:     }
                   9533:     if (need_bubble_count) {
                   9534:         alert("$warning");
                   9535:         return;
                   9536:     }
                   9537:     form.submit(); 
                   9538: }
                   9539: ENDSCRIPT
                   9540:     return $output;
                   9541: }
                   9542: 
1.497     foxr     9543: =pod
                   9544: 
                   9545: =item  questions_to_line_list
1.157     albertel 9546: 
1.497     foxr     9547: Converts a list of questions into a string of comma separated
                   9548: line numbers in the answer sheet used by the questions.  This is
                   9549: used to fill in the scantron_questions form field.
                   9550: 
                   9551:   Arguments:
                   9552:      questions    - Reference to an array of questions.
1.691     raeburn  9553:      randomorder  - True if randomorder in use.
                   9554:      randompick   - True if randompick in use.
                   9555:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9556:                      for current line to question number used for same question
                   9557:                      in "Master Seqence" (as seen by Course Coordinator).
                   9558:      startline    - Reference to hash where key is question number (0 is first)
                   9559:                     and key is number of first bubble line for current student
                   9560:                     or code-based randompick and/or randomorder.
1.693     raeburn  9561: 
1.497     foxr     9562: =cut
                   9563: 
                   9564: 
                   9565: sub questions_to_line_list {
1.691     raeburn  9566:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     9567:     my @lines;
                   9568: 
1.503     raeburn  9569:     foreach my $item (@{$questions}) {
                   9570:         my $question = $item;
                   9571:         my ($first,$count,$last);
                   9572:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   9573:             $question = $1;
                   9574:             my $subquestion = $2;
1.691     raeburn  9575:             my $responsenum = $question-1;
                   9576:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9577:                 $responsenum = $respnumlookup->{$question-1};
                   9578:                 if (ref($startline) eq 'HASH') {
                   9579:                     $first = $startline->{$question-1} + 1;
                   9580:                 }
                   9581:             } else {
                   9582:                 $first = $first_bubble_line{$responsenum} + 1;
                   9583:             }
                   9584:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9585:             my $subcount = 1;
                   9586:             while ($subcount<$subquestion) {
                   9587:                 $first += $subans[$subcount-1];
                   9588:                 $subcount ++;
                   9589:             }
                   9590:             $count = $subans[$subquestion-1];
                   9591:         } else {
1.691     raeburn  9592:             my $responsenum = $question-1;
                   9593:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9594:                 $responsenum = $respnumlookup->{$question-1};
                   9595:                 if (ref($startline) eq 'HASH') {
                   9596:                     $first = $startline->{$question-1} + 1;
                   9597:                 }
                   9598:             } else {
                   9599:                 $first = $first_bubble_line{$responsenum} + 1;
                   9600:             }
                   9601: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9602:         }
1.506     raeburn  9603:         $last = $first+$count-1;
1.503     raeburn  9604:         push(@lines, ($first..$last));
1.497     foxr     9605:     }
                   9606:     return join(',', @lines);
                   9607: }
                   9608: 
                   9609: =pod 
                   9610: 
                   9611: =item prompt_for_corrections
                   9612: 
                   9613: Prompts for a potentially multiline correction to the
                   9614: user's bubbling (factors out common code from scantron_get_correction
                   9615: for multi and missing bubble cases).
                   9616: 
                   9617:  Arguments:
                   9618:    $r           - Apache request object.
                   9619:    $question    - The question number to prompt for.
                   9620:    $scan_config - The scantron file configuration hash.
                   9621:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  9622:    $error       - Type of error
1.691     raeburn  9623:    $randomorder - True if randomorder in use.
                   9624:    $randompick  - True if randompick in use.
                   9625:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9626:                     for current line to question number used for same question
                   9627:                     in "Master Seqence" (as seen by Course Coordinator).
                   9628:    $startline   - Reference to hash where key is question number (0 is first)
                   9629:                   and value is number of first bubble line for current student
                   9630:                   or code-based randompick and/or randomorder.
                   9631: 
1.497     foxr     9632: 
                   9633:  Implicit inputs:
                   9634:    %bubble_lines_per_response   - Starting line numbers for each question.
                   9635:                                   Numbered from 0 (but question numbers are from
                   9636:                                   1.
                   9637:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  9638:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   9639:                                   type problems render as separate sub-questions, 
1.503     raeburn  9640:                                   in exam mode. This hash contains a 
                   9641:                                   comma-separated list of the lines per 
                   9642:                                   sub-question.
1.510     raeburn  9643:    %responsetype_per_response   - essayresponse, formularesponse,
                   9644:                                   stringresponse, imageresponse, reactionresponse,
                   9645:                                   and organicresponse type problem parts can have
1.503     raeburn  9646:                                   multiple lines per response if the weight
                   9647:                                   assigned exceeds 10.  In this case, only
                   9648:                                   one bubble per line is permitted, but more 
                   9649:                                   than one line might contain bubbles, e.g.
                   9650:                                   bubbling of: line 1 - J, line 2 - J, 
                   9651:                                   line 3 - B would assign 22 points.  
1.497     foxr     9652: 
                   9653: =cut
                   9654: 
                   9655: sub prompt_for_corrections {
1.691     raeburn  9656:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   9657:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  9658:     my ($current_line,$lines);
                   9659:     my @linenums;
                   9660:     my $questionnum = $question;
1.691     raeburn  9661:     my ($first,$responsenum);
1.503     raeburn  9662:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   9663:         $question = $1;
                   9664:         my $subquestion = $2;
1.691     raeburn  9665:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9666:             $responsenum = $respnumlookup->{$question-1};
                   9667:             if (ref($startline) eq 'HASH') {
                   9668:                 $first = $startline->{$question-1};
                   9669:             }
                   9670:         } else {
                   9671:             $responsenum = $question-1;
1.714     raeburn  9672:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  9673:         }
                   9674:         $current_line = $first + 1 ;
                   9675:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9676:         my $subcount = 1;
                   9677:         while ($subcount<$subquestion) {
                   9678:             $current_line += $subans[$subcount-1];
                   9679:             $subcount ++;
                   9680:         }
                   9681:         $lines = $subans[$subquestion-1];
                   9682:     } else {
1.691     raeburn  9683:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9684:             $responsenum = $respnumlookup->{$question-1};
                   9685:             if (ref($startline) eq 'HASH') { 
                   9686:                 $first = $startline->{$question-1};
                   9687:             }
                   9688:         } else {
                   9689:             $responsenum = $question-1;
                   9690:             $first = $first_bubble_line{$responsenum};
                   9691:         }
                   9692:         $current_line = $first + 1;
                   9693:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9694:     }
1.497     foxr     9695:     if ($lines > 1) {
1.503     raeburn  9696:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  9697:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   9698:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   9699:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   9700:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   9701:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   9702:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   9703:             $r->print(
                   9704:                 &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)
                   9705:                .'<br /><br />'
                   9706:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   9707:                .'<br />'
                   9708:                .&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.')
                   9709:                .'<br />'
                   9710:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   9711:                .'<br /><br />'
                   9712:             );
1.503     raeburn  9713:         } else {
                   9714:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   9715:         }
1.497     foxr     9716:     }
                   9717:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  9718:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  9719: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  9720: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  9721:         push(@linenums,$current_line);
1.497     foxr     9722: 	$current_line++;
                   9723:     }
                   9724:     if ($lines > 1) {
                   9725: 	$r->print("<hr /><br />");
                   9726:     }
1.503     raeburn  9727:     return @linenums;
1.157     albertel 9728: }
1.423     albertel 9729: 
                   9730: =pod
                   9731: 
                   9732: =item scantron_bubble_selector
                   9733:   
                   9734:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 9735:    possibly showing the existing the selected bubbles if known
1.423     albertel 9736: 
                   9737:  Arguments:
                   9738:     $r           - Apache request object
1.754     raeburn  9739:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     9740:     $line        - Number of the line being displayed.
1.503     raeburn  9741:     $questionnum - Question number (may include subquestion)
                   9742:     $error       - Type of error.
1.497     foxr     9743:     @selected    - Array of bubbles picked on this line.
1.423     albertel 9744: 
                   9745: =cut
                   9746: 
1.157     albertel 9747: sub scantron_bubble_selector {
1.503     raeburn  9748:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 9749:     my $max=$$scan_config{'Qlength'};
1.274     albertel 9750: 
                   9751:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  9752:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   9753:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   9754:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   9755:             $max=$$scan_config{'BubblesPerRow'};
                   9756:             if (($scmode eq 'number') && ($max > 10)) {
                   9757:                 $max = 10;
                   9758:             } elsif (($scmode eq 'letter') && $max > 26) {
                   9759:                 $max = 26;
                   9760:             }
                   9761:         } else {
                   9762:             $max = 10;
                   9763:         }
                   9764:     }
1.274     albertel 9765: 
1.157     albertel 9766:     my @alphabet=('A'..'Z');
1.503     raeburn  9767:     $r->print(&Apache::loncommon::start_data_table().
                   9768:               &Apache::loncommon::start_data_table_row());
                   9769:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     9770:     for (my $i=0;$i<$max+1;$i++) {
                   9771: 	$r->print("\n".'<td align="center">');
                   9772: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   9773: 	else { $r->print('&nbsp;'); }
                   9774: 	$r->print('</td>');
                   9775:     }
1.503     raeburn  9776:     $r->print(&Apache::loncommon::end_data_table_row().
                   9777:               &Apache::loncommon::start_data_table_row());
1.497     foxr     9778:     for (my $i=0;$i<$max;$i++) {
                   9779: 	$r->print("\n".
                   9780: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   9781: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   9782:     }
1.503     raeburn  9783:     my $nobub_checked = ' ';
                   9784:     if ($error eq 'missingbubble') {
                   9785:         $nobub_checked = ' checked = "checked" ';
                   9786:     }
                   9787:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   9788: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   9789:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   9790:               $line.'" value="'.$questionnum.'" /></td>');
                   9791:     $r->print(&Apache::loncommon::end_data_table_row().
                   9792:               &Apache::loncommon::end_data_table());
1.157     albertel 9793: }
                   9794: 
1.423     albertel 9795: =pod
                   9796: 
                   9797: =item num_matches
                   9798: 
1.424     albertel 9799:    Counts the number of characters that are the same between the two arguments.
                   9800: 
                   9801:  Arguments:
                   9802:    $orig - CODE from the scanline
                   9803:    $code - CODE to match against
                   9804: 
                   9805:  Returns:
                   9806:    $count - integer count of the number of same characters between the
                   9807:             two arguments
                   9808: 
1.423     albertel 9809: =cut
                   9810: 
1.194     albertel 9811: sub num_matches {
                   9812:     my ($orig,$code) = @_;
                   9813:     my @code=split(//,$code);
                   9814:     my @orig=split(//,$orig);
                   9815:     my $same=0;
                   9816:     for (my $i=0;$i<scalar(@code);$i++) {
                   9817: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   9818:     }
                   9819:     return $same;
                   9820: }
                   9821: 
1.423     albertel 9822: =pod
                   9823: 
                   9824: =item scantron_get_closely_matching_CODEs
                   9825: 
1.424     albertel 9826:    Cycles through all CODEs and finds the set that has the greatest
                   9827:    number of same characters as the provided CODE
                   9828: 
                   9829:  Arguments:
                   9830:    $allcodes - hash ref returned by &get_codes()
                   9831:    $CODE     - CODE from the current scanline
                   9832: 
                   9833:  Returns:
                   9834:    2 element list
                   9835:     - first elements is number of how closely matching the best fit is 
                   9836:       (5 means best set has 5 matching characters)
                   9837:     - second element is an arrary ref containing the set of valid CODEs
                   9838:       that best fit the passed in CODE
                   9839: 
1.423     albertel 9840: =cut
                   9841: 
1.194     albertel 9842: sub scantron_get_closely_matching_CODEs {
                   9843:     my ($allcodes,$CODE)=@_;
                   9844:     my @CODEs;
                   9845:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   9846: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   9847:     }
                   9848: 
                   9849:     return ($#CODEs,$CODEs[-1]);
                   9850: }
                   9851: 
1.423     albertel 9852: =pod
                   9853: 
                   9854: =item get_codes
                   9855: 
1.424     albertel 9856:    Builds a hash which has keys of all of the valid CODEs from the selected
                   9857:    set of remembered CODEs.
                   9858: 
                   9859:  Arguments:
                   9860:   $old_name - name of the set of remembered CODEs
                   9861:   $cdom     - domain of the course
                   9862:   $cnum     - internal course name
                   9863: 
                   9864:  Returns:
                   9865:   %allcodes - keys are the valid CODEs, values are all 1
                   9866: 
1.423     albertel 9867: =cut
                   9868: 
1.194     albertel 9869: sub get_codes {
1.280     foxr     9870:     my ($old_name, $cdom, $cnum) = @_;
                   9871:     if (!$old_name) {
                   9872: 	$old_name=$env{'form.scantron_CODElist'};
                   9873:     }
                   9874:     if (!$cdom) {
                   9875: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9876:     }
                   9877:     if (!$cnum) {
                   9878: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   9879:     }
1.278     albertel 9880:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   9881: 				    $cdom,$cnum);
                   9882:     my %allcodes;
                   9883:     if ($result{"type\0$old_name"} eq 'number') {
                   9884: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   9885:     } else {
                   9886: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   9887:     }
1.194     albertel 9888:     return %allcodes;
                   9889: }
                   9890: 
1.423     albertel 9891: =pod
                   9892: 
                   9893: =item scantron_validate_CODE
                   9894: 
1.424     albertel 9895:    Validates all scanlines in the selected file to not have any
                   9896:    invalid or underspecified CODEs and that none of the codes are
                   9897:    duplicated if this was requested.
                   9898: 
1.423     albertel 9899: =cut
                   9900: 
1.157     albertel 9901: sub scantron_validate_CODE {
                   9902:     my ($r,$currentphase) = @_;
1.754     raeburn  9903:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 9904:     if ($scantron_config{'CODElocation'} &&
                   9905: 	$scantron_config{'CODEstart'} &&
                   9906: 	$scantron_config{'CODElength'}) {
1.257     albertel 9907: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 9908: 	    &FIXME_blow_up()
                   9909: 	}
                   9910:     } else {
                   9911: 	return (0,$currentphase+1);
                   9912:     }
                   9913:     
                   9914:     my %usedCODEs;
                   9915: 
1.194     albertel 9916:     my %allcodes=&get_codes();
1.186     albertel 9917: 
1.582     raeburn  9918:     my $nav_error;
1.649     raeburn  9919:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  9920:     if ($nav_error) {
                   9921:         $r->print(&navmap_errormsg());
                   9922:         return(1,$currentphase);
                   9923:     }
1.447     foxr     9924: 
1.186     albertel 9925:     my ($scanlines,$scan_data)=&scantron_getfile();
                   9926:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9927: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 9928: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9929: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9930: 						 $scan_data);
                   9931: 	my $CODE=$$scan_record{'scantron.CODE'};
                   9932: 	my $error=0;
1.224     albertel 9933: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   9934: 	    &scantron_get_correction($r,$i,$scan_record,
                   9935: 				     \%scantron_config,
                   9936: 				     $line,'incorrectCODE',\%allcodes);
                   9937: 	    return(1,$currentphase);
                   9938: 	}
1.221     albertel 9939: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   9940: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 9941: 	    &scantron_get_correction($r,$i,$scan_record,
                   9942: 				     \%scantron_config,
1.194     albertel 9943: 				     $line,'incorrectCODE',\%allcodes);
                   9944: 	    return(1,$currentphase);
1.186     albertel 9945: 	}
1.214     albertel 9946: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 9947: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 9948: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 9949: 	    &scantron_get_correction($r,$i,$scan_record,
                   9950: 				     \%scantron_config,
1.194     albertel 9951: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   9952: 	    return(1,$currentphase);
1.186     albertel 9953: 	}
1.524     raeburn  9954: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 9955:     }
1.157     albertel 9956:     return (0,$currentphase+1);
                   9957: }
                   9958: 
1.423     albertel 9959: =pod
                   9960: 
                   9961: =item scantron_validate_doublebubble
                   9962: 
1.424     albertel 9963:    Validates all scanlines in the selected file to not have any
                   9964:    bubble lines with multiple bubbles marked.
                   9965: 
1.423     albertel 9966: =cut
                   9967: 
1.157     albertel 9968: sub scantron_validate_doublebubble {
                   9969:     my ($r,$currentphase) = @_;
                   9970:     #get student info
                   9971:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9972:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  9973:     my (undef,undef,$sequence)=
                   9974:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 9975: 
                   9976:     #get scantron line setup
1.754     raeburn  9977:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9978:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  9979: 
                   9980:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9981:     unless (ref($navmap)) {
                   9982:         $r->print(&navmap_errormsg());
                   9983:         return(1,$currentphase);
                   9984:     }
                   9985:     my $map=$navmap->getResourceByUrl($sequence);
                   9986:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9987:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9988:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   9989:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9990: 
1.583     raeburn  9991:     my $nav_error;
1.691     raeburn  9992:     if (ref($map)) {
                   9993:         $randomorder = $map->randomorder();
                   9994:         $randompick = $map->randompick();
1.788     raeburn  9995:         unless ($randomorder || $randompick) {
                   9996:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9997:                 if ($res->randomorder()) {
                   9998:                     $randomorder = 1;
                   9999:                 }
                   10000:                 if ($res->randompick()) {
                   10001:                     $randompick = 1;
                   10002:                 }
                   10003:                 last if ($randomorder || $randompick);
                   10004:             }
                   10005:         }
1.691     raeburn  10006:         if ($randomorder || $randompick) {
                   10007:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10008:             if ($nav_error) {
                   10009:                 $r->print(&navmap_errormsg());
                   10010:                 return(1,$currentphase);
                   10011:             }
                   10012:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10013:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   10014:         }
                   10015:     } else {
                   10016:         $r->print(&navmap_errormsg());
                   10017:         return(1,$currentphase);
                   10018:     }
                   10019: 
1.649     raeburn  10020:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  10021:     if ($nav_error) {
                   10022:         $r->print(&navmap_errormsg());
                   10023:         return(1,$currentphase);
                   10024:     }
1.447     foxr     10025: 
1.157     albertel 10026:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 10027: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10028: 	if ($line=~/^[\s\cz]*$/) { next; }
                   10029: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  10030: 						 $scan_data,undef,\%idmap,$randomorder,
                   10031:                                                  $randompick,$sequence,\@master_seq,
                   10032:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   10033:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 10034: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   10035: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   10036: 				 'doublebubble',
1.691     raeburn  10037: 				 $$scan_record{'scantron.doubleerror'},
                   10038:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 10039:     	return (1,$currentphase);
                   10040:     }
                   10041:     return (0,$currentphase+1);
                   10042: }
                   10043: 
1.423     albertel 10044: 
1.503     raeburn  10045: sub scantron_get_maxbubble {
1.649     raeburn  10046:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 10047:     if (defined($env{'form.scantron_maxbubble'}) &&
                   10048: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     10049: 	&restore_bubble_lines();
1.257     albertel 10050: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 10051:     }
1.330     albertel 10052: 
1.447     foxr     10053:     my (undef, undef, $sequence) =
1.257     albertel 10054: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 10055: 
1.447     foxr     10056:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10057:     unless (ref($navmap)) {
                   10058:         if (ref($nav_error)) {
                   10059:             $$nav_error = 1;
                   10060:         }
1.591     raeburn  10061:         return;
1.582     raeburn  10062:     }
1.191     albertel 10063:     my $map=$navmap->getResourceByUrl($sequence);
                   10064:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  10065:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 10066: 
                   10067:     &Apache::lonxml::clear_problem_counter();
                   10068: 
1.557     raeburn  10069:     my $uname       = $env{'user.name'};
                   10070:     my $udom        = $env{'user.domain'};
1.435     foxr     10071:     my $cid         = $env{'request.course.id'};
                   10072:     my $total_lines = 0;
                   10073:     %bubble_lines_per_response = ();
1.447     foxr     10074:     %first_bubble_line         = ();
1.503     raeburn  10075:     %subdivided_bubble_lines   = ();
                   10076:     %responsetype_per_response = ();
1.691     raeburn  10077:     %masterseq_id_responsenum  = ();
1.554     raeburn  10078: 
1.447     foxr     10079:     my $response_number = 0;
                   10080:     my $bubble_line     = 0;
1.191     albertel 10081:     foreach my $resource (@resources) {
1.691     raeburn  10082:         my $resid = $resource->id(); 
1.672     raeburn  10083:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   10084:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  10085:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   10086: 	    foreach my $part_id (@{$parts}) {
                   10087:                 my $lines;
                   10088: 
                   10089: 	        # TODO - make this a persistent hash not an array.
                   10090: 
                   10091:                 # optionresponse, matchresponse and rankresponse type items 
                   10092:                 # render as separate sub-questions in exam mode.
                   10093:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   10094:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   10095:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   10096:                     my ($numbub,$numshown);
                   10097:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   10098:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   10099:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   10100:                         }
                   10101:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   10102:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   10103:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   10104:                         }
                   10105:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   10106:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   10107:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   10108:                         }
                   10109:                     }
                   10110:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   10111:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   10112:                     }
1.649     raeburn  10113:                     my $bubbles_per_row =
                   10114:                         &bubblesheet_bubbles_per_row($scantron_config);
                   10115:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   10116:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  10117:                         $inner_bubble_lines++;
                   10118:                     }
                   10119:                     for (my $i=0; $i<$numshown; $i++) {
                   10120:                         $subdivided_bubble_lines{$response_number} .= 
                   10121:                             $inner_bubble_lines.',';
                   10122:                     }
                   10123:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   10124:                     $lines = $numshown * $inner_bubble_lines;
                   10125:                 } else {
                   10126:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  10127:                 }
1.542     raeburn  10128: 
                   10129:                 $first_bubble_line{$response_number} = $bubble_line;
                   10130: 	        $bubble_lines_per_response{$response_number} = $lines;
                   10131:                 $responsetype_per_response{$response_number} = 
                   10132:                     $analysis->{$part_id.'.type'};
1.691     raeburn  10133:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  10134: 	        $response_number++;
                   10135: 
                   10136: 	        $bubble_line +=  $lines;
                   10137: 	        $total_lines +=  $lines;
                   10138: 	    }
                   10139:         }
                   10140:     }
1.552     raeburn  10141:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  10142: 
                   10143:     &save_bubble_lines();
                   10144:     $env{'form.scantron_maxbubble'} =
                   10145: 	$total_lines;
                   10146:     return $env{'form.scantron_maxbubble'};
                   10147: }
1.523     raeburn  10148: 
1.649     raeburn  10149: sub bubblesheet_bubbles_per_row {
                   10150:     my ($scantron_config) = @_;
                   10151:     my $bubbles_per_row;
                   10152:     if (ref($scantron_config) eq 'HASH') {
                   10153:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   10154:     }
                   10155:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   10156:         $bubbles_per_row = 10;
                   10157:     }
                   10158:     return $bubbles_per_row;
                   10159: }
                   10160: 
1.157     albertel 10161: sub scantron_validate_missingbubbles {
                   10162:     my ($r,$currentphase) = @_;
                   10163:     #get student info
                   10164:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10165:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  10166:     my (undef,undef,$sequence)=
                   10167:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 10168: 
                   10169:     #get scantron line setup
1.754     raeburn  10170:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 10171:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  10172: 
                   10173:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10174:     unless (ref($navmap)) {
                   10175:         $r->print(&navmap_errormsg());
                   10176:         return(1,$currentphase);
                   10177:     }
                   10178: 
                   10179:     my $map=$navmap->getResourceByUrl($sequence);
                   10180:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10181:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10182:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   10183:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10184: 
1.582     raeburn  10185:     my $nav_error;
1.691     raeburn  10186:     if (ref($map)) {
                   10187:         $randomorder = $map->randomorder();
                   10188:         $randompick = $map->randompick();
1.788     raeburn  10189:         unless ($randomorder || $randompick) {
                   10190:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10191:                 if ($res->randomorder()) {
                   10192:                     $randomorder = 1;
                   10193:                 }
                   10194:                 if ($res->randompick()) {
                   10195:                     $randompick = 1;
                   10196:                 }
                   10197:                 last if ($randomorder || $randompick);
                   10198:             }
                   10199:         }
1.691     raeburn  10200:         if ($randomorder || $randompick) {
                   10201:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10202:             if ($nav_error) {
                   10203:                 $r->print(&navmap_errormsg());
                   10204:                 return(1,$currentphase);
                   10205:             }
                   10206:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10207:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   10208:         }
                   10209:     } else {
                   10210:         $r->print(&navmap_errormsg());
                   10211:         return(1,$currentphase);
                   10212:     }
                   10213: 
                   10214: 
1.649     raeburn  10215:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  10216:     if ($nav_error) {
1.691     raeburn  10217:         $r->print(&navmap_errormsg());
1.693     raeburn  10218:         return(1,$currentphase);
1.582     raeburn  10219:     }
1.691     raeburn  10220: 
1.157     albertel 10221:     if (!$max_bubble) { $max_bubble=2**31; }
                   10222:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 10223: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10224: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  10225: 	my $scan_record =
                   10226:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   10227: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   10228:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   10229:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 10230: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   10231: 	my @to_correct;
1.470     foxr     10232: 	
                   10233: 	# Probably here's where the error is...
                   10234: 
1.157     albertel 10235: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  10236:             my $lastbubble;
                   10237:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   10238:                my $question = $1;
                   10239:                my $subquestion = $2;
1.691     raeburn  10240:                my ($first,$responsenum);
                   10241:                if ($randomorder || $randompick) {
                   10242:                    $responsenum = $respnumlookup{$question-1};
                   10243:                    $first = $startline{$question-1};
                   10244:                } else {
                   10245:                    $responsenum = $question-1; 
                   10246:                    $first = $first_bubble_line{$responsenum};
                   10247:                }
                   10248:                if (!defined($first)) { next; }
                   10249:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  10250:                my $subcount = 1;
                   10251:                while ($subcount<$subquestion) {
                   10252:                    $first += $subans[$subcount-1];
                   10253:                    $subcount ++;
                   10254:                }
                   10255:                my $count = $subans[$subquestion-1];
                   10256:                $lastbubble = $first + $count;
                   10257:             } else {
1.691     raeburn  10258:                my ($first,$responsenum);
                   10259:                if ($randomorder || $randompick) {
                   10260:                    $responsenum = $respnumlookup{$missing-1};
                   10261:                    $first = $startline{$missing-1};
                   10262:                } else {
                   10263:                    $responsenum = $missing-1;
                   10264:                    $first = $first_bubble_line{$responsenum};
                   10265:                }
                   10266:                if (!defined($first)) { next; }
                   10267:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  10268:             }
                   10269:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 10270: 	    push(@to_correct,$missing);
                   10271: 	}
                   10272: 	if (@to_correct) {
                   10273: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  10274: 				     $line,'missingbubble',\@to_correct,
                   10275:                                      $randomorder,$randompick,\%respnumlookup,
                   10276:                                      \%startline);
1.157     albertel 10277: 	    return (1,$currentphase);
                   10278: 	}
                   10279: 
                   10280:     }
                   10281:     return (0,$currentphase+1);
                   10282: }
                   10283: 
1.663     raeburn  10284: sub hand_bubble_option {
                   10285:     my (undef, undef, $sequence) =
                   10286:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10287:     return if ($sequence eq '');
                   10288:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10289:     unless (ref($navmap)) {
                   10290:         return;
                   10291:     }
                   10292:     my $needs_hand_bubbles;
                   10293:     my $map=$navmap->getResourceByUrl($sequence);
                   10294:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10295:     foreach my $res (@resources) {
                   10296:         if (ref($res)) {
                   10297:             if ($res->is_problem()) {
                   10298:                 my $partlist = $res->parts();
                   10299:                 foreach my $part (@{ $partlist }) {
                   10300:                     my @types = $res->responseType($part);
                   10301:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   10302:                         $needs_hand_bubbles = 1;
                   10303:                         last;
                   10304:                     }
                   10305:                 }
                   10306:             }
                   10307:         }
                   10308:     }
                   10309:     if ($needs_hand_bubbles) {
1.754     raeburn  10310:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  10311:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10312:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   10313:                &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 />').
                   10314:                '<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  10315:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  10316:     }
                   10317:     return;
                   10318: }
1.423     albertel 10319: 
1.82      albertel 10320: sub scantron_process_students {
1.608     www      10321:     my ($r,$symb) = @_;
1.513     foxr     10322: 
1.257     albertel 10323:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     10324:     if (!$symb) {
                   10325: 	return '';
                   10326:     }
1.324     albertel 10327:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 10328: 
1.754     raeburn  10329:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  10330:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 10331:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 10332:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10333:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 10334:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10335:     unless (ref($navmap)) {
                   10336:         $r->print(&navmap_errormsg());
                   10337:         return '';
1.691     raeburn  10338:     }
1.83      albertel 10339:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10340:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.788     raeburn  10341:         %grader_randomlists_by_symb,%symb_for_examcode);
1.677     raeburn  10342:     if (ref($map)) {
                   10343:         $randomorder = $map->randomorder();
1.689     raeburn  10344:         $randompick = $map->randompick();
1.788     raeburn  10345:         unless ($randomorder || $randompick) {
                   10346:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10347:                 if ($res->randomorder()) {
                   10348:                     $randomorder = 1;
                   10349:                 }
                   10350:                 if ($res->randompick()) {
                   10351:                     $randompick = 1;
                   10352:                 }
                   10353:                 last if ($randomorder || $randompick);
                   10354:             }
                   10355:         }
1.691     raeburn  10356:     } else {
                   10357:         $r->print(&navmap_errormsg());
                   10358:         return '';
1.677     raeburn  10359:     }
1.691     raeburn  10360:     my $nav_error;
1.83      albertel 10361:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10362:     if ($randomorder || $randompick) {
1.788     raeburn  10363:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
1.691     raeburn  10364:         if ($nav_error) {
                   10365:             $r->print(&navmap_errormsg());
                   10366:             return '';
                   10367:         }
                   10368:     }
1.557     raeburn  10369:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  10370:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  10371: 
1.554     raeburn  10372:     my ($uname,$udom);
1.82      albertel 10373:     my $result= <<SCANTRONFORM;
1.81      albertel 10374: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   10375:   <input type="hidden" name="command" value="scantron_configphase" />
                   10376:   $default_form_data
                   10377: SCANTRONFORM
1.82      albertel 10378:     $r->print($result);
                   10379: 
1.770     raeburn  10380:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 10381:     my @delayqueue;
1.542     raeburn  10382:     my (%completedstudents,%scandata);
1.770     raeburn  10383: 
1.520     www      10384:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 10385:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10386:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   10387:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  10388:     $r->print('<br />');
1.140     albertel 10389:     my $start=&Time::HiRes::time();
1.158     albertel 10390:     my $i=-1;
1.542     raeburn  10391:     my $started;
1.447     foxr     10392: 
1.649     raeburn  10393:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10394:     if ($nav_error) {
                   10395:         $r->print(&navmap_errormsg());
                   10396:         return '';
                   10397:     }
                   10398: 
1.513     foxr     10399:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   10400:     # the user and return.
                   10401: 
                   10402:     if ($ssi_error) {
                   10403: 	$r->print("</form>");
                   10404: 	&ssi_print_error($r);
1.520     www      10405:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     10406: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   10407:     }
1.447     foxr     10408: 
1.755     raeburn  10409:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  10410:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  10411:     my %orderedforcode;
1.542     raeburn  10412: 
1.157     albertel 10413:     while ($i<$scanlines->{'count'}) {
                   10414:  	($uname,$udom)=('','');
                   10415:  	$i++;
1.200     albertel 10416:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10417:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 10418: 	if ($started) {
1.667     www      10419: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 10420: 	}
                   10421: 	$started=1;
1.691     raeburn  10422:         my %respnumlookup = ();
                   10423:         my %startline = ();
                   10424:         my $total;
1.157     albertel 10425:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  10426:                                                  $scan_data,undef,\%idmap,$randomorder,
                   10427:                                                  $randompick,$sequence,\@master_seq,
                   10428:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   10429:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   10430:                                                  \$total);
1.157     albertel 10431:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10432:  					      \%idmap,$i)) {
                   10433:   	    &scantron_add_delay(\@delayqueue,$line,
                   10434:  				'Unable to find a student that matches',1);
                   10435:  	    next;
                   10436:   	}
                   10437:  	if (exists $completedstudents{$uname}) {
                   10438:  	    &scantron_add_delay(\@delayqueue,$line,
                   10439:  				'Student '.$uname.' has multiple sheets',2);
                   10440:  	    next;
                   10441:  	}
1.677     raeburn  10442:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  10443:         if (($checksec ne '') && ($checksec ne $usec)) {
                   10444:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   10445:                 &scantron_add_delay(\@delayqueue,$line,
                   10446:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   10447:                 next;
                   10448:             }
                   10449:         }
1.677     raeburn  10450:         my $user = $uname.':'.$usec;
1.157     albertel 10451:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 10452: 
1.677     raeburn  10453:         my $scancode;
                   10454:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10455:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10456:             $scancode = $scan_record->{'scantron.CODE'};
                   10457:         } else {
                   10458:             $scancode = '';
                   10459:         }
                   10460: 
                   10461:         my @mapresources = @resources;
1.689     raeburn  10462:         if ($randomorder || $randompick) {
1.678     raeburn  10463:             @mapresources = 
1.691     raeburn  10464:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10465:                              \%orderedforcode);
1.677     raeburn  10466:         }
1.586     raeburn  10467:         my (%partids_by_symb,$res_error);
1.677     raeburn  10468:         foreach my $resource (@mapresources) {
1.586     raeburn  10469:             my $ressymb;
                   10470:             if (ref($resource)) {
                   10471:                 $ressymb = $resource->symb();
                   10472:             } else {
                   10473:                 $res_error = 1;
                   10474:                 last;
                   10475:             }
1.557     raeburn  10476:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10477:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10478:                 my $currcode;
                   10479:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10480:                     $currcode = $scancode;
                   10481:                 }
1.557     raeburn  10482:                 my ($analysis,$parts) =
1.672     raeburn  10483:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  10484:                                               $uname,$udom,undef,$bubbles_per_row,
                   10485:                                               $currcode);
1.557     raeburn  10486:                 $partids_by_symb{$ressymb} = $parts;
                   10487:             } else {
                   10488:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   10489:             }
1.554     raeburn  10490:         }
                   10491: 
1.586     raeburn  10492:         if ($res_error) {
                   10493:             &scantron_add_delay(\@delayqueue,$line,
                   10494:                                 'An error occurred while grading student '.$uname,2);
                   10495:             next;
                   10496:         }
                   10497: 
1.330     albertel 10498: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  10499:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 10500: 
                   10501: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   10502: 	    &scantron_putfile($scanlines,$scan_data);
                   10503: 	}
1.161     albertel 10504: 	
1.542     raeburn  10505:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10506:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  10507:                                    $bubbles_per_row,$randomorder,$randompick,
                   10508:                                    \%respnumlookup,\%startline) 
                   10509:             eq 'ssi_error') {
1.542     raeburn  10510:             $ssi_error = 0; # So end of handler error message does not trigger.
                   10511:             $r->print("</form>");
                   10512:             &ssi_print_error($r);
                   10513:             &Apache::lonnet::remove_lock($lock);
                   10514:             return '';      # Why return ''?  Beats me.
                   10515:         }
1.513     foxr     10516: 
1.692     raeburn  10517:         if (($scancode) && ($randomorder || $randompick)) {
1.788     raeburn  10518:             foreach my $key (keys(%symb_for_examcode)) {
                   10519:                 my $symb_in_map = $symb_for_examcode{$key};
                   10520:                 if ($symb_in_map ne '') {
                   10521:                     my $parmresult =
                   10522:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   10523:                                                                '0_examcode',2,$scancode,
                   10524:                                                                'string_examcode',$uname,
                   10525:                                                                $udom);
                   10526:                 }
                   10527:             }
1.692     raeburn  10528:         }
1.140     albertel 10529: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  10530:         if ($env{'form.verifyrecord'}) {
                   10531:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  10532:             if ($randompick) {
                   10533:                 if ($total) {
                   10534:                     $lastpos = $total*$scantron_config{'Qlength'};
                   10535:                 }
                   10536:             }
                   10537: 
1.542     raeburn  10538:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10539:             chomp($studentdata);
                   10540:             $studentdata =~ s/\r$//;
                   10541:             my $studentrecord = '';
                   10542:             my $counter = -1;
1.677     raeburn  10543:             foreach my $resource (@mapresources) {
1.554     raeburn  10544:                 my $ressymb = $resource->symb();
1.542     raeburn  10545:                 ($counter,my $recording) =
                   10546:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10547:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10548:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   10549:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  10550:                 $studentrecord .= $recording;
                   10551:             }
                   10552:             if ($studentrecord ne $studentdata) {
1.554     raeburn  10553:                 &Apache::lonxml::clear_problem_counter();
                   10554:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10555:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  10556:                                            $bubbles_per_row,$randomorder,$randompick,
                   10557:                                            \%respnumlookup,\%startline) 
                   10558:                     eq 'ssi_error') {
1.554     raeburn  10559:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   10560:                     $r->print("</form>");
                   10561:                     &ssi_print_error($r);
                   10562:                     &Apache::lonnet::remove_lock($lock);
                   10563:                     delete($completedstudents{$uname});
                   10564:                     return '';
                   10565:                 }
1.542     raeburn  10566:                 $counter = -1;
                   10567:                 $studentrecord = '';
1.677     raeburn  10568:                 foreach my $resource (@mapresources) {
1.554     raeburn  10569:                     my $ressymb = $resource->symb();
1.542     raeburn  10570:                     ($counter,my $recording) =
                   10571:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10572:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10573:                                                  \%scantron_config,\%lettdig,$numletts,
                   10574:                                                  $randomorder,$randompick,\%respnumlookup,
                   10575:                                                  \%startline);
1.542     raeburn  10576:                     $studentrecord .= $recording;
                   10577:                 }
                   10578:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   10579:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  10580:                     if ($scancode eq '') {
1.658     bisitz   10581:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  10582:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   10583:                     } else {
1.658     bisitz   10584:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  10585:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   10586:                     }
                   10587:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   10588:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   10589:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   10590:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   10591:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10592:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   10593:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  10594:                               &Apache::loncommon::end_data_table_row().
                   10595:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10596:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   10597:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  10598:                               &Apache::loncommon::end_data_table_row().
                   10599:                               &Apache::loncommon::end_data_table().'</p>');
                   10600:                 } else {
                   10601:                     $r->print('<br /><span class="LC_warning">'.
                   10602:                              &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 />'.
                   10603:                              &mt("As a consequence, this user's submission history records two tries.").
                   10604:                                  '</span><br />');
                   10605:                 }
                   10606:             }
                   10607:         }
1.543     raeburn  10608:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 10609:     } continue {
1.330     albertel 10610: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  10611: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 10612:     }
1.140     albertel 10613:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      10614:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 10615: #    my $lasttime = &Time::HiRes::time()-$start;
                   10616: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 10617: 
1.200     albertel 10618:     $r->print("</form>");
1.157     albertel 10619:     return '';
1.75      albertel 10620: }
1.157     albertel 10621: 
1.557     raeburn  10622: sub graders_resources_pass {
1.649     raeburn  10623:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   10624:         $bubbles_per_row) = @_;
1.557     raeburn  10625:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   10626:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   10627:         foreach my $resource (@{$resources}) {
                   10628:             my $ressymb = $resource->symb();
                   10629:             my ($analysis,$parts) =
                   10630:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  10631:                                           $env{'user.name'},$env{'user.domain'},
                   10632:                                           1,$bubbles_per_row);
1.557     raeburn  10633:             $grader_partids_by_symb->{$ressymb} = $parts;
                   10634:             if (ref($analysis) eq 'HASH') {
                   10635:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   10636:                     $grader_randomlists_by_symb->{$ressymb} =
                   10637:                         $analysis->{'parts_withrandomlist'};
                   10638:                 }
                   10639:             }
                   10640:         }
                   10641:     }
                   10642:     return;
                   10643: }
                   10644: 
1.678     raeburn  10645: =pod
                   10646: 
                   10647: =item users_order
                   10648: 
                   10649:   Returns array of resources in current map, ordered based on either CODE,
                   10650:   if this is a CODEd exam, or based on student's identity if this is a 
                   10651:   "NAMEd" exam.
                   10652: 
1.691     raeburn  10653:   Should be used when randomorder and/or randompick applied when the 
                   10654:   corresponding exam was printed, prior to students completing bubblesheets 
                   10655:   for the version of the exam the student received.
1.678     raeburn  10656: 
                   10657: =cut
                   10658: 
                   10659: sub users_order  {
1.691     raeburn  10660:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  10661:     my @mapresources;
1.691     raeburn  10662:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  10663:         return @mapresources;
1.691     raeburn  10664:     }
                   10665:     if ($scancode) {
                   10666:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   10667:             @mapresources = @{$orderedforcode->{$scancode}};
                   10668:         } else {
                   10669:             $env{'form.CODE'} = $scancode;
                   10670:             my $actual_seq =
                   10671:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10672:                                                                $master_seq,
                   10673:                                                                $user,$scancode,1);
                   10674:             if (ref($actual_seq) eq 'ARRAY') {
                   10675:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10676:                 if (ref($orderedforcode) eq 'HASH') {
                   10677:                     if (@mapresources > 0) { 
                   10678:                         $orderedforcode->{$scancode} = \@mapresources;
                   10679:                     }
                   10680:                 }
                   10681:             }
                   10682:             delete($env{'form.CODE'});
1.678     raeburn  10683:         }
                   10684:     } else {
                   10685:         my $actual_seq =
                   10686:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10687:                                                            $master_seq,
1.688     raeburn  10688:                                                            $user,undef,1);
1.678     raeburn  10689:         if (ref($actual_seq) eq 'ARRAY') {
                   10690:             @mapresources = 
                   10691:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10692:         }
1.691     raeburn  10693:     }
                   10694:     return @mapresources;
1.678     raeburn  10695: }
                   10696: 
1.542     raeburn  10697: sub grade_student_bubbles {
1.691     raeburn  10698:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   10699:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   10700:     my $uselookup = 0;
                   10701:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   10702:         (ref($startline) eq 'HASH')) {
                   10703:         $uselookup = 1;
                   10704:     }
                   10705: 
1.554     raeburn  10706:     if (ref($resources) eq 'ARRAY') {
                   10707:         my $count = 0;
                   10708:         foreach my $resource (@{$resources}) {
                   10709:             my $ressymb = $resource->symb();
                   10710:             my %form = ('submitted'      => 'scantron',
                   10711:                         'grade_target'   => 'grade',
                   10712:                         'grade_username' => $uname,
                   10713:                         'grade_domain'   => $udom,
                   10714:                         'grade_courseid' => $env{'request.course.id'},
                   10715:                         'grade_symb'     => $ressymb,
                   10716:                         'CODE'           => $scancode
                   10717:                        );
1.649     raeburn  10718:             if ($bubbles_per_row ne '') {
                   10719:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   10720:             }
1.663     raeburn  10721:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   10722:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   10723:             }
1.554     raeburn  10724:             if (ref($parts) eq 'HASH') {
                   10725:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   10726:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  10727:                         if ($uselookup) {
                   10728:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   10729:                         } else {
                   10730:                             $form{'scantron_questnum_start.'.$part} =
                   10731:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   10732:                         }
1.554     raeburn  10733:                         $count++;
                   10734:                     }
                   10735:                 }
                   10736:             }
                   10737:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   10738:             return 'ssi_error' if ($ssi_error);
                   10739:             last if (&Apache::loncommon::connection_aborted($r));
                   10740:         }
1.542     raeburn  10741:     }
                   10742:     return;
                   10743: }
                   10744: 
1.157     albertel 10745: sub scantron_upload_scantron_data {
1.767     raeburn  10746:     my ($r,$symb) = @_;
1.565     raeburn  10747:     my $dom = $env{'request.role.domain'};
1.754     raeburn  10748:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  10749:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   10750:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 10751:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 10752: 							  'domainid',
1.565     raeburn  10753: 							  'coursename',$dom);
                   10754:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   10755:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      10756:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  10757:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  10758:     &js_escape(\$nofile_alert);
1.579     raeburn  10759:     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  10760:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 10761:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 10762:     function checkUpload(formname) {
                   10763: 	if (formname.upfile.value == "") {
1.579     raeburn  10764: 	    alert("'.$nofile_alert.'");
1.157     albertel 10765: 	    return false;
                   10766: 	}
1.565     raeburn  10767:         if (formname.courseid.value == "") {
1.579     raeburn  10768:             alert("'.$nocourseid_alert.'");
1.565     raeburn  10769:             return false;
                   10770:         }
1.157     albertel 10771: 	formname.submit();
                   10772:     }
1.565     raeburn  10773: 
                   10774:     function ToSyllabus() {
                   10775:         var cdom = '."'$dom'".';
                   10776:         var cnum = document.rules.courseid.value;
                   10777:         if (cdom == "" || cdom == null) {
                   10778:             return;
                   10779:         }
                   10780:         if (cnum == "" || cnum == null) {
                   10781:            return;
                   10782:         }
                   10783:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   10784:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   10785:         return;
                   10786:     }
                   10787: 
1.754     raeburn  10788:     '.$formatjs.'
1.597     wenzelju 10789: '));
                   10790:     $r->print('
1.648     bisitz   10791: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  10792: 
1.492     albertel 10793: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  10794: '.$default_form_data.
                   10795:   &Apache::lonhtmlcommon::start_pick_box().
                   10796:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   10797:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   10798:   &Apache::lonhtmlcommon::row_closure().
                   10799:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   10800:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   10801:   &Apache::lonhtmlcommon::row_closure().
                   10802:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   10803:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  10804:   &Apache::lonhtmlcommon::row_closure());
                   10805:     if ($formatoptions) {
                   10806:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   10807:                   &Apache::lonhtmlcommon::row_closure());
                   10808:     }
                   10809:     $r->print(
1.565     raeburn  10810:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   10811:   '<input type="file" name="upfile" size="50" />'.
                   10812:   &Apache::lonhtmlcommon::row_closure(1).
                   10813:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   10814: 
1.492     albertel 10815: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   10816: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 10817: </form>
1.492     albertel 10818: ');
1.157     albertel 10819:     return '';
                   10820: }
                   10821: 
1.754     raeburn  10822: sub scantron_upload_dataformat {
                   10823:     my ($dom) = @_;
                   10824:     my ($formatoptions,$formattitle,$formatjs);
                   10825:     $formatjs = <<'END';
                   10826: function toggleScantab(form) {
                   10827:    return;
                   10828: }
                   10829: END
                   10830:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   10831:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10832:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10833:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   10834:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   10835:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  10836:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   10837:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   10838:                             my ($onclick,$formatextra,$singleline);
                   10839:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   10840:                             my $count = 0;
                   10841:                             foreach my $line (@lines) {
1.790     raeburn  10842:                                 next if (($line =~ /^\#/) || ($line eq ''));
1.756     raeburn  10843:                                 $singleline = $line;
                   10844:                                 $count ++;
                   10845:                             }
                   10846:                             if ($count > 1) {
                   10847:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  10848:                                                '<span class="LC_nobreak">'.
1.776     raeburn  10849:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  10850:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  10851:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   10852:                                 $formatjs = <<"END";
1.754     raeburn  10853: function toggleScantab(form) {
                   10854:     var divid = 'bubbletype';
                   10855:     if (document.getElementById(divid)) {
                   10856:         var radioname = 'fileformat';
                   10857:         var num = form.elements[radioname].length;
                   10858:         if (num) {
                   10859:             for (var i=0; i<num; i++) {
                   10860:                 if (form.elements[radioname][i].checked) {
                   10861:                     var chosen = form.elements[radioname][i].value;
                   10862:                     if (chosen == 'dat') {
                   10863:                         document.getElementById(divid).style.display = 'none';
                   10864:                     } else if (chosen == 'csv') {
1.757     raeburn  10865:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  10866:                     }
                   10867:                 }
                   10868:             }
                   10869:         }
                   10870:     }
                   10871:     return;
                   10872: }
                   10873: 
                   10874: END
1.756     raeburn  10875:                             } elsif ($count == 1) {
                   10876:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   10877:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   10878:                             }
                   10879:                             $formattitle = &mt('File format');
                   10880:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   10881:                                              &mt('Plain Text (no delimiters)').
                   10882:                                              '</label>'.('&nbsp;'x2).
                   10883:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   10884:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  10885:                         }
                   10886:                     }
                   10887:                 }
                   10888:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  10889:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10890:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  10891:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  10892:                         $formatoptions = &scantron_scantab();
                   10893:                     }
1.754     raeburn  10894:                 }
                   10895:             }
                   10896:         }
                   10897:     }
                   10898:     return ($formatoptions,$formattitle,$formatjs);
                   10899: }
1.423     albertel 10900: 
1.157     albertel 10901: sub scantron_upload_scantron_data_save {
1.767     raeburn  10902:     my ($r,$symb) = @_;
1.182     albertel 10903:     my $doanotherupload=
                   10904: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   10905: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 10906: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 10907: 	'</form>'."\n";
1.257     albertel 10908:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 10909: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  10910: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   10911:         !&Apache::lonnet::allowed('usc',
                   10912:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      10913: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      10914: 	unless ($symb) {
1.182     albertel 10915: 	    $r->print($doanotherupload);
                   10916: 	}
1.162     albertel 10917: 	return '';
                   10918:     }
1.257     albertel 10919:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  10920:     my $uploadedfile;
1.710     bisitz   10921:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 10922:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10923:         $r->print(
                   10924:             &Apache::lonhtmlcommon::confirm_success(
                   10925:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10926:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 10927:     } else {
1.754     raeburn  10928:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   10929:         my $parser;
                   10930:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10931:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10932:                 my $is_csv;
                   10933:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   10934:                 if (@possibles > 1) {
                   10935:                     if ($env{'form.fileformat'} eq 'csv') {
                   10936:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10937:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10938:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10939:                                     $is_csv = 1;
                   10940:                                 }
1.754     raeburn  10941:                             }
                   10942:                         }
                   10943:                     }
                   10944:                 } elsif (@possibles == 1) {
                   10945:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10946:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10947:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10948:                                 $is_csv = 1;
                   10949:                             }
1.754     raeburn  10950:                         }
                   10951:                     }
                   10952:                 }
                   10953:                 if ($is_csv) {
                   10954:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   10955:                 }
                   10956:             }
                   10957:         }
                   10958:         my $result =
                   10959:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  10960:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   10961:         if ($result =~ m{^/uploaded/}) {
                   10962:             $r->print(
                   10963:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   10964:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   10965:                         (length($env{'form.upfile'})-1),
                   10966:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  10967:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  10968:             if ($uploadedfile =~ /^scantron_orig_/) {
                   10969:                 my $logname = $uploadedfile;
                   10970:                 $logname =~ s/^scantron_orig_//;
                   10971:                 if ($logname ne '') {
                   10972:                     my $now = time;
                   10973:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   10974:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   10975:                 }
                   10976:             }
1.567     raeburn  10977:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  10978:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   10979:         } else {
                   10980:             $r->print(
                   10981:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   10982:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   10983:                           $result,
1.568     raeburn  10984: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 10985: 	}
                   10986:     }
1.174     albertel 10987:     if ($symb) {
1.612     www      10988: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 10989:     } else {
1.182     albertel 10990: 	$r->print($doanotherupload);
1.174     albertel 10991:     }
1.157     albertel 10992:     return '';
                   10993: }
                   10994: 
1.567     raeburn  10995: sub validate_uploaded_scantron_file {
1.770     raeburn  10996:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   10997: 
1.567     raeburn  10998:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   10999:     my @lines;
                   11000:     if ($scanlines ne '-1') {
                   11001:         @lines=split("\n",$scanlines,-1);
                   11002:     }
1.770     raeburn  11003:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   11004:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   11005:     if ($context eq 'download') {
                   11006:         $priv = 'mgr';
                   11007:     } else {
                   11008:         $priv = 'usc';
                   11009:     }
                   11010:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   11011:             (($env{'request.course.id'}) &&
                   11012:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   11013:         if ($env{'request.course.sec'} ne '') {
                   11014:             unless (&Apache::lonnet::allowed($priv,
                   11015:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   11016:                 unless ($context eq 'download') {
                   11017:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   11018:                 }
                   11019:                 return $output;
                   11020:             }
                   11021:             ($checksec,@possibles)=&gradable_sections();
                   11022:         }
                   11023:     }
1.567     raeburn  11024:     if (@lines) {
                   11025:         my (%counts,$max_match_format);
1.710     bisitz   11026:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  11027:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   11028:         my %idmap = &username_to_idmap($classlist);
                   11029:         foreach my $key (keys(%idmap)) {
                   11030:             my $lckey = lc($key);
                   11031:             $idmap{$lckey} = $idmap{$key};
                   11032:         }
                   11033:         my %unique_formats;
1.754     raeburn  11034:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  11035:         foreach my $line (@formatlines) {
1.790     raeburn  11036:             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  11037:             my @config = split(/:/,$line);
                   11038:             my $idstart = $config[5];
                   11039:             my $idlength = $config[6];
                   11040:             if (($idstart ne '') && ($idlength > 0)) {
                   11041:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   11042:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   11043:                 } else {
                   11044:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   11045:                 }
                   11046:             }
                   11047:         }
                   11048:         foreach my $key (keys(%unique_formats)) {
                   11049:             my ($idstart,$idlength) = split(':',$key);
                   11050:             %{$counts{$key}} = (
                   11051:                                'found'   => 0,
                   11052:                                'total'   => 0,
1.770     raeburn  11053:                                'totalanysec' => 0,
                   11054:                                'othersec' => 0,
1.567     raeburn  11055:                               );
                   11056:             foreach my $line (@lines) {
                   11057:                 next if ($line =~ /^#/);
                   11058:                 next if ($line =~ /^[\s\cz]*$/);
                   11059:                 my $id = substr($line,$idstart-1,$idlength);
                   11060:                 $id = lc($id);
                   11061:                 if (exists($idmap{$id})) {
1.770     raeburn  11062:                     if ($checksec ne '') {
                   11063:                         $counts{$key}{'totalanysec'} ++;
                   11064:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   11065:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   11066:                             if ($stusec ne $checksec) {
                   11067:                                 if (@possibles) {
                   11068:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   11069:                                         $counts{$key}{'othersec'} ++;
                   11070:                                         next;
                   11071:                                     }
                   11072:                                 } else {
                   11073:                                     $counts{$key}{'othersec'} ++;
                   11074:                                     next;
                   11075:                                 }
                   11076:                             }
                   11077:                         }
                   11078:                     }
1.567     raeburn  11079:                     $counts{$key}{'found'} ++;
                   11080:                 }
                   11081:                 $counts{$key}{'total'} ++;
                   11082:             }
                   11083:             if ($counts{$key}{'total'}) {
                   11084:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   11085:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   11086:                     $max_match_pct = $percent_match;
                   11087:                     $max_match_format = $key;
1.710     bisitz   11088:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  11089:                     $max_match_count = $counts{$key}{'total'};
                   11090:                 }
                   11091:             }
                   11092:         }
1.770     raeburn  11093:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  11094:             my $format_descs;
                   11095:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   11096:             for (my $i=0; $i<$numwithformat; $i++) {
                   11097:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   11098:                 if ($i<$numwithformat-2) {
                   11099:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   11100:                 } elsif ($i==$numwithformat-2) {
                   11101:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   11102:                 } elsif ($i==$numwithformat-1) {
                   11103:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   11104:                 }
                   11105:             }
                   11106:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   11107:             $output .= '<br />';
                   11108:             if ($found_match_count == $max_match_count) {
                   11109:                 # 100% matching entries
                   11110:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   11111:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   11112:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   11113:                 &mt('Comparison of student IDs in the uploaded file with'.
                   11114:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   11115:                     ' in the file (for the format defined for [_3]).',
                   11116:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   11117:             } else {
                   11118:                 # Not all entries matching? -> Show warning and additional info
                   11119:                 $output .=
                   11120:                     &Apache::lonhtmlcommon::confirm_success(
                   11121:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   11122:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   11123:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   11124:                     &mt('Comparison of student IDs in the uploaded file with'.
                   11125:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   11126:                         ' in the file (for the format defined for [_3]).',
                   11127:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   11128:                     '<p class="LC_info">'.
                   11129:                     &mt('A low percentage of matches results from one of the following:').
                   11130:                     '</p><ul>'.
                   11131:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   11132:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   11133:                                '<i>'.$cdom.'</i>').'</li>'.
                   11134:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   11135:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   11136:                     '</ul>';
                   11137:             }
1.770     raeburn  11138:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11139:                 if ($counts{$max_match_format}{'othersec'}) {
                   11140:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   11141:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   11142:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   11143:                     &js_escape(\$confirmdel);
                   11144:                     $output .= '<p class="LC_warning">'.
                   11145:                                &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',
                   11146:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   11147:                                '<br />'.
                   11148:                                &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>').
                   11149:                                '</p><p>'.
                   11150:                                &mt('If you prefer to delete the file now, use: [_1]').
                   11151:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   11152:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   11153:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   11154:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   11155:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   11156:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   11157:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   11158:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   11159:                                '</form></p>';
                   11160:                 }
                   11161:             }
1.567     raeburn  11162:         }
1.770     raeburn  11163:         if (($context eq 'download') && ($checksec ne '')) {
                   11164:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11165:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   11166:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   11167:             }
                   11168:         } 
                   11169:     } elsif ($context ne 'download') {
1.710     bisitz   11170:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  11171:     }
                   11172:     return $output;
                   11173: }
                   11174: 
1.770     raeburn  11175: sub gradable_sections {
                   11176:     my $checksec = $env{'request.course.sec'};
                   11177:     my @oksecs;
                   11178:     if ($checksec) {
                   11179:         my %availablesecs = &sections_grade_privs();
                   11180:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   11181:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   11182:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   11183:                     push(@oksecs,$sec);
                   11184:                 }
                   11185:             }
                   11186:             if (grep(/^all$/,@oksecs)) {
                   11187:                 undef($checksec);
                   11188:             }
                   11189:         }
                   11190:     }
                   11191:     return($checksec,@oksecs);
                   11192: }
                   11193: 
                   11194: sub sections_grade_privs {
                   11195:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11196:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11197:     my %availablesecs = (
                   11198:                           mgr => [],
                   11199:                           vgr => [],
                   11200:                           usc => [],
                   11201:                         );
                   11202:     my $ccrole = 'cc';
                   11203:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   11204:         $ccrole = 'co';
                   11205:     }
                   11206:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   11207:                                                      'userroles',['active'],
                   11208:                                                      [$ccrole,'in','cr'],$cdom,1);
                   11209:     my $crsid = $cnum.':'.$cdom;
                   11210:     foreach my $item (keys(%crsroleshash)) {
                   11211:         next unless ($item =~ /^$crsid\:/);
                   11212:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   11213:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   11214:         if ($sec ne '') {
                   11215:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   11216:         }
                   11217:         if (($role eq $ccrole) || ($role eq 'in')) {
                   11218:             foreach my $priv ('mgr','vgr','usc') { 
                   11219:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11220:                     if ($sec eq '') {
                   11221:                         $availablesecs{$priv} = ['all'];
                   11222:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   11223:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11224:                             push(@{$availablesecs{$priv}},$sec);
                   11225:                         }
                   11226:                     }
                   11227:                 }
                   11228:             }
                   11229:         } elsif ($role =~ m{^cr/}) {
                   11230:             foreach my $priv ('mgr','vgr','usc') {
                   11231:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11232:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   11233:                         if ($sec eq '') {
                   11234:                             $availablesecs{$priv} = ['all'];
                   11235:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   11236:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11237:                                 push(@{$availablesecs{$priv}},$sec);
                   11238:                             }
                   11239:                         }
                   11240:                     }
                   11241:                 }
                   11242:             }
                   11243:         }
                   11244:     }
                   11245:     return %availablesecs;
                   11246: }
                   11247: 
                   11248: sub scantron_upload_delete {
                   11249:     my ($r,$symb) = @_;
                   11250:     my $filename = $env{'form.uploadedfile'};
                   11251:     if ($filename =~ /^scantron_orig_/) {
                   11252:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   11253:             &Apache::lonnet::allowed('usc',
                   11254:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   11255:             &Apache::lonnet::allowed('usc',
                   11256:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   11257:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   11258:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   11259:             if ($retrieval eq '-1') {
                   11260:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11261:                           &mt('File requested for deletion not found.'));
                   11262:             } else {
                   11263:                 $filename =~ s/^scantron_orig_//;
                   11264:                 if ($filename ne '') {
                   11265:                     my ($is_valid,$numleft);
                   11266:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11267:                     if (keys(%info)) {
                   11268:                         if (ref($info{$filename}) eq 'HASH') {
                   11269:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   11270:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11271:                                     $is_valid = 1;
                   11272:                                     delete($info{$filename}{$timestamp}); 
                   11273:                                 }
                   11274:                             }
                   11275:                             $numleft = scalar(keys(%{$info{$filename}}));
                   11276:                         }
                   11277:                     }
                   11278:                     if ($is_valid) {
                   11279:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   11280:                         if ($result eq 'ok') {
                   11281:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   11282:                             if ($numleft) {
                   11283:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   11284:                             } else {
                   11285:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11286:                             }
                   11287:                         } else {
                   11288:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11289:                                       &mt('Result was [_1]',$result));
                   11290:                         }
                   11291:                     } else {
                   11292:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11293:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   11294:                     }
                   11295:                 } else {
                   11296:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11297:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11298:                 }
                   11299:             }
                   11300:         } else {
                   11301:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   11302:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   11303:         }
                   11304:     } else {
                   11305:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11306:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11307:     }
                   11308:     return;
                   11309: }
                   11310: 
1.202     albertel 11311: sub valid_file {
                   11312:     my ($requested_file)=@_;
                   11313:     foreach my $filename (sort(&scantron_filenames())) {
                   11314: 	if ($requested_file eq $filename) { return 1; }
                   11315:     }
                   11316:     return 0;
                   11317: }
                   11318: 
                   11319: sub scantron_download_scantron_data {
1.767     raeburn  11320:     my ($r,$symb) = @_;
1.608     www      11321:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 11322:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   11323:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   11324:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 11325:     if (! &valid_file($file)) {
1.492     albertel 11326: 	$r->print('
1.202     albertel 11327: 	<p>
1.686     bisitz   11328: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 11329:         </p>
1.492     albertel 11330: ');
1.202     albertel 11331: 	return;
                   11332:     }
1.770     raeburn  11333:     my (%uploader,$is_owner,%counts,$percent);
                   11334:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   11335:     if (ref($uploader{$file}) eq 'HASH') {
                   11336:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   11337:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11338:                 $is_owner = 1;
                   11339:                 last;
                   11340:             }
                   11341:         }
                   11342:     }
                   11343:     unless ($is_owner) {
                   11344:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   11345:         if ($counts{'totalanysec'}) {
                   11346:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   11347:             if ($percent_othersec >= 10) {
                   11348:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   11349:                 $r->print('<p class="LC_warning">'.
                   11350:                           &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).
                   11351:                           '</p>');
                   11352:                 return;
                   11353:             }
                   11354:         }
                   11355:     }
1.202     albertel 11356:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   11357:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   11358:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   11359:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   11360:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   11361:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 11362:     $r->print('
1.202     albertel 11363:     <p>
1.723     raeburn  11364: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 11365: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 11366:     </p>
                   11367:     <p>
1.492     albertel 11368: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   11369: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 11370:     </p>
                   11371:     <p>
1.492     albertel 11372: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   11373: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 11374:     </p>
1.492     albertel 11375: ');
1.202     albertel 11376:     return '';
                   11377: }
1.157     albertel 11378: 
1.523     raeburn  11379: sub checkscantron_results {
1.608     www      11380:     my ($r,$symb) = @_;
1.523     raeburn  11381:     if (!$symb) {return '';}
                   11382:     my $cid = $env{'request.course.id'};
1.755     raeburn  11383:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  11384:     my $numletts = scalar(keys(%lettdig));
                   11385:     my $cnum = $env{'course.'.$cid.'.num'};
                   11386:     my $cdom = $env{'course.'.$cid.'.domain'};
                   11387:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   11388:     my %record;
                   11389:     my %scantron_config =
1.754     raeburn  11390:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  11391:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  11392:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  11393:     my $classlist=&Apache::loncoursedata::get_classlist();
                   11394:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   11395:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  11396:     unless (ref($navmap)) {
                   11397:         $r->print(&navmap_errormsg());
                   11398:         return '';
                   11399:     }
1.523     raeburn  11400:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  11401:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   11402:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  11403:     if (ref($map)) { 
                   11404:         $randomorder=$map->randomorder();
1.689     raeburn  11405:         $randompick=$map->randompick();
1.788     raeburn  11406:         unless ($randomorder || $randompick) {
                   11407:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   11408:                 if ($res->randomorder()) {
                   11409:                     $randomorder = 1;
                   11410:                 }
                   11411:                 if ($res->randompick()) {
                   11412:                     $randompick = 1;
                   11413:                 }
                   11414:                 last if ($randomorder || $randompick);
                   11415:             }
                   11416:         }
1.677     raeburn  11417:     }
1.557     raeburn  11418:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  11419:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   11420:     if ($nav_error) {
                   11421:         $r->print(&navmap_errormsg());
                   11422:         return '';
1.678     raeburn  11423:     }
1.673     raeburn  11424:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   11425:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  11426:     my ($uname,$udom);
1.523     raeburn  11427:     my (%scandata,%lastname,%bylast);
                   11428:     $r->print('
                   11429: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   11430: 
                   11431:     my @delayqueue;
                   11432:     my %completedstudents;
                   11433: 
1.691     raeburn  11434:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      11435:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  11436:     my ($username,$domain,$started);
1.649     raeburn  11437:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  11438:     if ($nav_error) {
                   11439:         $r->print(&navmap_errormsg());
                   11440:         return '';
                   11441:     }
1.523     raeburn  11442: 
1.667     www      11443:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  11444:     my $start=&Time::HiRes::time();
                   11445:     my $i=-1;
                   11446: 
                   11447:     while ($i<$scanlines->{'count'}) {
                   11448:         ($username,$domain,$uname)=('','','');
                   11449:         $i++;
                   11450:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   11451:         if ($line=~/^[\s\cz]*$/) { next; }
                   11452:         if ($started) {
1.667     www      11453:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  11454:         }
                   11455:         $started=1;
                   11456:         my $scan_record=
                   11457:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   11458:                                                      $scan_data);
1.693     raeburn  11459:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   11460:                                               \%idmap,$i)) {
1.523     raeburn  11461:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11462:                                 'Unable to find a student that matches',1);
                   11463:             next;
                   11464:         }
                   11465:         if (exists $completedstudents{$uname}) {
                   11466:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11467:                                 'Student '.$uname.' has multiple sheets',2);
                   11468:             next;
                   11469:         }
                   11470:         my $pid = $scan_record->{'scantron.ID'};
                   11471:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   11472:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  11473:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   11474:         my $user = $uname.':'.$usec;
1.523     raeburn  11475:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  11476: 
1.678     raeburn  11477:         my $scancode;
1.677     raeburn  11478:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   11479:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   11480:             $scancode = $scan_record->{'scantron.CODE'};
                   11481:         } else {
                   11482:             $scancode = '';
                   11483:         }
                   11484: 
                   11485:         my @mapresources = @resources;
1.691     raeburn  11486:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   11487:         my %respnumlookup=();
                   11488:         my %startline=();
1.689     raeburn  11489:         if ($randomorder || $randompick) {
1.678     raeburn  11490:             @mapresources =
1.691     raeburn  11491:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   11492:                              \%orderedforcode);
                   11493:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   11494:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   11495:                                              \%grader_partids_by_symb,\%orderedforcode,
                   11496:                                              \%respnumlookup,\%startline);
                   11497:             if ($randompick && $total) {
                   11498:                 $lastpos = $total*$scantron_config{'Qlength'};
                   11499:             }
1.677     raeburn  11500:         }
1.691     raeburn  11501:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   11502:         chomp($scandata{$pid});
                   11503:         $scandata{$pid} =~ s/\r$//;
                   11504: 
1.523     raeburn  11505:         my $counter = -1;
1.677     raeburn  11506:         foreach my $resource (@mapresources) {
1.557     raeburn  11507:             my $parts;
1.554     raeburn  11508:             my $ressymb = $resource->symb();
1.557     raeburn  11509:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   11510:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  11511:                 my $currcode;
                   11512:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   11513:                     $currcode = $scancode;
                   11514:                 }
1.557     raeburn  11515:                 (my $analysis,$parts) =
1.672     raeburn  11516:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   11517:                                               $username,$domain,undef,
1.741     raeburn  11518:                                               $bubbles_per_row,$currcode);
1.557     raeburn  11519:             } else {
                   11520:                 $parts = $grader_partids_by_symb{$ressymb};
                   11521:             }
1.542     raeburn  11522:             ($counter,my $recording) =
                   11523:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  11524:                                          $scandata{$pid},$parts,
1.691     raeburn  11525:                                          \%scantron_config,\%lettdig,$numletts,
                   11526:                                          $randomorder,$randompick,
                   11527:                                          \%respnumlookup,\%startline);
1.542     raeburn  11528:             $record{$pid} .= $recording;
1.523     raeburn  11529:         }
                   11530:     }
                   11531:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   11532:     $r->print('<br />');
                   11533:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   11534:     $passed = 0;
                   11535:     $failed = 0;
                   11536:     $numstudents = 0;
                   11537:     foreach my $last (sort(keys(%bylast))) {
                   11538:         if (ref($bylast{$last}) eq 'ARRAY') {
                   11539:             foreach my $pid (sort(@{$bylast{$last}})) {
                   11540:                 my $showscandata = $scandata{$pid};
                   11541:                 my $showrecord = $record{$pid};
                   11542:                 $showscandata =~ s/\s/&nbsp;/g;
                   11543:                 $showrecord =~ s/\s/&nbsp;/g;
                   11544:                 if ($scandata{$pid} eq $record{$pid}) {
                   11545:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   11546:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      11547: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  11548: '</tr>'."\n".
                   11549: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11550: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  11551:                     $passed ++;
                   11552:                 } else {
                   11553:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      11554:                     $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  11555: '</tr>'."\n".
                   11556: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11557: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  11558: '</tr>'."\n";
                   11559:                     $failed ++;
                   11560:                 }
                   11561:                 $numstudents ++;
                   11562:             }
                   11563:         }
                   11564:     }
1.648     bisitz   11565:     $r->print(
                   11566:         '<p>'
                   11567:        .&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).',
                   11568:             '<b>',
                   11569:             $numstudents,
                   11570:             '</b>',
                   11571:             $env{'form.scantron_maxbubble'})
                   11572:        .'</p>'
                   11573:     );
1.682     raeburn  11574:     $r->print('<p>'
1.683     raeburn  11575:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  11576:              .'<br />'
                   11577:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   11578:              .'</p>'
                   11579:     );
1.523     raeburn  11580:     if ($passed) {
1.572     www      11581:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11582:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11583:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11584:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11585:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11586:                  $okstudents."\n".
                   11587:                  &Apache::loncommon::end_data_table().'<br />');
                   11588:     }
                   11589:     if ($failed) {
1.572     www      11590:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11591:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11592:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11593:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11594:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11595:                  $badstudents."\n".
                   11596:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      11597:                  &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  11598:     }
1.614     www      11599:     $r->print('</form><br />');
1.523     raeburn  11600:     return;
                   11601: }
                   11602: 
1.542     raeburn  11603: sub verify_scantron_grading {
1.554     raeburn  11604:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  11605:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   11606:         $respnumlookup,$startline) = @_;
1.542     raeburn  11607:     my ($record,%expected,%startpos);
                   11608:     return ($counter,$record) if (!ref($resource));
                   11609:     return ($counter,$record) if (!$resource->is_problem());
                   11610:     my $symb = $resource->symb();
1.554     raeburn  11611:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   11612:     foreach my $part_id (@{$partids}) {
1.542     raeburn  11613:         $counter ++;
                   11614:         $expected{$part_id} = 0;
1.691     raeburn  11615:         my $respnum = $counter;
                   11616:         if ($randomorder || $randompick) {
                   11617:             $respnum = $respnumlookup->{$counter};
                   11618:             $startpos{$part_id} = $startline->{$counter} + 1;
                   11619:         } else {
                   11620:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   11621:         }
                   11622:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   11623:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  11624:             foreach my $item (@sub_lines) {
                   11625:                 $expected{$part_id} += $item;
                   11626:             }
                   11627:         } else {
1.691     raeburn  11628:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  11629:         }
                   11630:     }
                   11631:     if ($symb) {
                   11632:         my %recorded;
                   11633:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   11634:         if ($returnhash{'version'}) {
                   11635:             my %lasthash=();
                   11636:             my $version;
                   11637:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   11638:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   11639:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   11640:                 }
                   11641:             }
                   11642:             foreach my $key (keys(%lasthash)) {
                   11643:                 if ($key =~ /\.scantron$/) {
                   11644:                     my $value = &unescape($lasthash{$key});
                   11645:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   11646:                     if ($value eq '') {
                   11647:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11648:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   11649:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11650:                             }
                   11651:                         }
                   11652:                     } else {
                   11653:                         my @tocheck;
                   11654:                         my @items = split(//,$value);
                   11655:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   11656:                             ($scantron_config->{'Qon'} eq 'number')) {
                   11657:                             if (@items < $expected{$part_id}) {
                   11658:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   11659:                                 my @singles = split(//,$fragment);
                   11660:                                 foreach my $pos (@singles) {
                   11661:                                     if ($pos eq ' ') {
                   11662:                                         push(@tocheck,$pos);
                   11663:                                     } else {
                   11664:                                         my $next = shift(@items);
                   11665:                                         push(@tocheck,$next);
                   11666:                                     }
                   11667:                                 }
                   11668:                             } else {
                   11669:                                 @tocheck = @items;
                   11670:                             }
                   11671:                             foreach my $letter (@tocheck) {
                   11672:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   11673:                                     if ($letter !~ /^[A-J]$/) {
                   11674:                                         $letter = $scantron_config->{'Qoff'};
                   11675:                                     }
                   11676:                                     $recorded{$part_id} .= $letter;
                   11677:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   11678:                                     my $digit;
                   11679:                                     if ($letter !~ /^[A-J]$/) {
                   11680:                                         $digit = $scantron_config->{'Qoff'};
                   11681:                                     } else {
                   11682:                                         $digit = $lettdig->{$letter};
                   11683:                                     }
                   11684:                                     $recorded{$part_id} .= $digit;
                   11685:                                 }
                   11686:                             }
                   11687:                         } else {
                   11688:                             @tocheck = @items;
                   11689:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11690:                                 my $curr_sub = shift(@tocheck);
                   11691:                                 my $digit;
                   11692:                                 if ($curr_sub =~ /^[A-J]$/) {
                   11693:                                     $digit = $lettdig->{$curr_sub}-1;
                   11694:                                 }
                   11695:                                 if ($curr_sub eq 'J') {
                   11696:                                     $digit += scalar($numletts);
                   11697:                                 }
                   11698:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11699:                                     if ($j == $digit) {
                   11700:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   11701:                                     } else {
                   11702:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11703:                                     }
                   11704:                                 }
                   11705:                             }
                   11706:                         }
                   11707:                     }
                   11708:                 }
                   11709:             }
                   11710:         }
1.554     raeburn  11711:         foreach my $part_id (@{$partids}) {
1.542     raeburn  11712:             if ($recorded{$part_id} eq '') {
                   11713:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11714:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11715:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11716:                     }
                   11717:                 }
                   11718:             }
                   11719:             $record .= $recorded{$part_id};
                   11720:         }
                   11721:     }
                   11722:     return ($counter,$record);
                   11723: }
                   11724: 
1.75      albertel 11725: #-------- end of section for handling grading scantron forms -------
                   11726: #
                   11727: #-------------------------------------------------------------------
                   11728: 
1.72      ng       11729: #-------------------------- Menu interface -------------------------
                   11730: #
1.614     www      11731: #--- Href with symb and command ---
                   11732: 
                   11733: sub href_symb_cmd {
                   11734:     my ($symb,$cmd)=@_;
1.796     raeburn  11735:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.
                   11736:            &HTML::Entities::encode($cmd,'<>&"');
1.72      ng       11737: }
                   11738: 
1.443     banghart 11739: sub grading_menu {
1.608     www      11740:     my ($request,$symb) = @_;
1.443     banghart 11741:     if (!$symb) {return '';}
                   11742: 
                   11743:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      11744:                   'command'=>'individual');
1.538     schulted 11745:     
1.598     www      11746:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11747: 
                   11748:     $fields{'command'}='ungraded';
                   11749:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11750: 
                   11751:     $fields{'command'}='table';
                   11752:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11753: 
                   11754:     $fields{'command'}='all_for_one';
                   11755:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11756: 
1.621     www      11757:     $fields{'command'}='downloadfilesselect';
                   11758:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11759: 
1.443     banghart 11760:     $fields{'command'} = 'csvform';
1.538     schulted 11761:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11762:     
1.443     banghart 11763:     $fields{'command'} = 'processclicker';
1.538     schulted 11764:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11765:     
1.443     banghart 11766:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 11767:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      11768: 
                   11769:     $fields{'command'} = 'initialverifyreceipt';
                   11770:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  11771: 
                   11772:     my %permissions;
                   11773:     if ($perm{'mgr'}) {
                   11774:         $permissions{'either'} = 'F';
                   11775:         $permissions{'mgr'} = 'F';
                   11776:     }
                   11777:     if ($perm{'vgr'}) {
                   11778:         $permissions{'either'} = 'F';
                   11779:         $permissions{'vgr'} = 'F';
                   11780:     }
                   11781: 
1.598     www      11782:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 11783:             items =>[
1.598     www      11784:                         {	linktext => 'Select individual students to grade',
                   11785:                     		url => $url1a,
1.781     raeburn  11786:                     		permission => $permissions{'either'},
1.636     wenzelju 11787:                     		icon => 'grade_students.png',
1.598     www      11788:                     		linktitle => 'Grade current resource for a selection of students.'
                   11789:                         }, 
1.764     raeburn  11790:                         {       linktext => 'Grade ungraded submissions',
1.598     www      11791:                                 url => $url1b,
1.781     raeburn  11792:                                 permission => $permissions{'either'},
1.636     wenzelju 11793:                                 icon => 'ungrade_sub.png',
1.598     www      11794:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 11795:                         },
1.598     www      11796: 
                   11797:                         {       linktext => 'Grading table',
                   11798:                                 url => $url1c,
1.781     raeburn  11799:                                 permission => $permissions{'either'},
1.636     wenzelju 11800:                                 icon => 'grading_table.png',
1.598     www      11801:                                 linktitle => 'Grade current resource for all students.'
                   11802:                         },
1.615     www      11803:                         {       linktext => 'Grade page/folder for one student',
1.598     www      11804:                                 url => $url1d,
1.781     raeburn  11805:                                 permission => $permissions{'either'},
1.636     wenzelju 11806:                                 icon => 'grade_PageFolder.png',
1.598     www      11807:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      11808:                         },
                   11809:                         {       linktext => 'Download submissions',
                   11810:                                 url => $url1e,
1.781     raeburn  11811:                                 permission => $permissions{'either'},
1.636     wenzelju 11812:                                 icon => 'download_sub.png',
1.621     www      11813:                                 linktitle => 'Download all students submissions.'
1.598     www      11814:                         }]},
                   11815:                          { categorytitle=>'Automated Grading',
                   11816:                items =>[
                   11817: 
1.538     schulted 11818:                 	    {	linktext => 'Upload Scores',
                   11819:                     		url => $url2,
1.780     raeburn  11820:                     		permission => $permissions{'mgr'},
1.538     schulted 11821:                     		icon => 'uploadscores.png',
                   11822:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   11823:                 	    },
                   11824:                 	    {	linktext => 'Process Clicker',
                   11825:                     		url => $url3,
1.780     raeburn  11826:                     		permission => $permissions{'mgr'},
1.538     schulted 11827:                     		icon => 'addClickerInfoFile.png',
                   11828:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   11829:                 	    },
1.587     raeburn  11830:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 11831:                     		url => $url4,
1.780     raeburn  11832:                     		permission => $permissions{'mgr'},
1.636     wenzelju 11833:                     		icon => 'bubblesheet.png',
1.648     bisitz   11834:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      11835:                 	    },
1.616     www      11836:                             {   linktext => 'Verify Receipt Number',
1.602     www      11837:                                 url => $url5,
1.780     raeburn  11838:                                 permission => $permissions{'either'},
1.636     wenzelju 11839:                                 icon => 'receipt_number.png',
1.602     www      11840:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   11841:                             }
                   11842: 
1.538     schulted 11843:                     ]
                   11844:             });
1.796     raeburn  11845:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   11846:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   11847:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   11848:     if (keys(%passback)) {
                   11849:         $fields{'command'} = 'initialpassback';
                   11850:         my $url6 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11851:         push (@{$menu[1]{items}},
                   11852:                   { linktext => 'Passback of Scores',
                   11853:                     url => $url6,
                   11854:                     permission => $permissions{'either'},
                   11855:                     icon => 'passback.png',
                   11856:                     linktitle => 'Passback scores to launcher CMS for resources accessed via LTI-mediated deep-linking',
                   11857:                   });
                   11858:     }
1.443     banghart 11859:     # Create the menu
                   11860:     my $Str;
1.445     banghart 11861:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   11862:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      11863:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 11864: 
1.602     www      11865:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 11866:     return $Str;    
                   11867: }
                   11868: 
1.598     www      11869: sub ungraded {
                   11870:     my ($request)=@_;
                   11871:     &submit_options($request);
                   11872: }
                   11873: 
1.599     www      11874: sub submit_options_sequence {
1.608     www      11875:     my ($request,$symb) = @_;
1.599     www      11876:     if (!$symb) {return '';}
1.600     www      11877:     &commonJSfunctions($request);
                   11878:     my $result;
1.599     www      11879: 
1.600     www      11880:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11881:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      11882:     $result.=&selectfield(0).
1.601     www      11883:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      11884:             <div>
                   11885:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11886:             </div>
                   11887:         </div>
                   11888:   </form>';
                   11889:     return $result;
                   11890: }
                   11891: 
                   11892: sub submit_options_table {
1.608     www      11893:     my ($request,$symb) = @_;
1.600     www      11894:     if (!$symb) {return '';}
1.599     www      11895:     &commonJSfunctions($request);
1.746     raeburn  11896:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      11897:     my $result;
                   11898: 
                   11899:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11900:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      11901: 
1.745     raeburn  11902:     $result.=&selectfield(1,$is_tool).
1.601     www      11903:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      11904:             <div>
                   11905:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11906:             </div>
                   11907:         </div>
                   11908:   </form>';
                   11909:     return $result;
                   11910: }
1.443     banghart 11911: 
1.621     www      11912: sub submit_options_download {
                   11913:     my ($request,$symb) = @_;
                   11914:     if (!$symb) {return '';}
                   11915: 
1.773     raeburn  11916:     my $res_error;
                   11917:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   11918:         &response_type($symb,\$res_error);
                   11919:     if ($res_error) {
                   11920:         $request->print(&mt('An error occurred retrieving response types'));
                   11921:         return;
                   11922:     }
                   11923:     unless ($numessay) {
                   11924:         $request->print(&mt('No essayresponse items found'));
                   11925:         return;
                   11926:     }
                   11927:     my $table;
                   11928:     if (ref($partlist) eq 'ARRAY') {
                   11929:         if (scalar(@$partlist) > 1 ) {
                   11930:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   11931:         }
                   11932:     }
                   11933: 
1.746     raeburn  11934:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      11935:     &commonJSfunctions($request);
                   11936: 
                   11937:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  11938:                $table."\n".
                   11939:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      11940:     $result.='
                   11941: <h2>
1.750     raeburn  11942:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  11943: </h2>'.&selectfield(1,$is_tool).'
1.621     www      11944:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   11945:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11946:             </div>
                   11947:           </div>
1.600     www      11948: 
                   11949: 
1.621     www      11950:   </form>';
                   11951:     return $result;
                   11952: }
                   11953: 
1.443     banghart 11954: #--- Displays the submissions first page -------
                   11955: sub submit_options {
1.608     www      11956:     my ($request,$symb) = @_;
1.72      ng       11957:     if (!$symb) {return '';}
                   11958: 
1.746     raeburn  11959:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       11960:     &commonJSfunctions($request);
1.473     albertel 11961:     my $result;
1.533     bisitz   11962: 
1.72      ng       11963:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11964: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  11965:     $result.=&selectfield(1,$is_tool).'
1.601     www      11966:                 <input type="hidden" name="command" value="submission" /> 
                   11967: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11968:             </div>
                   11969:           </div>
                   11970:   </form>';
                   11971:     return $result;
                   11972: }
1.533     bisitz   11973: 
1.601     www      11974: sub selectfield {
1.745     raeburn  11975:    my ($full,$is_tool)=@_;
                   11976:    my %options;
                   11977:    if ($is_tool) {
                   11978:        %options =
                   11979:            (&transtatus_options,
                   11980:             'select_form_order' => ['yes','incorrect','all']);
                   11981:    } else {
                   11982:        %options = 
                   11983:            (&substatus_options,
                   11984:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   11985:    }
1.782     raeburn  11986: 
                   11987:   #
                   11988:   # PrepareClasslist() needs to be called to avoid getting a sections list
                   11989:   # for a different course from the @Sections global in lonstatistics.pm, 
                   11990:   # populated by an earlier request.
                   11991:   #
                   11992:    &Apache::lonstatistics::PrepareClasslist();
                   11993: 
1.601     www      11994:    my $result='<div class="LC_columnSection">
1.537     harmsja  11995:   
1.533     bisitz   11996:     <fieldset>
                   11997:       <legend>
                   11998:        '.&mt('Sections').'
                   11999:       </legend>
1.601     www      12000:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   12001:     </fieldset>
1.537     harmsja  12002:   
1.533     bisitz   12003:     <fieldset>
                   12004:       <legend>
                   12005:         '.&mt('Groups').'
                   12006:       </legend>
                   12007:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   12008:     </fieldset>
1.537     harmsja  12009:   
1.533     bisitz   12010:     <fieldset>
                   12011:       <legend>
                   12012:         '.&mt('Access Status').'
                   12013:       </legend>
1.601     www      12014:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   12015:     </fieldset>';
                   12016:     if ($full) {
1.745     raeburn  12017:         my $heading = &mt('Submission Status');
                   12018:         if ($is_tool) {
                   12019:             $heading = &mt('Transaction Status');
                   12020:         }
                   12021:         $result.='
1.533     bisitz   12022:     <fieldset>
                   12023:       <legend>
1.745     raeburn  12024:         '.$heading.'
1.601     www      12025:       </legend>'.
1.635     raeburn  12026:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      12027:    '</fieldset>';
                   12028:     }
                   12029:     $result.='</div><br />';
1.44      ng       12030:     return $result;
1.2       albertel 12031: }
                   12032: 
1.738     raeburn  12033: sub substatus_options {
                   12034:     return &Apache::lonlocal::texthash(
                   12035:                                       'yes'       => 'with submissions',
                   12036:                                       'queued'    => 'in grading queue',
                   12037:                                       'graded'    => 'with ungraded submissions',
                   12038:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  12039:                                       'all'       => 'with any status',
                   12040:                                       );
1.738     raeburn  12041: }
                   12042: 
1.745     raeburn  12043: sub transtatus_options {
                   12044:     return &Apache::lonlocal::texthash(
                   12045:                                        'yes'       => 'with score transactions',
                   12046:                                        'incorrect' => 'with less than full credit',
                   12047:                                        'all'       => 'with any status',
                   12048:                                       );
                   12049: }
                   12050: 
1.285     albertel 12051: sub reset_perm {
                   12052:     undef(%perm);
                   12053: }
                   12054: 
                   12055: sub init_perm {
                   12056:     &reset_perm();
1.770     raeburn  12057:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 12058: 
                   12059: 	my $scope = $env{'request.course.id'};
                   12060: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   12061: 
                   12062: 	    $scope .= '/'.$env{'request.course.sec'};
                   12063: 	    if ( $perm{$test_perm}=
                   12064: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   12065: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   12066: 	    } else {
                   12067: 		delete($perm{$test_perm});
                   12068: 	    }
1.285     albertel 12069: 	}
                   12070:     }
                   12071: }
                   12072: 
1.674     raeburn  12073: sub init_old_essays {
                   12074:     my ($symb,$apath,$adom,$aname) = @_;
                   12075:     if ($symb ne '') {
                   12076:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   12077:         if (keys(%essays) > 0) {
                   12078:             $old_essays{$symb} = \%essays;
                   12079:         }
                   12080:     }
                   12081:     return;
                   12082: }
                   12083: 
                   12084: sub reset_old_essays {
                   12085:     undef(%old_essays);
                   12086: }
                   12087: 
1.400     www      12088: sub gather_clicker_ids {
1.408     albertel 12089:     my %clicker_ids;
1.400     www      12090: 
                   12091:     my $classlist = &Apache::loncoursedata::get_classlist();
                   12092: 
                   12093:     # Set up a couple variables.
1.407     albertel 12094:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   12095:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      12096:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      12097: 
1.407     albertel 12098:     foreach my $student (keys(%$classlist)) {
1.438     www      12099:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 12100:         my $username = $classlist->{$student}->[$username_idx];
                   12101:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      12102:         my $clickers =
1.408     albertel 12103: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      12104:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      12105:             $id=~s/^[\#0]+//;
1.421     www      12106:             $id=~s/[\-\:]//g;
1.407     albertel 12107:             if (exists($clicker_ids{$id})) {
1.408     albertel 12108: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      12109:             } else {
1.408     albertel 12110: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      12111:             }
                   12112:         }
                   12113:     }
1.407     albertel 12114:     return %clicker_ids;
1.400     www      12115: }
                   12116: 
1.402     www      12117: sub gather_adv_clicker_ids {
1.408     albertel 12118:     my %clicker_ids;
1.402     www      12119:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   12120:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   12121:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 12122:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      12123:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   12124:             my ($puname,$pudom)=split(/\:/,$person);
                   12125:             my $clickers =
1.408     albertel 12126: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      12127:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      12128: 		$id=~s/^[\#0]+//;
1.421     www      12129:                 $id=~s/[\-\:]//g;
1.408     albertel 12130: 		if (exists($clicker_ids{$id})) {
                   12131: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   12132: 		} else {
                   12133: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   12134: 		}
1.405     www      12135:             }
1.402     www      12136:         }
                   12137:     }
1.407     albertel 12138:     return %clicker_ids;
1.402     www      12139: }
                   12140: 
1.413     www      12141: sub clicker_grading_parameters {
                   12142:     return ('gradingmechanism' => 'scalar',
                   12143:             'upfiletype' => 'scalar',
                   12144:             'specificid' => 'scalar',
                   12145:             'pcorrect' => 'scalar',
                   12146:             'pincorrect' => 'scalar');
                   12147: }
                   12148: 
1.400     www      12149: sub process_clicker {
1.608     www      12150:     my ($r,$symb)=@_;
1.400     www      12151:     if (!$symb) {return '';}
                   12152:     my $result=&checkforfile_js();
1.632     www      12153:     $result.=&Apache::loncommon::start_data_table().
                   12154:              &Apache::loncommon::start_data_table_header_row().
                   12155:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   12156:              &Apache::loncommon::end_data_table_header_row().
                   12157:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      12158: # Attempt to restore parameters from last session, set defaults if not present
                   12159:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12160:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   12161:                                                  \%Saveable_Parameters);
                   12162:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   12163:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   12164:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   12165:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   12166: 
                   12167:     my %checked;
1.521     www      12168:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      12169:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   12170:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      12171:        }
                   12172:     }
                   12173: 
1.632     www      12174:     my $upload=&mt("Evaluate File");
1.400     www      12175:     my $type=&mt("Type");
1.402     www      12176:     my $attendance=&mt("Award points just for participation");
                   12177:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      12178:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      12179:     my $given=&mt("Correctness determined from given list of answers").' '.
                   12180:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      12181:     my $pcorrect=&mt("Percentage points for correct solution");
                   12182:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      12183:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  12184: 						   {'iclicker' => 'i>clicker',
1.666     www      12185:                                                     'interwrite' => 'interwrite PRS',
                   12186:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 12187:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 12188:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      12189: function sanitycheck() {
                   12190: // Accept only integer percentages
                   12191:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   12192:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   12193: // Find out grading choice
                   12194:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12195:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   12196:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   12197:       }
                   12198:    }
                   12199: // By default, new choice equals user selection
                   12200:    newgradingchoice=gradingchoice;
                   12201: // Not good to give more points for false answers than correct ones
                   12202:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   12203:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   12204:    }
                   12205: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   12206:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   12207:       document.forms.gradesupload.pcorrect.value=100;
                   12208:       document.forms.gradesupload.pincorrect.value=100;
                   12209:    }
                   12210: // If the values are different, cannot be attendance only
                   12211:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   12212:        (gradingchoice=='attendance')) {
                   12213:        newgradingchoice='personnel';
                   12214:    }
                   12215: // Change grading choice to new one
                   12216:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12217:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   12218:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   12219:       } else {
                   12220:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   12221:       }
                   12222:    }
                   12223: // Remember the old state
                   12224:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   12225: }
1.597     wenzelju 12226: ENDUPFORM
                   12227:     $result.= <<ENDUPFORM;
1.400     www      12228: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   12229: <input type="hidden" name="symb" value="$symb" />
                   12230: <input type="hidden" name="command" value="processclickerfile" />
                   12231: <input type="file" name="upfile" size="50" />
                   12232: <br /><label>$type: $selectform</label>
1.632     www      12233: ENDUPFORM
                   12234:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   12235:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   12236:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   12237: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   12238: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      12239: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   12240: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      12241: <br />&nbsp;&nbsp;&nbsp;
                   12242: <input type="text" name="givenanswer" size="50" />
1.413     www      12243: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      12244: ENDGRADINGFORM
1.766     raeburn  12245:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      12246:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   12247:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   12248: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   12249: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  12250: </form>
1.632     www      12251: ENDPERCFORM
                   12252:     $result.='</td>'.
                   12253:              &Apache::loncommon::end_data_table_row().
                   12254:              &Apache::loncommon::end_data_table();
1.400     www      12255:     return $result;
                   12256: }
                   12257: 
                   12258: sub process_clicker_file {
1.766     raeburn  12259:     my ($r,$symb) = @_;
1.400     www      12260:     if (!$symb) {return '';}
1.413     www      12261: 
                   12262:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12263:     &Apache::loncommon::store_course_settings('grades_clicker',
                   12264:                                               \%Saveable_Parameters);
1.598     www      12265:     my $result='';
1.404     www      12266:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 12267: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      12268: 	return $result;
1.404     www      12269:     }
1.522     www      12270:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      12271:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      12272:         return $result;
1.521     www      12273:     }
1.522     www      12274:     my $foundgiven=0;
1.521     www      12275:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12276:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   12277:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      12278:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      12279:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      12280:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   12281:         $foundgiven=$#answers+1;
1.521     www      12282:     }
1.407     albertel 12283:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 12284:     my %correct_ids;
1.404     www      12285:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 12286: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      12287:     }
                   12288:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      12289: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   12290: 	   $correct_id=~tr/a-z/A-Z/;
                   12291: 	   $correct_id=~s/\s//gs;
                   12292: 	   $correct_id=~s/^[\#0]+//;
1.421     www      12293:            $correct_id=~s/[\-\:]//g;
1.414     www      12294:            if ($correct_id) {
                   12295: 	      $correct_ids{$correct_id}='specified';
                   12296:            }
                   12297:         }
1.400     www      12298:     }
1.404     www      12299:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 12300: 	$result.=&mt('Score based on attendance only');
1.521     www      12301:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      12302:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      12303:     } else {
1.408     albertel 12304: 	my $number=0;
1.411     www      12305: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 12306: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      12307: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 12308: 	    if ($correct_ids{$id} eq 'specified') {
                   12309: 		$result.=&mt('specified');
                   12310: 	    } else {
                   12311: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   12312: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   12313: 	    }
                   12314: 	    $number++;
                   12315: 	}
1.411     www      12316:         $result.="</p>\n";
1.710     bisitz   12317:         if ($number==0) {
                   12318:             $result .=
                   12319:                  &Apache::lonhtmlcommon::confirm_success(
                   12320:                      &mt('No IDs found to determine correct answer'),1);
                   12321:             return $result;
                   12322:         }
1.404     www      12323:     }
1.405     www      12324:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   12325:         $result .=
                   12326:             &Apache::lonhtmlcommon::confirm_success(
                   12327:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   12328:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      12329:         return $result;
1.405     www      12330:     }
1.760     raeburn  12331:     my $mimetype;
                   12332:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   12333:         my $mm = new File::MMagic;
                   12334:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   12335:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   12336:             $result.= '<p>'.
                   12337:                 &Apache::lonhtmlcommon::confirm_success(
                   12338:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   12339:             return $result;
                   12340:         }
                   12341:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   12342:         $result .= '<p>'.
                   12343:             &Apache::lonhtmlcommon::confirm_success(
                   12344:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   12345:         return $result;
                   12346:     }
1.410     www      12347: 
                   12348: # Were able to get all the info needed, now analyze the file
                   12349: 
1.411     www      12350:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 12351:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      12352:     $result.=&Apache::loncommon::start_data_table().
                   12353:              &Apache::loncommon::start_data_table_header_row().
                   12354:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   12355:              &Apache::loncommon::end_data_table_header_row().
                   12356:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   12357: <td>
1.410     www      12358: <form method="post" action="/adm/grades" name="clickeranalysis">
                   12359: <input type="hidden" name="symb" value="$symb" />
                   12360: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      12361: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   12362: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   12363: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      12364: ENDHEADER
1.522     www      12365:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12366:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   12367:     } 
1.408     albertel 12368:     my %responses;
                   12369:     my @questiontitles;
1.405     www      12370:     my $errormsg='';
                   12371:     my $number=0;
                   12372:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  12373:         if ($mimetype eq 'text/plain') {
                   12374:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   12375:         } elsif ($mimetype eq 'text/html') {
                   12376:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   12377:         }
                   12378:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      12379:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  12380:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      12381:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   12382:     }
1.411     www      12383:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   12384:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   12385:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   12386:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   12387:              '<br />';
1.522     www      12388:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   12389:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      12390:        return $result;
1.522     www      12391:     } 
1.414     www      12392: # Remember Question Titles
                   12393: # FIXME: Possibly need delimiter other than ":"
                   12394:     for (my $i=0;$i<$number;$i++) {
                   12395:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   12396:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   12397:     }
1.411     www      12398:     my $correct_count=0;
                   12399:     my $student_count=0;
                   12400:     my $unknown_count=0;
1.414     www      12401: # Match answers with usernames
                   12402: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 12403:     foreach my $id (keys(%responses)) {
1.410     www      12404:        if ($correct_ids{$id}) {
1.414     www      12405:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      12406:           $correct_count++;
1.410     www      12407:        } elsif ($clicker_ids{$id}) {
1.437     www      12408:           if ($clicker_ids{$id}=~/\,/) {
                   12409: # More than one user with the same clicker!
1.632     www      12410:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12411:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12412:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      12413:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12414:                            "<select name='multi".$id."'>";
                   12415:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   12416:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   12417:              }
                   12418:              $result.='</select>';
                   12419:              $unknown_count++;
                   12420:           } else {
                   12421: # Good: found one and only one user with the right clicker
                   12422:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   12423:              $student_count++;
                   12424:           }
1.410     www      12425:        } else {
1.632     www      12426:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12427:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12428:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      12429:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12430:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   12431:                    "\n".&mt("Domain").": ".
                   12432:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  12433:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      12434:           $unknown_count++;
1.410     www      12435:        }
1.405     www      12436:     }
1.412     www      12437:     $result.='<hr />'.
                   12438:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      12439:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      12440:        if ($correct_count==0) {
1.696     bisitz   12441:           $errormsg.="Found no correct answers for grading!";
1.412     www      12442:        } elsif ($correct_count>1) {
1.414     www      12443:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      12444:        }
                   12445:     }
1.428     www      12446:     if ($number<1) {
                   12447:        $errormsg.="Found no questions.";
                   12448:     }
1.412     www      12449:     if ($errormsg) {
                   12450:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   12451:     } else {
                   12452:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   12453:     }
1.632     www      12454:     $result.='</form></td>'.
                   12455:              &Apache::loncommon::end_data_table_row().
                   12456:              &Apache::loncommon::end_data_table();
1.614     www      12457:     return $result;
1.400     www      12458: }
                   12459: 
1.405     www      12460: sub iclicker_eval {
1.406     www      12461:     my ($questiontitles,$responses)=@_;
1.405     www      12462:     my $number=0;
                   12463:     my $errormsg='';
                   12464:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      12465:         my %components=&Apache::loncommon::record_sep($line);
                   12466:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 12467: 	if ($entries[0] eq 'Question') {
                   12468: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   12469: 		$$questiontitles[$number]=$entries[$i];
                   12470: 		$number++;
                   12471: 	    }
                   12472: 	}
                   12473: 	if ($entries[0]=~/^\#/) {
                   12474: 	    my $id=$entries[0];
                   12475: 	    my @idresponses;
                   12476: 	    $id=~s/^[\#0]+//;
                   12477: 	    for (my $i=0;$i<$number;$i++) {
                   12478: 		my $idx=3+$i*6;
1.644     www      12479:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 12480: 		push(@idresponses,$entries[$idx]);
                   12481: 	    }
                   12482: 	    $$responses{$id}=join(',',@idresponses);
                   12483: 	}
1.405     www      12484:     }
                   12485:     return ($errormsg,$number);
                   12486: }
                   12487: 
1.760     raeburn  12488: sub iclickerxml_eval {
                   12489:     my ($questiontitles,$responses)=@_;
                   12490:     my $number=0;
                   12491:     my $errormsg='';
                   12492:     my @state;
                   12493:     my %respbyid;
                   12494:     my $p = HTML::Parser->new
                   12495:     (
                   12496:         xml_mode => 1,
                   12497:         start_h =>
                   12498:             [sub {
                   12499:                  my ($tagname,$attr) = @_;
                   12500:                  push(@state,$tagname);
                   12501:                  if ("@state" eq "ssn p") {
                   12502:                      my $title = $attr->{qn};
                   12503:                      $title =~ s/(^\s+|\s+$)//g;
                   12504:                      $questiontitles->[$number]=$title;
                   12505:                  } elsif ("@state" eq "ssn p v") {
                   12506:                      my $id = $attr->{id};
                   12507:                      my $entry = $attr->{ans};
                   12508:                      $id=~s/^[\#0]+//;
                   12509:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   12510:                      $respbyid{$id}[$number] = $entry;
                   12511:                  }
                   12512:             }, "tagname, attr"],
                   12513:          end_h =>
                   12514:                [sub {
                   12515:                    my ($tagname) = @_;
                   12516:                    if ("@state" eq "ssn p") {
                   12517:                        $number++;
                   12518:                    }
                   12519:                    pop(@state);
                   12520:                 }, "tagname"],
                   12521:     );
                   12522: 
                   12523:     $p->parse($env{'form.upfile'});
                   12524:     $p->eof;
                   12525:     foreach my $id (keys(%respbyid)) {
                   12526:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   12527:     }
                   12528:     return ($errormsg,$number);
                   12529: }
                   12530: 
1.419     www      12531: sub interwrite_eval {
                   12532:     my ($questiontitles,$responses)=@_;
                   12533:     my $number=0;
                   12534:     my $errormsg='';
1.420     www      12535:     my $skipline=1;
                   12536:     my $questionnumber=0;
                   12537:     my %idresponses=();
1.419     www      12538:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12539:         my %components=&Apache::loncommon::record_sep($line);
                   12540:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      12541:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   12542:         if ($entries[1] eq 'Response') { $skipline=1; }
                   12543:         next if $skipline;
                   12544:         if ($entries[0]!=$questionnumber) {
                   12545:            $questionnumber=$entries[0];
                   12546:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   12547:            $number++;
1.419     www      12548:         }
1.420     www      12549:         my $id=$entries[4];
                   12550:         $id=~s/^[\#0]+//;
1.421     www      12551:         $id=~s/^v\d*\://i;
                   12552:         $id=~s/[\-\:]//g;
1.420     www      12553:         $idresponses{$id}[$number]=$entries[6];
                   12554:     }
1.524     raeburn  12555:     foreach my $id (keys(%idresponses)) {
1.420     www      12556:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   12557:        $$responses{$id}=~s/^\s*\,//;
1.419     www      12558:     }
                   12559:     return ($errormsg,$number);
                   12560: }
                   12561: 
1.666     www      12562: sub turning_eval {
                   12563:     my ($questiontitles,$responses)=@_;
                   12564:     my $number=0;
                   12565:     my $errormsg='';
                   12566:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12567:         my %components=&Apache::loncommon::record_sep($line);
                   12568:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   12569:         if ($#entries>$number) { $number=$#entries; }
                   12570:         my $id=$entries[0];
                   12571:         my @idresponses;
                   12572:         $id=~s/^[\#0]+//;
                   12573:         unless ($id) { next; }
                   12574:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   12575:             $entries[$idx]=~s/\,/\;/g;
                   12576:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   12577:             push(@idresponses,$entries[$idx]);
                   12578:         }
                   12579:         $$responses{$id}=join(',',@idresponses);
                   12580:     }
                   12581:     for (my $i=1; $i<=$number; $i++) {
                   12582:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   12583:     }
                   12584:     return ($errormsg,$number);
                   12585: }
                   12586: 
                   12587: 
1.414     www      12588: sub assign_clicker_grades {
1.766     raeburn  12589:     my ($r,$symb) = @_;
1.414     www      12590:     if (!$symb) {return '';}
1.416     www      12591: # See which part we are saving to
1.582     raeburn  12592:     my $res_error;
                   12593:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   12594:     if ($res_error) {
                   12595:         return &navmap_errormsg();
                   12596:     }
1.804     raeburn  12597:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12598:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12599:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   12600:     my (%skip_passback,%pbsave); 
1.416     www      12601: # FIXME: This should probably look for the first handgradeable part
                   12602:     my $part=$$partlist[0];
                   12603: # Start screen output
1.766     raeburn  12604:     my $result = &Apache::loncommon::start_data_table().
                   12605:                  &Apache::loncommon::start_data_table_header_row().
                   12606:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   12607:                  &Apache::loncommon::end_data_table_header_row().
                   12608:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      12609: # Get correct result
                   12610: # FIXME: Possibly need delimiter other than ":"
                   12611:     my @correct=();
1.415     www      12612:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   12613:     my $number=$env{'form.number'};
                   12614:     if ($gradingmechanism ne 'attendance') {
1.414     www      12615:        foreach my $key (keys(%env)) {
                   12616:           if ($key=~/^form\.correct\:/) {
                   12617:              my @input=split(/\,/,$env{$key});
                   12618:              for (my $i=0;$i<=$#input;$i++) {
                   12619:                  if (($correct[$i]) && ($input[$i]) &&
                   12620:                      ($correct[$i] ne $input[$i])) {
                   12621:                     $result.='<br /><span class="LC_warning">'.
                   12622:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   12623:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      12624:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      12625:                     $correct[$i]=$input[$i];
                   12626:                  }
                   12627:              }
                   12628:           }
                   12629:        }
1.415     www      12630:        for (my $i=0;$i<$number;$i++) {
1.644     www      12631:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      12632:              $result.='<br /><span class="LC_error">'.
                   12633:                       &mt('No correct result given for question "[_1]"!',
                   12634:                           $env{'form.question:'.$i}).'</span>';
                   12635:           }
                   12636:        }
1.644     www      12637:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      12638:     }
                   12639: # Start grading
1.415     www      12640:     my $pcorrect=$env{'form.pcorrect'};
                   12641:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      12642:     my $storecount=0;
1.632     www      12643:     my %users=();
1.415     www      12644:     foreach my $key (keys(%env)) {
1.420     www      12645:        my $user='';
1.415     www      12646:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      12647:           $user=$1;
                   12648:        }
                   12649:        if ($key=~/^form\.unknown\:(.*)$/) {
                   12650:           my $id=$1;
                   12651:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   12652:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      12653:           } elsif ($env{'form.multi'.$id}) {
                   12654:              $user=$env{'form.multi'.$id};
1.420     www      12655:           }
                   12656:        }
1.632     www      12657:        if ($user) {
                   12658:           if ($users{$user}) {
                   12659:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   12660:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      12661:                       '</span><br />';
                   12662:           }
                   12663:           $users{$user}=1; 
1.415     www      12664:           my @answer=split(/\,/,$env{$key});
                   12665:           my $sum=0;
1.522     www      12666:           my $realnumber=$number;
1.415     www      12667:           for (my $i=0;$i<$number;$i++) {
1.576     www      12668:              if  ($correct[$i] eq '-') {
                   12669:                 $realnumber--;
1.766     raeburn  12670:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      12671:                 if ($gradingmechanism eq 'attendance') {
                   12672:                    $sum+=$pcorrect;
1.576     www      12673:                 } elsif ($correct[$i] eq '*') {
1.522     www      12674:                    $sum+=$pcorrect;
1.415     www      12675:                 } else {
1.644     www      12676: # We actually grade if correct or not
                   12677:                    my $increment=$pincorrect;
                   12678: # Special case: numerical answer "0"
                   12679:                    if ($correct[$i] eq '0') {
                   12680:                       if ($answer[$i]=~/^[0\.]+$/) {
                   12681:                          $increment=$pcorrect;
                   12682:                       }
                   12683: # General numerical answer, both evaluate to something non-zero
                   12684:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   12685:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   12686:                          $increment=$pcorrect;
                   12687:                       }
                   12688: # Must be just alphanumeric
                   12689:                    } elsif ($answer[$i] eq $correct[$i]) {
                   12690:                       $increment=$pcorrect;
1.415     www      12691:                    }
1.644     www      12692:                    $sum+=$increment;
1.415     www      12693:                 }
                   12694:              }
                   12695:           }
1.522     www      12696:           my $ave=$sum/(100*$realnumber);
1.416     www      12697: # Store
                   12698:           my ($username,$domain)=split(/\:/,$user);
                   12699:           my %grades=();
                   12700:           $grades{"resource.$part.solved"}='correct_by_override';
                   12701:           $grades{"resource.$part.awarded"}=$ave;
                   12702:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   12703:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   12704:                                                  $env{'request.course.id'},
                   12705:                                                  $domain,$username);
                   12706:           if ($returncode ne 'ok') {
                   12707:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   12708:           } else {
                   12709:              $storecount++;
1.804     raeburn  12710:              if (keys(%needpb)) {
                   12711:                  my (%weights,%awardeds,%excuseds);
                   12712:                  my $usec = &Apache::lonnet::getsection($domain,$username,$env{'request.course.id'});
                   12713:                  $weights{$symb}{$part} = &Apache::lonnet::EXT("resource.$part.weight",$symb,$domain,$username,$usec);
                   12714:                  $awardeds{$symb}{$part} = $ave;
                   12715:                  $excuseds{$symb}{$part} = '';
                   12716:                  &process_passbacks('clickergrade',[$symb],$cdom,$cnum,$domain,$username,$usec,\%weights,
                   12717:                                     \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   12718:              }
1.416     www      12719:           }
1.415     www      12720:        }
                   12721:     }
                   12722: # We are done
1.549     hauer    12723:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      12724:              '</td>'.
                   12725:              &Apache::loncommon::end_data_table_row().
                   12726:              &Apache::loncommon::end_data_table();
1.614     www      12727:     return $result;
1.414     www      12728: }
                   12729: 
1.582     raeburn  12730: sub navmap_errormsg {
                   12731:     return '<div class="LC_error">'.
                   12732:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  12733:            &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  12734:            '</div>';
                   12735: }
1.607     droeschl 12736: 
1.609     www      12737: sub startpage {
1.777     raeburn  12738:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  12739:     my %args;
                   12740:     if ($onload) {
                   12741:          my %loaditems = (
                   12742:                         'onload' => $onload,
                   12743:                       );
                   12744:          $args{'add_entries'} = \%loaditems;
                   12745:     }
1.671     raeburn  12746:     if ($nomenu) {
1.754     raeburn  12747:         $args{'only_body'} = 1; 
1.777     raeburn  12748:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  12749:     } else {
1.785     raeburn  12750:         if ($env{'request.course.id'}) { 
                   12751:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   12752:         }
1.754     raeburn  12753:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  12754:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  12755:         if ($env{'request.course.id'}) {
                   12756:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   12757:         }
1.671     raeburn  12758:     }
1.613     www      12759:     unless ($nodisplayflag) {
1.773     raeburn  12760:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      12761:     }
1.607     droeschl 12762: }
1.582     raeburn  12763: 
1.622     www      12764: sub select_problem {
                   12765:     my ($r)=@_;
1.632     www      12766:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  12767:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      12768:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   12769:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   12770: }
                   12771: 
1.793     raeburn  12772: #----- display problem, answer, and submissions for a single student (no grading)
                   12773: 
                   12774: sub view_as_user {
                   12775:     my ($symb,$vuname,$vudom,$hasperm) = @_;
                   12776:     my $plainname = &Apache::loncommon::plainname($vuname,$vudom,'lastname');
                   12777:     my $displayname = &nameUserString('',$plainname,$vuname,$vudom);
                   12778:     my $output = &Apache::loncommon::get_student_view($symb,$vuname,$vudom,
                   12779:                                                       $env{'request.course.id'},
                   12780:                                                       undef,{'disable_submit' => 1}).
                   12781:                  "\n\n".
                   12782:                  '<div class="LC_grade_show_user">'.
                   12783:                  '<h2>'.$displayname.'</h2>'.
                   12784:                  "\n".
                   12785:                  &Apache::loncommon::track_student_link('View recent activity',
                   12786:                                                         $vuname,$vudom,'check').' '.
                   12787:                  "\n";
                   12788:     if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) ||
                   12789:         (($env{'request.course.sec'} ne '') &&
                   12790:          &Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
                   12791:         $output .= &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   12792:                                                $vuname,$vudom,$symb,'check');
                   12793:     }
                   12794:     $output .= "\n";
                   12795:     my $companswer = &Apache::loncommon::get_student_answers($symb,$vuname,$vudom,
                   12796:                                                              $env{'request.course.id'});
                   12797:     $companswer=~s|<form(.*?)>||g;
                   12798:     $companswer=~s|</form>||g;
                   12799:     $companswer=~s|name="submit"|name="would_have_been_submit"|g;
                   12800:     $output .= '<div class="LC_Box">'.
                   12801:                '<h3 class="LC_hcell">'.&mt('Correct answer for[_1]',$displayname).'</h3>'.
                   12802:                $companswer.
                   12803:                '</div>'."\n";
                   12804:     my $is_tool = ($symb =~ /ext\.tool$/);
                   12805:     my ($essayurl,%coursedesc_by_cid);
                   12806:     (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   12807:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$vudom,$vuname);
                   12808:     my $res_error;
                   12809:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   12810:         &response_type($symb,\$res_error);
                   12811:     my $fullname;
                   12812:     my $collabinfo;
                   12813:     if ($numessay) {
                   12814:         unless ($hasperm) {
                   12815:             &init_perm();
                   12816:         }
                   12817:         ($collabinfo,$fullname)=
                   12818:             &check_collaborators($symb,$vuname,$vudom,\%record,$handgrade,0);
                   12819:         unless ($hasperm) {
                   12820:             &reset_perm();
                   12821:         }
                   12822:     }
                   12823:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   12824:                     '" src="'.$Apache::lonnet::perlvar{'lonIconsURL'}.
                   12825:                     '/check.gif" height="16" border="0" />';
                   12826:     my ($lastsubonly,$partinfo) =
                   12827:         &show_last_submission($vuname,$vudom,$symb,$essayurl,$responseType,'datesub',
                   12828:                               '',$fullname,\%record,\%coursedesc_by_cid);
                   12829:     $output .= '<div class="LC_Box">'.
                   12830:                '<h3 class="LC_hcell">'.&mt('Submissions').'</h3>'."\n".$collabinfo."\n";
                   12831:     if (($numresp > $numessay) & !$is_tool) {
                   12832:         $output .='<p class="LC_info">'.
                   12833:                   &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon).
                   12834:                   "</p>\n";
                   12835:     }
                   12836:     $output .= $partinfo;
                   12837:     $output .= $lastsubonly;
                   12838:     $output .= &displaySubByDates($symb,\%record,$partlist,$responseType,$checkIcon,$vuname,$vudom);
                   12839:     $output .= '</div></div>'."\n";
                   12840:     return $output;
                   12841: }
                   12842: 
1.1       albertel 12843: sub handler {
1.41      ng       12844:     my $request=$_[0];
1.434     albertel 12845:     &reset_caches();
1.646     raeburn  12846:     if ($request->header_only) {
                   12847:         &Apache::loncommon::content_type($request,'text/html');
                   12848:         $request->send_http_header;
                   12849:         return OK;
                   12850:     }
                   12851:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   12852: 
1.664     raeburn  12853: # see what command we need to execute
                   12854: 
                   12855:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   12856:     my $command=$commands[0];
                   12857: 
1.646     raeburn  12858:     &init_perm();
                   12859:     if (!$env{'request.course.id'}) {
1.664     raeburn  12860:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   12861:                 ($command =~ /^scantronupload/)) {
                   12862:             # Not in a course.
                   12863:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   12864:             return HTTP_NOT_ACCEPTABLE;
                   12865:         }
1.646     raeburn  12866:     } elsif (!%perm) {
                   12867:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  12868:         return OK;
1.41      ng       12869:     }
1.646     raeburn  12870:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       12871:     $request->send_http_header;
1.646     raeburn  12872: 
1.160     albertel 12873:     if ($#commands > 0) {
                   12874: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   12875:     }
1.608     www      12876: 
1.801     raeburn  12877: # -------------------------------------- Flag and buffer for registered cleanup
                   12878:     $registered_cleanup=0;
                   12879:     undef(@Apache::grades::ltipassback);
                   12880: 
1.608     www      12881: # see what the symb is
                   12882: 
                   12883:     my $symb=$env{'form.symb'};
                   12884:     unless ($symb) {
                   12885:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   12886:        $symb=&Apache::lonnet::symbread($url);
                   12887:     }
1.646     raeburn  12888:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      12889: 
1.513     foxr     12890:     $ssi_error = 0;
1.637     www      12891:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      12892: #
1.637     www      12893: # Not called from a resource, but inside a course
1.601     www      12894: #    
1.622     www      12895:         &startpage($request,undef,[],1,1);
                   12896:         &select_problem($request);
1.41      ng       12897:     } else {
1.104     albertel 12898: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  12899:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  12900:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   12901:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12902:                     &choose_task_version_form($symb,$env{'form.student'},
                   12903:                                               $env{'form.userdom'});
                   12904:             }
1.773     raeburn  12905:             my $divforres;
                   12906:             if ($env{'form.student'} eq '') {
                   12907:                 $js .= &part_selector_js();
                   12908:                 $onload = "toggleParts('gradesub');";
                   12909:             } else {
                   12910:                 $divforres = 1;
                   12911:             }
1.778     raeburn  12912:             my $head_extra = $js;
                   12913:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12914:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12915:                 if ($csslinks) {
                   12916:                     $head_extra .= "\n$csslinks";
                   12917:                 }
                   12918:             }
1.777     raeburn  12919:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   12920:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  12921:             if ($versionform) {
1.775     raeburn  12922:                 if ($divforres) {
                   12923:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   12924:                 }
1.671     raeburn  12925:                 $request->print($versionform);
                   12926:             }
1.773     raeburn  12927: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  12928:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   12929:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12930:                 &choose_task_version_form($symb,$env{'form.student'},
                   12931:                                           $env{'form.userdom'},
                   12932:                                           $env{'form.inhibitmenu'});
1.778     raeburn  12933:             my $head_extra = $js;
                   12934:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12935:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12936:                 if ($csslinks) {
                   12937:                     $head_extra .= "\n$csslinks";
                   12938:                 }
                   12939:             }
1.777     raeburn  12940:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   12941:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  12942:             if ($versionform) {
                   12943:                 $request->print($versionform);
                   12944:             }
                   12945:             $request->print('<br clear="all" />');
                   12946:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 12947: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      12948:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12949:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      12950: 	    &pickStudentPage($request,$symb);
1.103     albertel 12951: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  12952:             my $csslinks;
                   12953:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12954:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  12955:             }
1.615     www      12956:             &startpage($request,$symb,
                   12957:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12958:                                        {href=>'',text=>'Select student'},
1.777     raeburn  12959:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      12960: 	    &displayPage($request,$symb);
1.104     albertel 12961: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      12962:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12963:                                        {href=>'',text=>'Select student'},
                   12964:                                        {href=>'',text=>'Grade student'},
                   12965:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      12966: 	    &updateGradeByPage($request,$symb);
1.104     albertel 12967: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  12968:             my $csslinks;
                   12969:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12970:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12971:             }
1.619     www      12972:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  12973:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      12974: 	    &processGroup($request,$symb);
1.104     albertel 12975: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      12976:             &startpage($request,$symb);
                   12977: 	    $request->print(&grading_menu($request,$symb));
1.598     www      12978: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      12979:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      12980: 	    $request->print(&submit_options($request,$symb));
1.598     www      12981:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  12982:             my $js = &part_selector_js();
                   12983:             my $onload = "toggleParts('gradesub');";
                   12984:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   12985:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      12986:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      12987:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      12988:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      12989:             $request->print(&submit_options_table($request,$symb));
1.598     www      12990:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      12991:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      12992:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 12993: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      12994:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      12995: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 12996: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      12997:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   12998:                                        {href=>'',text=>'Store grades'}]);
1.608     www      12999: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 13000: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      13001:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   13002:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   13003:                                                                              text=>"Modify grades"},
                   13004:                                        {href=>'', text=>"Store grades"}]);
1.608     www      13005: 	    $request->print(&editgrades($request,$symb));
1.602     www      13006:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      13007:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      13008:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 13009: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      13010:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   13011:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      13012: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      13013:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      13014:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      13015:             $request->print(&process_clicker($request,$symb));
1.400     www      13016:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      13017:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   13018:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      13019:             $request->print(&process_clicker_file($request,$symb));
1.414     www      13020:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      13021:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   13022:                                        {href=>'', text=>'Process clicker file'},
                   13023:                                        {href=>'', text=>'Store grades'}]);
1.608     www      13024:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 13025: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      13026:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13027: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 13028: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      13029:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13030: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 13031: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      13032:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13033: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 13034: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 13035: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      13036:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13037: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       13038: 	    } else {
1.257     albertel 13039: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   13040: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       13041: 		} else {
1.257     albertel 13042: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       13043: 		}
1.627     www      13044:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13045: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       13046: 	    }
1.246     albertel 13047: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      13048:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13049: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 13050: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  13051:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   13052:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      13053: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 13054:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      13055:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13056:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 13057: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      13058:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13059: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 13060: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      13061:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13062: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 13063:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  13064:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  13065:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   13066:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      13067:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 13068:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  13069:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      13070:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13071:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  13072:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      13073:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13074:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  13075:         } elsif ($command eq 'scantronupload_delete' &&
                   13076:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   13077:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   13078:             &scantron_upload_delete($request,$symb);
1.523     raeburn  13079:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      13080:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      13081:             $request->print(&checkscantron_results($request,$symb));
                   13082:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  13083:             my $js = &part_selector_js();
                   13084:             my $onload = "toggleParts('gradingMenu');";
                   13085:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   13086:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      13087:             $request->print(&submit_options_download($request,$symb));
                   13088:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   13089:             &startpage($request,$symb,
                   13090:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  13091:     {href=>'', text=>'Download submitted files'}],
                   13092:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  13093:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      13094:             &submit_download_link($request,$symb);
1.796     raeburn  13095:         } elsif ($command eq 'initialpassback') {
                   13096:             &startpage($request,$symb,[{href=>'', text=>'Choose Launcher'}],undef,1);
                   13097:             $request->print(&initialpassback($request,$symb));
                   13098:         } elsif ($command eq 'passback') {
                   13099:             &startpage($request,$symb,
                   13100:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13101:                         {href=>'', text=>'Types of User'}],undef,1);
                   13102:             $request->print(&passback_filters($request,$symb));
                   13103:         } elsif ($command eq 'passbacknames') {
                   13104:             my $chosen;
                   13105:             if ($env{'form.passback'} ne '') {
                   13106:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13107:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13108:                 }
                   13109:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13110:             }
                   13111:             &startpage($request,$symb,
                   13112:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13113:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13114:                         {href=>'', text=>'Select Users'}],undef,1);
                   13115:             $request->print(&names_for_passback($request,$symb));
                   13116:         } elsif ($command eq 'passbackscores') {
                   13117:             my ($chosen,$stu_status);
                   13118:             if ($env{'form.passback'} ne '') {
                   13119:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13120:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13121:                 }
                   13122:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13123:             }
                   13124:             if ($env{'form.Status'}) {
                   13125:                 $stu_status = &HTML::Entities::encode($env{'form.Status'});
                   13126:             }
                   13127:             &startpage($request,$symb,
                   13128:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13129:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13130:                         {href=>&href_symb_cmd($symb,'passbacknames').'&amp;Status='.$stu_status.'&amp;passback='.$chosen, text=>'Select Users'},
                   13131:                         {href=>'', text=>'Execute Passback'}],undef,1);
                   13132:             $request->print(&do_passback($request,$symb));
1.106     albertel 13133: 	} elsif ($command) {
1.620     www      13134:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   13135: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 13136: 	}
1.2       albertel 13137:     }
1.513     foxr     13138:     if ($ssi_error) {
                   13139: 	&ssi_print_error($request);
                   13140:     }
1.671     raeburn  13141:     if ($env{'form.inhibitmenu'}) {
                   13142:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  13143:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  13144:         &Apache::lonquickgrades::endGradeScreen($request);
                   13145:     }
1.434     albertel 13146:     &reset_caches();
1.646     raeburn  13147:     return OK;
1.44      ng       13148: }
                   13149: 
1.1       albertel 13150: 1;
                   13151: 
1.13      albertel 13152: __END__;
1.531     jms      13153: 
                   13154: 
                   13155: =head1 NAME
                   13156: 
                   13157: Apache::grades
                   13158: 
                   13159: =head1 SYNOPSIS
                   13160: 
                   13161: Handles the viewing of grades.
                   13162: 
                   13163: This is part of the LearningOnline Network with CAPA project
                   13164: described at http://www.lon-capa.org.
                   13165: 
                   13166: =head1 OVERVIEW
                   13167: 
                   13168: Do an ssi with retries:
1.715     bisitz   13169: While I'd love to factor out this with the version in lonprintout,
1.531     jms      13170: 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
                   13171: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   13172: 
                   13173: At least the logic that drives this has been pulled out into loncommon.
                   13174: 
                   13175: 
                   13176: 
                   13177: ssi_with_retries - Does the server side include of a resource.
                   13178:                      if the ssi call returns an error we'll retry it up to
                   13179:                      the number of times requested by the caller.
1.715     bisitz   13180:                      If we still have a problem, no text is appended to the
1.531     jms      13181:                      output and we set some global variables.
                   13182:                      to indicate to the caller an SSI error occurred.  
                   13183:                      All of this is supposed to deal with the issues described
1.715     bisitz   13184:                      in LON-CAPA BZ 5631 see:
1.531     jms      13185:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   13186:                      by informing the user that this happened.
                   13187: 
                   13188: Parameters:
                   13189:   resource   - The resource to include.  This is passed directly, without
                   13190:                interpretation to lonnet::ssi.
                   13191:   form       - The form hash parameters that guide the interpretation of the resource
                   13192:                
                   13193:   retries    - Number of retries allowed before giving up completely.
                   13194: Returns:
                   13195:   On success, returns the rendered resource identified by the resource parameter.
                   13196: Side Effects:
                   13197:   The following global variables can be set:
                   13198:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   13199:                               It is up to the caller to initialize this to false
                   13200:                               if desired.
                   13201:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   13202:                               of the resource that could not be rendered by the ssi
                   13203:                               call.
                   13204:    ssi_error_message   - The error string fetched from the ssi response
                   13205:                               in the event of an error.
                   13206: 
                   13207: 
                   13208: =head1 HANDLER SUBROUTINE
                   13209: 
                   13210: ssi_with_retries()
                   13211: 
                   13212: =head1 SUBROUTINES
                   13213: 
                   13214: =over
                   13215: 
1.671     raeburn  13216: =head1 Routines to display previous version of a Task for a specific student
                   13217: 
                   13218: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   13219: can receive another opportunity. Access to tasks is slot-based. If a slot
                   13220: requires a proctor to check-in the student, a new version of the Task will
                   13221: be created when the student is checked in to the new opportunity.
                   13222: 
                   13223: If a particular student has tried two or more versions of a particular task,
                   13224: the submission screen provides a user with vgr privileges (e.g., a Course
                   13225: Coordinator) the ability to display a previous version worked on by the
                   13226: student.  By default, the current version is displayed. If a previous version
                   13227: has been selected for display, submission data are only shown that pertain
                   13228: to that particular version, and the interface to submit grades is not shown.
                   13229: 
                   13230: =over 4
                   13231: 
                   13232: =item show_previous_task_version()
                   13233: 
                   13234: Displays a specified version of a student's Task, as the student sees it.
                   13235: 
                   13236: Inputs: 2
                   13237:         request - request object
                   13238:         symb    - unique symb for current instance of resource
                   13239: 
                   13240: Output: None.
                   13241: 
                   13242: Side Effects: calls &show_problem() to print version of Task, with
                   13243:               version contained in form item: $env{'form.previousversion'}
                   13244: 
                   13245: =item choose_task_version_form()
                   13246: 
                   13247: Displays a web form used to select which version of a student's view of a
                   13248: Task should be displayed.  Either launches a pop-up window, or replaces
                   13249: content in existing pop-up, or replaces page in main window.
                   13250: 
                   13251: Inputs: 4
                   13252:         symb    - unique symb for current instance of resource
                   13253:         uname   - username of student
                   13254:         udom    - domain of student
                   13255:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13256:                   breadcrumbs etc., are displayed
                   13257: 
                   13258: Output: 4
                   13259:         current   - student's current version
                   13260:         displayed - student's version being displayed
                   13261:         result    - scalar containing HTML for web form used to switch to
                   13262:                     a different version (or a link to close window, if pop-up).
                   13263:         js        - javascript for processing selection in versions web form
                   13264: 
                   13265: Side Effects: None.
                   13266: 
                   13267: =item previous_display_javascript()
                   13268: 
                   13269: Inputs: 2
                   13270:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13271:                   breadcrumbs etc., are displayed.
                   13272:         current - student's current version number.
                   13273: 
                   13274: Output: 1
                   13275:         js      - javascript for processing selection in versions web form.
                   13276: 
                   13277: Side Effects: None.
                   13278: 
                   13279: =back
                   13280: 
                   13281: =head1 Routines to process bubblesheet data.
                   13282: 
                   13283: =over 4
                   13284: 
1.531     jms      13285: =item scantron_get_correction() : 
                   13286: 
                   13287:    Builds the interface screen to interact with the operator to fix a
                   13288:    specific error condition in a specific scanline
                   13289: 
                   13290:  Arguments:
                   13291:     $r           - Apache request object
                   13292:     $i           - number of the current scanline
                   13293:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  13294:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      13295:     $line        - full contents of the current scanline
                   13296:     $error       - error condition, valid values are
                   13297:                    'incorrectCODE', 'duplicateCODE',
                   13298:                    'doublebubble', 'missingbubble',
                   13299:                    'duplicateID', 'incorrectID'
                   13300:     $arg         - extra information needed
                   13301:        For errors:
                   13302:          - duplicateID   - paper number that this studentID was seen before on
                   13303:          - duplicateCODE - array ref of the paper numbers this CODE was
                   13304:                            seen on before
                   13305:          - incorrectCODE - current incorrect CODE 
                   13306:          - doublebubble  - array ref of the bubble lines that have double
                   13307:                            bubble errors
                   13308:          - missingbubble - array ref of the bubble lines that have missing
                   13309:                            bubble errors
                   13310: 
1.788     raeburn  13311:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   13312:    $randompick  - True if exam folder (or a sub-folder) has randompick set
1.691     raeburn  13313:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   13314:                      for current line to question number used for same question
                   13315:                      in "Master Seqence" (as seen by Course Coordinator).
                   13316:    $startline   - Reference to hash where key is question number (0 is first)
                   13317:                   and value is number of first bubble line for current student
                   13318:                   or code-based randompick and/or randomorder.
                   13319: 
                   13320: 
                   13321: 
1.531     jms      13322: =item  scantron_get_maxbubble() : 
                   13323: 
1.582     raeburn  13324:    Arguments:
                   13325:        $nav_error  - Reference to scalar which is a flag to indicate a
                   13326:                       failure to retrieve a navmap object.
                   13327:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   13328:        calling routine should trap the error condition and display the warning
                   13329:        found in &navmap_errormsg().
                   13330: 
1.649     raeburn  13331:        $scantron_config - Reference to bubblesheet format configuration hash.
                   13332: 
1.531     jms      13333:    Returns the maximum number of bubble lines that are expected to
                   13334:    occur. Does this by walking the selected sequence rendering the
                   13335:    resource and then checking &Apache::lonxml::get_problem_counter()
                   13336:    for what the current value of the problem counter is.
                   13337: 
                   13338:    Caches the results to $env{'form.scantron_maxbubble'},
                   13339:    $env{'form.scantron.bubble_lines.n'}, 
                   13340:    $env{'form.scantron.first_bubble_line.n'} and
                   13341:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  13342:    which are the total number of bubble lines, the number of bubble
1.531     jms      13343:    lines for response n and number of the first bubble line for response n,
                   13344:    and a comma separated list of numbers of bubble lines for sub-questions
                   13345:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   13346: 
                   13347: 
                   13348: =item  scantron_validate_missingbubbles() : 
                   13349: 
                   13350:    Validates all scanlines in the selected file to not have any
                   13351:     answers that don't have bubbles that have not been verified
                   13352:     to be bubble free.
                   13353: 
                   13354: =item  scantron_process_students() : 
                   13355: 
1.659     raeburn  13356:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      13357: 
                   13358:    The parsed scanline hash is added to %env 
                   13359: 
                   13360:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   13361:    foreach resource , with the form data of
                   13362: 
                   13363: 	'submitted'     =>'scantron' 
                   13364: 	'grade_target'  =>'grade',
                   13365: 	'grade_username'=> username of student
                   13366: 	'grade_domain'  => domain of student
                   13367: 	'grade_courseid'=> of course
                   13368: 	'grade_symb'    => symb of resource to grade
                   13369: 
                   13370:     This triggers a grading pass. The problem grading code takes care
                   13371:     of converting the bubbled letter information (now in %env) into a
                   13372:     valid submission.
                   13373: 
                   13374: =item  scantron_upload_scantron_data() :
                   13375: 
1.659     raeburn  13376:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      13377: 
                   13378: =item  scantron_upload_scantron_data_save() : 
                   13379: 
                   13380:    Adds a provided bubble information data file to the course if user
1.770     raeburn  13381:    has the correct privileges to do so.
                   13382: 
                   13383: = item scantron_upload_delete() :
                   13384: 
                   13385:    Deletes a previously uploaded bubble information data file, if user
                   13386:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      13387: 
                   13388: =item  valid_file() :
                   13389: 
                   13390:    Validates that the requested bubble data file exists in the course.
                   13391: 
                   13392: =item  scantron_download_scantron_data() : 
                   13393: 
                   13394:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  13395:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      13396:    course.
                   13397: 
                   13398: =item  scantron_validate_ID() : 
                   13399: 
                   13400:    Validates all scanlines in the selected file to not have any
1.556     weissno  13401:    invalid or underspecified student/employee IDs
1.531     jms      13402: 
1.582     raeburn  13403: =item navmap_errormsg() :
                   13404: 
                   13405:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  13406:    Should be called whenever the request to instantiate a navmap object fails.
                   13407: 
                   13408: =back
1.582     raeburn  13409: 
1.531     jms      13410: =back
                   13411: 
                   13412: =cut

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