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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.804   ! raeburn     4: # $Id: grades.pm,v 1.803 2024/12/10 17:04:38 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.752     raeburn    49: use Apache::lontexconvert();
1.796     raeburn    50: use Apache::loncourserespicker;
1.170     albertel   51: use String::Similarity;
1.760     raeburn    52: use HTML::Parser();
                     53: use File::MMagic;
1.359     www        54: use LONCAPA;
1.796     raeburn    55: use LONCAPA::ltiutils();
1.359     www        56: 
1.315     bowersj2   57: use POSIX qw(floor);
1.87      www        58: 
1.435     foxr       59: 
1.513     foxr       60: 
1.435     foxr       61: my %perm=();
1.674     raeburn    62: my %old_essays=();
1.447     foxr       63: 
1.513     foxr       64: #  These variables are used to recover from ssi errors
                     65: 
                     66: my $ssi_retries = 5;
                     67: my $ssi_error;
                     68: my $ssi_error_resource;
                     69: my $ssi_error_message;
1.798     raeburn    70: my $registered_cleanup;
1.513     foxr       71: 
                     72: sub ssi_with_retries {
                     73:     my ($resource, $retries, %form) = @_;
                     74:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     75:     if ($response->is_error) {
                     76: 	$ssi_error          = 1;
                     77: 	$ssi_error_resource = $resource;
                     78: 	$ssi_error_message  = $response->code . " " . $response->message;
                     79:     }
                     80: 
                     81:     return $content;
                     82: 
                     83: }
                     84: #
                     85: #  Prodcuces an ssi retry failure error message to the user:
                     86: #
                     87: 
                     88: sub ssi_print_error {
                     89:     my ($r) = @_;
1.516     raeburn    90:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     91:     $r->print('
                     92: <br />
                     93: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     94: <p>
                     95: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     96: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     97: '.&mt('Error:').' '.$ssi_error_message.'
                     98: </p>
                     99: <p>'.
                    100: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                    101: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                    102: '</p>');
                    103:     return;
1.513     foxr      104: }
                    105: 
1.44      ng        106: #
1.146     albertel  107: # --- Retrieve the parts from the metadata file.---
1.598     www       108: # Returns an array of everything that the resources stores away
                    109: #
                    110: 
1.44      ng        111: sub getpartlist {
1.582     raeburn   112:     my ($symb,$errorref) = @_;
1.439     albertel  113: 
                    114:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   115:     unless (ref($navmap)) {
                    116:         if (ref($errorref)) { 
                    117:             $$errorref = 'navmap';
                    118:             return;
                    119:         }
                    120:     }
1.439     albertel  121:     my $res      = $navmap->getBySymb($symb);
                    122:     my $partlist = $res->parts();
                    123:     my $url      = $res->src();
1.745     raeburn   124:     my $toolsymb;
                    125:     if ($url =~ /ext\.tool$/) {
                    126:         $toolsymb = $symb;
                    127:     }
                    128:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
1.439     albertel  129: 
1.146     albertel  130:     my @stores;
1.439     albertel  131:     foreach my $part (@{ $partlist }) {
1.146     albertel  132: 	foreach my $key (@metakeys) {
                    133: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    134: 	}
                    135:     }
                    136:     return @stores;
1.2       albertel  137: }
                    138: 
1.129     ng        139: #--- Format fullname, username:domain if different for display
                    140: #--- Use anywhere where the student names are listed
                    141: sub nameUserString {
                    142:     my ($type,$fullname,$uname,$udom) = @_;
                    143:     if ($type eq 'header') {
1.485     albertel  144: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        145:     } else {
1.398     albertel  146: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    147: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        148:     }
                    149: }
                    150: 
1.44      ng        151: #--- Get the partlist and the response type for a given problem. ---
1.773     raeburn   152: #--- Count responseIDs, essayresponse items, and dropbox items ---
1.623     www       153: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        154: sub response_type {
1.582     raeburn   155:     my ($symb,$response_error) = @_;
1.377     albertel  156: 
                    157:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   158:     unless (ref($navmap)) {
                    159:         if (ref($response_error)) {
                    160:             $$response_error = 1;
                    161:         }
                    162:         return;
                    163:     }
1.377     albertel  164:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   165:     unless (ref($res)) {
                    166:         $$response_error = 1;
                    167:         return;
                    168:     }
1.377     albertel  169:     my $partlist = $res->parts();
1.773     raeburn   170:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
1.392     albertel  171:     my %vPart = 
                    172: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  173:     my (%response_types,%handgrade);
                    174:     foreach my $part (@{ $partlist }) {
1.392     albertel  175: 	next if (%vPart && !exists($vPart{$part}));
                    176: 
1.377     albertel  177: 	my @types = $res->responseType($part);
                    178: 	my @ids = $res->responseIds($part);
                    179: 	for (my $i=0; $i < scalar(@ids); $i++) {
1.773     raeburn   180:             $numresp ++;
1.377     albertel  181: 	    $response_types{$part}{$ids[$i]} = $types[$i];
1.773     raeburn   182:             if ($types[$i] eq 'essay') {
                    183:                 $numessay ++;
                    184:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
                    185:                     $numdropbox ++;
                    186:                 }
                    187:             }
1.377     albertel  188: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    189: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    190: 				     '.handgrade',$symb);
1.41      ng        191: 	}
                    192:     }
1.773     raeburn   193:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
1.39      ng        194: }
                    195: 
1.375     albertel  196: sub flatten_responseType {
                    197:     my ($responseType) = @_;
                    198:     my @part_response_id =
                    199: 	map { 
                    200: 	    my $part = $_;
                    201: 	    map {
                    202: 		[$part,$_]
                    203: 		} sort(keys(%{ $responseType->{$part} }));
                    204: 	} sort(keys(%$responseType));
                    205:     return @part_response_id;
                    206: }
                    207: 
1.207     albertel  208: sub get_display_part {
1.324     albertel  209:     my ($partID,$symb)=@_;
1.207     albertel  210:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    211:     if (defined($display) and $display ne '') {
1.577     bisitz    212:         $display.= ' (<span class="LC_internal_info">'
                    213:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  214:     } else {
                    215: 	$display=$partID;
                    216:     }
                    217:     return $display;
                    218: }
1.269     raeburn   219: 
1.773     raeburn   220: #--- Show parts and response type
                    221: sub showResourceInfo {
                    222:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
                    223:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
                    224:         return '<br clear="all">';
                    225:     }
                    226:     my $coltitle = &mt('Problem Part Shown');
                    227:     if ($checkboxes) {
                    228:         $coltitle = &mt('Problem Part');
                    229:     } else {
                    230:         my $checkedparts = 0;
                    231:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                    232:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
                    233:                 $checkedparts ++;
                    234:             }
                    235:         }
                    236:         if ($checkedparts == scalar(@{$partlist})) {
                    237:             return '<br clear="all">';
                    238:         }
                    239:         if ($uploads) {
                    240:             $coltitle = &mt('Problem Part Selected');
                    241:         }
                    242:     }
                    243:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
                    244:     if ($checkboxes) {
                    245:         my $legend = &mt('Parts to display');
                    246:         if ($uploads) {
                    247:             $legend = &mt('Part(s) with dropbox');
                    248:         }
                    249:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
                    250:                    '<span class="LC_nobreak">'.
                    251:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
                    252:                    &mt('All parts').'</label>'.('&nbsp;'x2).
                    253:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
                    254:                    &mt('Selected parts').'</label></span>'.
                    255:                    '<div id="LC_partselector" style="display:none">';
                    256:     }
                    257:     $result .= &Apache::loncommon::start_data_table()
                    258:               .&Apache::loncommon::start_data_table_header_row();
                    259:     if ($checkboxes) {
                    260:         $result .= '<th>'.&mt('Display?').'</th>';
                    261:     }
                    262:     $result .= '<th>'.$coltitle.'</th>'
                    263:               .'<th>'.&mt('Res. ID').'</th>'
                    264:               .'<th>'.&mt('Type').'</th>'
                    265:               .&Apache::loncommon::end_data_table_header_row();
                    266:     my %partsseen;
                    267:     foreach my $partID (sort(keys(%$responseType))) {
                    268:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    269:             my $responsetype = $responseType->{$partID}->{$resID};
                    270:             if ($uploads) {
                    271:                 next unless ($responsetype eq 'essay');
                    272:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
                    273:             }
                    274:             my $display_part=&get_display_part($partID,$symb);
                    275:             if (exists($partsseen{$partID})) {
                    276:                 $result.=&Apache::loncommon::continue_data_table_row();
                    277:             } else {
                    278:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
                    279:                 $result.=&Apache::loncommon::start_data_table_row().
                    280:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
                    281:                 if ($checkboxes) {
                    282:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
                    283:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
                    284:                 } else {
                    285:                     $result.=$display_part.'</td>';
                    286:                 }
                    287:             }
                    288:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
                    289:                     .'<td>'.&mt($responsetype).'</td>'
                    290:                     .&Apache::loncommon::end_data_table_row();
                    291:         }
                    292:     }
                    293:     $result.=&Apache::loncommon::end_data_table();
                    294:     if ($checkboxes) {
                    295:         $result .= '</div></fieldset>';
                    296:     }
                    297:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
1.775     raeburn   298:     if (!keys(%partsseen)) {
                    299:         $result = '';
                    300:         if ($uploads) {
                    301:             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
                    302:                    '<p class="LC_info">'.
                    303:                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
                    304:                    '</p>';
                    305:         } else {
                    306:             return '<br clear="all" />';
                    307:         }
                    308:     }
1.773     raeburn   309:     return $result;
                    310: }
                    311: 
                    312: sub part_selector_js {
                    313:     my $js = <<"END";
                    314: function toggleParts(formname) {
                    315:     if (document.getElementById('LC_partselector')) {
                    316:         var index = '';
                    317:         if (document.forms.length) {
                    318:             for (var i=0; i<document.forms.length; i++) {
                    319:                 if (document.forms[i].name == formname) {
                    320:                     index = i;
                    321:                     break;
                    322:                 }
                    323:             }
                    324:         }
                    325:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
                    326:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
                    327:                 if (document.forms[index].elements['chooseparts'][i].checked) {
                    328:                    var val = document.forms[index].elements['chooseparts'][i].value;
                    329:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
                    330:                         document.getElementById('LC_partselector').style.display = 'block';
                    331:                     } else {
                    332:                         document.getElementById('LC_partselector').style.display = 'none';
                    333:                     }
                    334:                 }
                    335:             }
                    336:         }
                    337:     }
                    338: }
                    339: END
                    340:     return &Apache::lonhtmlcommon::scripttag($js);
                    341: }
                    342: 
1.434     albertel  343: sub reset_caches {
                    344:     &reset_analyze_cache();
                    345:     &reset_perm();
1.674     raeburn   346:     &reset_old_essays();
1.434     albertel  347: }
                    348: 
                    349: {
                    350:     my %analyze_cache;
1.557     raeburn   351:     my %analyze_cache_formkeys;
1.148     albertel  352: 
1.434     albertel  353:     sub reset_analyze_cache {
                    354: 	undef(%analyze_cache);
1.557     raeburn   355:         undef(%analyze_cache_formkeys);
1.434     albertel  356:     }
                    357: 
                    358:     sub get_analyze {
1.649     raeburn   359: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  360: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   361:         if ($type eq 'randomizetry') {
                    362:             if ($trial ne '') {
                    363:                 $key .= "\0".$trial;
                    364:             }
                    365:         }
1.557     raeburn   366: 	if (exists($analyze_cache{$key})) {
                    367:             my $getupdate = 0;
                    368:             if (ref($add_to_hash) eq 'HASH') {
                    369:                 foreach my $item (keys(%{$add_to_hash})) {
                    370:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    371:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    372:                             $getupdate = 1;
                    373:                             last;
                    374:                         }
                    375:                     } else {
                    376:                         $getupdate = 1;
                    377:                     }
                    378:                 }
                    379:             }
                    380:             if (!$getupdate) {
                    381:                 return $analyze_cache{$key};
                    382:             }
                    383:         }
1.434     albertel  384: 
                    385: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    386: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   387:         my %form = ('grade_target'      => 'analyze',
                    388:                     'grade_domain'      => $udom,
                    389:                     'grade_symb'        => $symb,
                    390:                     'grade_courseid'    =>  $env{'request.course.id'},
                    391:                     'grade_username'    => $uname,
                    392:                     'grade_noincrement' => $no_increment);
1.649     raeburn   393:         if ($bubbles_per_row ne '') {
                    394:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    395:         }
1.640     raeburn   396:         if ($type eq 'randomizetry') {
                    397:             $form{'grade_questiontype'} = $type;
                    398:             if ($rndseed ne '') {
                    399:                 $form{'grade_rndseed'} = $rndseed;
                    400:             }
                    401:         }
1.557     raeburn   402:         if (ref($add_to_hash)) {
                    403:             %form = (%form,%{$add_to_hash});
1.640     raeburn   404:         }
1.557     raeburn   405: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  406: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    407: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   408:         if (ref($add_to_hash) eq 'HASH') {
                    409:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    410:         } else {
                    411:             $analyze_cache_formkeys{$key} = {};
                    412:         }
1.434     albertel  413: 	return $analyze_cache{$key} = \%analyze;
                    414:     }
                    415: 
                    416:     sub get_order {
1.640     raeburn   417: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    418: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  419: 	return $analyze->{"$partid.$respid.shown"};
                    420:     }
                    421: 
                    422:     sub get_radiobutton_correct_foil {
1.640     raeburn   423: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    424: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    425:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   426:         if (ref($foils) eq 'ARRAY') {
                    427: 	    foreach my $foil (@{$foils}) {
                    428: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    429: 		    return $foil;
                    430: 	        }
1.434     albertel  431: 	    }
                    432: 	}
                    433:     }
1.554     raeburn   434: 
                    435:     sub scantron_partids_tograde {
1.741     raeburn   436:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   437:         my (%analysis,@parts);
                    438:         if (ref($resource)) {
                    439:             my $symb = $resource->symb();
1.557     raeburn   440:             my $add_to_form;
                    441:             if ($check_for_randomlist) {
                    442:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    443:             }
1.741     raeburn   444:             if ($scancode) {
                    445:                 if (ref($add_to_form) eq 'HASH') {
                    446:                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    447:                 } else {
                    448:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    449:                 }
                    450:             }
1.767     raeburn   451:             my $analyze =
1.649     raeburn   452:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    453:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   454:             if (ref($analyze) eq 'HASH') {
                    455:                 %analysis = %{$analyze};
                    456:             }
                    457:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    458:                 foreach my $part (@{$analysis{'parts'}}) {
                    459:                     my ($id,$respid) = split(/\./,$part);
                    460:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    461:                         push(@parts,$part);
                    462:                     }
                    463:                 }
                    464:             }
                    465:         }
                    466:         return (\%analysis,\@parts);
                    467:     }
                    468: 
1.148     albertel  469: }
1.434     albertel  470: 
1.118     ng        471: #--- Clean response type for display
1.335     albertel  472: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    473: #        response types only.
1.118     ng        474: sub cleanRecord {
1.336     albertel  475:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   476: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  477:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  478:     if ($response =~ /^(option|rank)$/) {
                    479: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     480:         my @answer = %answer;
1.767     raeburn   481:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  482: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    483: 	my ($toprow,$bottomrow);
                    484: 	foreach my $foil (@$order) {
                    485: 	    if ($grading{$foil} == 1) {
                    486: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    487: 	    } else {
                    488: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    489: 	    }
1.398     albertel  490: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  491: 	}
                    492: 	return '<blockquote><table border="1">'.
1.466     albertel  493: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    494: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   495: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  496:     } elsif ($response eq 'match') {
                    497: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     498:         my @answer = %answer;
1.767     raeburn   499:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  500: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    501: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    502: 	my ($toprow,$middlerow,$bottomrow);
                    503: 	foreach my $foil (@$order) {
                    504: 	    my $item=shift(@items);
                    505: 	    if ($grading{$foil} == 1) {
                    506: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  507: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  508: 	    } else {
                    509: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  510: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  511: 	    }
1.398     albertel  512: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        513: 	}
1.126     ng        514: 	return '<blockquote><table border="1">'.
1.466     albertel  515: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    516: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  517: 	    $middlerow.'</tr>'.
1.466     albertel  518: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   519: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  520:     } elsif ($response eq 'radiobutton') {
                    521: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     522:         my @answer = %answer;
                    523:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  524: 	my ($toprow,$bottomrow);
1.434     albertel  525: 	my $correct = 
1.640     raeburn   526: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  527: 	foreach my $foil (@$order) {
1.148     albertel  528: 	    if (exists($answer{$foil})) {
1.434     albertel  529: 		if ($foil eq $correct) {
1.466     albertel  530: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  531: 		} else {
1.466     albertel  532: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  533: 		}
                    534: 	    } else {
1.466     albertel  535: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  536: 	    }
1.398     albertel  537: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  538: 	}
                    539: 	return '<blockquote><table border="1">'.
1.466     albertel  540: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    541: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   542: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  543:     } elsif ($response eq 'essay') {
1.257     albertel  544: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        545: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  546: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    547: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        548: 
1.257     albertel  549: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    550: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    551: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    552: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    553: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    554: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        555: 	}
1.751     raeburn   556:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
1.730     kruse     557: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  558:     } elsif ( $response eq 'organic') {
1.721     bisitz    559:         my $result=&mt('Smile representation: [_1]',
                    560:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  561: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    562: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    563: 	return $result;
1.335     albertel  564:     } elsif ( $response eq 'Task') {
                    565: 	if ( $answer eq 'SUBMITTED') {
                    566: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  567: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  568: 	    return $result;
                    569: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    570: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    571: 			       keys(%{$record}));
                    572: 	    return join('<br />',($version,@matches));
                    573: 			       
                    574: 			       
                    575: 	} else {
                    576: 	    my $result =
                    577: 		'<p>'
                    578: 		.&mt('Overall result: [_1]',
                    579: 		     $record->{$version."resource.$respid.$partid.status"})
                    580: 		.'</p>';
                    581: 	    
                    582: 	    $result .= '<ul>';
                    583: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    584: 			     keys(%{$record}));
                    585: 	    foreach my $grade (sort(@grade)) {
                    586: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    587: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    588: 				     $dim, $record->{$grade}).
                    589: 			  '</li>';
                    590: 	    }
                    591: 	    $result.='</ul>';
                    592: 	    return $result;
                    593: 	}
1.716     bisitz    594:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    595:         # Respect multiple input fields, see Bug #5409
1.440     albertel  596: 	$answer = 
                    597: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    598: 							      $answer);
1.720     kruse     599: 	return $answer;
1.122     ng        600:     }
1.720     kruse     601:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        602: }
                    603: 
                    604: #-- A couple of common js functions
                    605: sub commonJSfunctions {
                    606:     my $request = shift;
1.597     wenzelju  607:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        608:     function radioSelection(radioButton) {
                    609: 	var selection=null;
                    610: 	if (radioButton.length > 1) {
                    611: 	    for (var i=0; i<radioButton.length; i++) {
                    612: 		if (radioButton[i].checked) {
                    613: 		    return radioButton[i].value;
                    614: 		}
                    615: 	    }
                    616: 	} else {
                    617: 	    if (radioButton.checked) return radioButton.value;
                    618: 	}
                    619: 	return selection;
                    620:     }
                    621: 
                    622:     function pullDownSelection(selectOne) {
                    623: 	var selection="";
                    624: 	if (selectOne.length > 1) {
                    625: 	    for (var i=0; i<selectOne.length; i++) {
                    626: 		if (selectOne[i].selected) {
                    627: 		    return selectOne[i].value;
                    628: 		}
                    629: 	    }
                    630: 	} else {
1.138     albertel  631:             // only one value it must be the selected one
                    632: 	    return selectOne.value;
1.118     ng        633: 	}
                    634:     }
                    635: COMMONJSFUNCTIONS
                    636: }
                    637: 
1.44      ng        638: #--- Dumps the class list with usernames,list of sections,
                    639: #--- section, ids and fullnames for each user.
                    640: sub getclasslist {
1.796     raeburn   641:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus,$filterbypbid,$possibles) = @_;
1.291     albertel  642:     my @getsec;
1.450     banghart  643:     my @getgroup;
1.442     banghart  644:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  645:     if (!ref($getsec)) {
                    646: 	if ($getsec ne '' && $getsec ne 'all') {
                    647: 	    @getsec=($getsec);
                    648: 	}
                    649:     } else {
                    650: 	@getsec=@{$getsec};
                    651:     }
                    652:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  653:     if (!ref($getgroup)) {
                    654: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    655: 	    @getgroup=($getgroup);
                    656: 	}
                    657:     } else {
                    658: 	@getgroup=@{$getgroup};
                    659:     }
                    660:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  661: 
1.449     banghart  662:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  663:     # Bail out if we were unable to get the classlist
1.56      matthew   664:     return if (! defined($classlist));
1.449     banghart  665:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   666:     #
                    667:     my %sections;
                    668:     my %fullnames;
1.796     raeburn   669:     my %passback;
1.750     raeburn   670:     my ($cdom,$cnum,$partlist);
                    671:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    672:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    673:         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    674:         my $res_error;
1.773     raeburn   675:         ($partlist) = &response_type($symb,\$res_error);
1.796     raeburn   676:     } elsif ($filterbypbid) {
                    677:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    678:         $cnum = $env{"course.$env{'request.course.id'}.num"};
1.750     raeburn   679:     }
1.205     matthew   680:     foreach my $student (keys(%$classlist)) {
                    681:         my $end      = 
                    682:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    683:         my $start    = 
                    684:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    685:         my $id       = 
                    686:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    687:         my $section  = 
                    688:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    689:         my $fullname = 
                    690:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    691:         my $status   = 
                    692:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  693:         my $group   = 
                    694:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        695: 	# filter students according to status selected
1.750     raeburn   696: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  697: 	    if (!($stu_status =~ $status)) {
1.450     banghart  698: 		delete($classlist->{$student});
1.76      ng        699: 		next;
                    700: 	    }
                    701: 	}
1.450     banghart  702: 	# filter students according to groups selected
1.453     banghart  703: 	my @stu_groups = split(/,/,$group);
1.450     banghart  704: 	if (@getgroup) {
                    705: 	    my $exclude = 1;
1.454     banghart  706: 	    foreach my $grp (@getgroup) {
                    707: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  708: 	            if ($stu_group eq $grp) {
                    709: 	                $exclude = 0;
                    710:     	            } 
1.450     banghart  711: 	        }
1.453     banghart  712:     	        if (($grp eq 'none') && !$group) {
1.750     raeburn   713:         	    $exclude = 0;
1.453     banghart  714:         	}
1.450     banghart  715: 	    }
                    716: 	    if ($exclude) {
                    717: 	        delete($classlist->{$student});
1.750     raeburn   718: 		next;
1.450     banghart  719: 	    }
                    720: 	}
1.750     raeburn   721:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    722:             my $udom =
                    723:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    724:             my $uname =
                    725:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    726:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    727:                 if ($submitonly eq 'queued') {
                    728:                     my %queue_status =
                    729:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    730:                                                                 $udom,$uname);
                    731:                     if (!defined($queue_status{'gradingqueue'})) {
                    732:                         delete($classlist->{$student});
                    733:                         next;
                    734:                     }
                    735:                 } else {
                    736:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    737:                     my $submitted = 0;
                    738:                     my $graded = 0;
                    739:                     my $incorrect = 0;
                    740:                     foreach (keys(%status)) {
                    741:                         $submitted = 1 if ($status{$_} ne 'nothing');
                    742:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    743:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    744: 
                    745:                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    746:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    747:                             $submitted = 0;
                    748:                         }
                    749:                     }
                    750:                     if (!$submitted && ($submitonly eq 'yes' ||
                    751:                                         $submitonly eq 'incorrect' ||
                    752:                                         $submitonly eq 'graded')) {
                    753:                         delete($classlist->{$student});
                    754:                         next;
                    755:                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    756:                         delete($classlist->{$student});
                    757:                         next;
                    758:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    759:                         delete($classlist->{$student});
                    760:                         next;
                    761:                     }
                    762:                 }
                    763:             }
                    764:         }
1.796     raeburn   765:         if ($filterbypbid) {
                    766:             if (ref($possibles) eq 'HASH') {
                    767:                 unless (exists($possibles->{$student})) {
                    768:                     delete($classlist->{$student});
                    769:                     next;
                    770:                 }
                    771:             }
                    772:             my $udom =
                    773:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    774:             my $uname =
                    775:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    776:             if (($udom ne '') && ($uname ne '')) {
                    777:                 my %pbinfo = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',[$filterbypbid],$udom,$uname);
                    778:                 if (ref($pbinfo{$filterbypbid}) eq 'ARRAY') {
1.798     raeburn   779:                     $passback{$student} = $pbinfo{$filterbypbid};
1.796     raeburn   780:                 } else {
                    781:                     delete($classlist->{$student});
                    782:                     next;
                    783:                 }
                    784:             }
                    785:         }
1.205     matthew   786: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  787: 	if (&canview($section)) {
1.291     albertel  788: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  789: 		$sections{$section}++;
1.450     banghart  790: 		if ($classlist->{$student}) {
                    791: 		    $fullnames{$student}=$fullname;
                    792: 		}
1.103     albertel  793: 	    } else {
1.205     matthew   794: 		delete($classlist->{$student});
1.103     albertel  795: 	    }
                    796: 	} else {
1.205     matthew   797: 	    delete($classlist->{$student});
1.103     albertel  798: 	}
1.44      ng        799:     }
1.56      matthew   800:     my @sections = sort(keys(%sections));
1.796     raeburn   801:     return ($classlist,\@sections,\%fullnames,\%passback);
1.44      ng        802: }
                    803: 
1.103     albertel  804: sub canmodify {
                    805:     my ($sec)=@_;
                    806:     if ($perm{'mgr'}) {
                    807: 	if (!defined($perm{'mgr_section'})) {
                    808: 	    # can modify whole class
                    809: 	    return 1;
                    810: 	} else {
                    811: 	    if ($sec eq $perm{'mgr_section'}) {
                    812: 		#can modify the requested section
                    813: 		return 1;
                    814: 	    } else {
1.763     raeburn   815: 		# can't modify the requested section
1.103     albertel  816: 		return 0;
                    817: 	    }
                    818: 	}
                    819:     }
                    820:     #can't modify
                    821:     return 0;
                    822: }
                    823: 
                    824: sub canview {
                    825:     my ($sec)=@_;
                    826:     if ($perm{'vgr'}) {
                    827: 	if (!defined($perm{'vgr_section'})) {
1.763     raeburn   828: 	    # can view whole class
1.103     albertel  829: 	    return 1;
                    830: 	} else {
                    831: 	    if ($sec eq $perm{'vgr_section'}) {
1.763     raeburn   832: 		#can view the requested section
1.103     albertel  833: 		return 1;
                    834: 	    } else {
1.763     raeburn   835: 		# can't view the requested section
1.103     albertel  836: 		return 0;
                    837: 	    }
                    838: 	}
                    839:     }
1.763     raeburn   840:     #can't view
1.103     albertel  841:     return 0;
                    842: }
                    843: 
1.44      ng        844: #--- Retrieve the grade status of a student for all the parts
                    845: sub student_gradeStatus {
1.324     albertel  846:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  847:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        848:     my %partstatus = ();
                    849:     foreach (@$partlist) {
1.128     ng        850: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        851: 	$status              = 'nothing' if ($status eq '');
                    852: 	$partstatus{$_}      = $status;
                    853: 	my $subkey           = "resource.$_.submitted_by";
                    854: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    855:     }
                    856:     return %partstatus;
                    857: }
                    858: 
1.45      ng        859: # hidden form and javascript that calls the form
                    860: # Use by verifyscript and viewgrades
                    861: # Shows a student's view of problem and submission
                    862: sub jscriptNform {
1.324     albertel  863:     my ($symb) = @_;
1.442     banghart  864:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  865:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        866: 	'    function viewOneStudent(user,domain) {'."\n".
                    867: 	'	document.onestudent.student.value = user;'."\n".
                    868: 	'	document.onestudent.userdom.value = domain;'."\n".
                    869: 	'	document.onestudent.submit();'."\n".
                    870: 	'    }'."\n".
1.597     wenzelju  871: 	"\n");
1.45      ng        872:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  873: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  874: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        875: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    876: 	'<input type="hidden" name="student" value="" />'."\n".
                    877: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    878: 	'</form>'."\n";
                    879:     return $jscript;
                    880: }
1.39      ng        881: 
1.447     foxr      882: 
                    883: 
1.315     bowersj2  884: # Given the score (as a number [0-1] and the weight) what is the final
                    885: # point value? This function will round to the nearest tenth, third,
                    886: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  887: sub compute_points {
1.315     bowersj2  888:     my ($score, $weight) = @_;
                    889:     
                    890:     my $tolerance = .00001;
                    891:     my $points = $score * $weight;
                    892: 
                    893:     # Check for nearness to 1/x.
                    894:     my $check_for_nearness = sub {
                    895:         my ($factor) = @_;
                    896:         my $num = ($points * $factor) + $tolerance;
                    897:         my $floored_num = floor($num);
1.316     albertel  898:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  899:             return $floored_num / $factor;
                    900:         }
                    901:         return $points;
                    902:     };
                    903: 
                    904:     $points = $check_for_nearness->(10);
                    905:     $points = $check_for_nearness->(3);
                    906:     $points = $check_for_nearness->(4);
                    907:     
                    908:     return $points;
                    909: }
                    910: 
1.44      ng        911: #------------------ End of general use routines --------------------
1.87      www       912: 
                    913: #
                    914: # Find most similar essay
                    915: #
                    916: 
                    917: sub most_similar {
1.674     raeburn   918:     my ($uname,$udom,$symb,$uessay)=@_;
                    919: 
                    920:     unless ($symb) { return ''; }
                    921: 
                    922:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       923: 
                    924: # ignore spaces and punctuation
                    925: 
                    926:     $uessay=~s/\W+/ /gs;
                    927: 
1.282     www       928: # ignore empty submissions (occuring when only files are sent)
                    929: 
1.598     www       930:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       931: 
1.87      www       932: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       933:     my $limit=0.6;
1.87      www       934:     my $sname='';
                    935:     my $sdom='';
                    936:     my $scrsid='';
                    937:     my $sessay='';
                    938: # go through all essays ...
1.674     raeburn   939:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  940: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       941: # ... except the same student
1.426     albertel  942:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   943: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  944: 	$tessay=~s/\W+/ /gs;
1.87      www       945: # String similarity gives up if not even limit
1.426     albertel  946: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       947: # Found one
1.426     albertel  948: 	if ($tsimilar>$limit) {
                    949: 	    $limit=$tsimilar;
                    950: 	    $sname=$tname;
                    951: 	    $sdom=$tdom;
                    952: 	    $scrsid=$tcrsid;
1.674     raeburn   953: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  954: 	}
1.87      www       955:     }
1.88      www       956:     if ($limit>0.6) {
1.87      www       957:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    958:     } else {
                    959:        return ('','','','',0);
                    960:     }
                    961: }
                    962: 
1.44      ng        963: #-------------------------------------------------------------------
                    964: 
                    965: #------------------------------------ Receipt Verification Routines
1.45      ng        966: #
1.602     www       967: 
                    968: sub initialverifyreceipt {
1.608     www       969:    my ($request,$symb) = @_;
1.602     www       970:    &commonJSfunctions($request);
1.694     bisitz    971:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       972:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    973:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       974:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    975:         '<input type="hidden" name="command" value="verify" />'.
                    976:         "</form>\n";
1.602     www       977: }
                    978: 
1.44      ng        979: #--- Check whether a receipt number is valid.---
                    980: sub verifyreceipt {
1.766     raeburn   981:     my ($request,$symb) = @_;
1.44      ng        982: 
1.257     albertel  983:     my $courseid = $env{'request.course.id'};
1.184     www       984:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  985: 	$env{'form.receipt'};
1.44      ng        986:     $receipt     =~ s/[^\-\d]//g;
                    987: 
1.766     raeburn   988:     my $title =
1.487     albertel  989: 	'<h3><span class="LC_info">'.
1.605     www       990: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    991: 	'</span></h3>'."\n";
1.44      ng        992: 
                    993:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   994:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  995:     
                    996:     my $receiptparts=0;
1.390     albertel  997:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    998: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  999:     my $parts=['0'];
1.582     raeburn  1000:     if ($receiptparts) {
                   1001:         my $res_error; 
                   1002:         ($parts)=&response_type($symb,\$res_error);
                   1003:         if ($res_error) {
                   1004:             return &navmap_errormsg();
                   1005:         } 
                   1006:     }
1.486     albertel 1007:     
                   1008:     my $header = 
                   1009: 	&Apache::loncommon::start_data_table().
                   1010: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel 1011: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                   1012: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                   1013: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel 1014:     if ($receiptparts) {
1.487     albertel 1015: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel 1016:     }
                   1017:     $header.=
                   1018: 	&Apache::loncommon::end_data_table_header_row();
                   1019: 
1.294     albertel 1020:     foreach (sort 
                   1021: 	     {
                   1022: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1023: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1024: 		 }
                   1025: 		 return $a cmp $b;
                   1026: 	     } (keys(%$fullname))) {
1.44      ng       1027: 	my ($uname,$udom)=split(/\:/);
1.177     albertel 1028: 	foreach my $part (@$parts) {
                   1029: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel 1030: 		$contents.=
                   1031: 		    &Apache::loncommon::start_data_table_row().
                   1032: 		    '<td>&nbsp;'."\n".
1.177     albertel 1033: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 1034: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel 1035: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                   1036: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                   1037: 		if ($receiptparts) {
                   1038: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                   1039: 		}
1.486     albertel 1040: 		$contents.= 
                   1041: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel 1042: 		
                   1043: 		$matches++;
                   1044: 	    }
1.44      ng       1045: 	}
                   1046:     }
                   1047:     if ($matches == 0) {
1.584     bisitz   1048:         $string = $title
                   1049:                  .'<p class="LC_warning">'
                   1050:                  .&mt('No match found for the above receipt number.')
                   1051:                  .'</p>';
1.44      ng       1052:     } else {
1.324     albertel 1053: 	$string = &jscriptNform($symb).$title.
1.487     albertel 1054: 	    '<p>'.
1.584     bisitz   1055: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel 1056: 	    '</p>'.
1.486     albertel 1057: 	    $header.
                   1058: 	    $contents.
                   1059: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng       1060:     }
1.614     www      1061:     return $string;
1.44      ng       1062: }
                   1063: 
1.798     raeburn  1064: #-------------------------------------------------------------------
                   1065: 
                   1066: #------------------------------------------- Grade Passback Routines
                   1067: #
                   1068: 
1.796     raeburn  1069: sub initialpassback {
                   1070:     my ($request,$symb) = @_;
                   1071:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1072:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1073:     my $crstype = &Apache::loncommon::course_type();
                   1074:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   1075:     my $readonly;
                   1076:     unless ($perm{'mgr'}) {
                   1077:         $readonly = 1;
                   1078:     }
                   1079:     my $formname = 'initialpassback';
                   1080:     my $navmap = Apache::lonnavmaps::navmap->new();
                   1081:     my $output;
                   1082:     if (!defined($navmap)) {
                   1083:         if ($crstype eq 'Community') {
                   1084:             $output = &mt('Unable to retrieve information about community contents');
                   1085:         } else {
                   1086:             $output = &mt('Unable to retrieve information about course contents');
                   1087:         }
                   1088:         return '<p>'.$output.'</p>';
                   1089:     }
                   1090:     return &Apache::loncourserespicker::create_picker($navmap,'passback',$formname,$crstype,undef,
                   1091:                                                       undef,undef,undef,undef,undef,undef,
                   1092:                                                       \%passback,$readonly);
                   1093: }
                   1094: 
                   1095: sub passback_filters {
                   1096:     my ($request,$symb) = @_;
                   1097:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1098:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1099:     my $crstype = &Apache::loncommon::course_type();
                   1100:     my ($launcher,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
                   1101:     if ($env{'form.passback'} ne '') {
                   1102:         $chosen = &unescape($env{'form.passback'});
                   1103:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1104:         ($launcher,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
                   1105:     }
                   1106:     my $result;
                   1107:     if ($launcher ne '') {
                   1108:         $result = &launcher_info_box($launcher,$appname,$setter,$linkuri,$scope).
                   1109:                   '<p><br />'.&mt('Set criteria to use to list students for possible passback of scores, then push Next [_1]',
                   1110:                                   '&rarr;').
                   1111:                   '</p>';
                   1112:     }
                   1113:     $result .= '<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   1114:                '<input type="hidden" name="passback" value="'.&escape($chosen).'" />'."\n".
                   1115:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   1116:     my ($submittext,$newcommand);
                   1117:     if ($launcher ne '') {
                   1118:         $submittext = &mt('Next').' &rarr;';
                   1119:         $newcommand = 'passbacknames';
                   1120:         $result .=  &selectfield(0)."\n";
                   1121:     } else {
                   1122:         $submittext = '&larr; '.&mt('Previous');
                   1123:         $newcommand = 'initialpassback';
                   1124:         if ($env{'form.passback'}) {
                   1125:             $result .= '<span class="LC_warning">'.&mt('Invalid launcher').'</span>'."\n";
                   1126:         } else {
                   1127:             $result .= '<span class="LC_warning">'.&mt('No launcher selected').'</span>'."\n";
                   1128:         }
                   1129:     }
                   1130:     $result .=  '<input type="hidden" name="command" value="'.$newcommand.'" />'."\n".
                   1131:                 '<div>'."\n".
                   1132:                 '<input type="submit" value="'.$submittext.'" />'."\n".
                   1133:                 '</div>'."\n".
                   1134:                 '</form>'."\n";
                   1135:     return $result;
                   1136: }
                   1137: 
                   1138: sub names_for_passback {
                   1139:     my ($request,$symb) = @_;
                   1140:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1141:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1142:     my $crstype = &Apache::loncommon::course_type();
                   1143:     my ($launcher,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
                   1144:     if ($env{'form.passback'} ne '') {
                   1145:         $chosen = &unescape($env{'form.passback'});
                   1146:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1147:         ($launcher,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
                   1148:     }
                   1149:     my ($result,$ctr,$newcommand,$submittext);
                   1150:     if ($launcher ne '') {
                   1151:         $result = &launcher_info_box($launcher,$appname,$setter,$linkuri,$scope);
                   1152:     }
                   1153:     $ctr = 0;
                   1154:     my @statuses = &Apache::loncommon::get_env_multiple('form.Status');
                   1155:     my $stu_status = join(':',@statuses);
                   1156:     $result .= '<form action="/adm/grades" method="post" name="passbackusers">'."\n".
                   1157:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   1158:     if ($launcher ne '') {
                   1159:         $result .= '<input type="hidden" name="passback" value="'.&escape($chosen).'" />'."\n".
                   1160:                    '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
                   1161:         my ($sections,$groups,$group_display,$disabled) = &sections_and_groups();
                   1162:         my $section_display = join(' ',@{$sections});
                   1163:         my $status_display;
                   1164:         if ((grep(/^Any$/,@statuses)) ||
                   1165:             (@statuses == 3)) {
                   1166:             $status_display = &mt('Any');
                   1167:         } else {
                   1168:             $status_display = join(' '.&mt('or').' ',map { &mt($_); } @statuses);
                   1169:         }
                   1170:         $result .= '<p>'.&mt('Student(s) with stored passback credentials for [_1], and also satisfy:',
                   1171:                              '<span class="LC_cusr_emph">'.$linkuri.'</span>').
                   1172:                    '<ul>'.
                   1173:                    '<li>'.&mt('Section(s)').": $section_display</li>\n".
                   1174:                    '<li>'.&mt('Group(s)').": $group_display</li>\n".
                   1175:                    '<li>'.&mt('Status').": $status_display</li>\n".
                   1176:                    '</ul>';
                   1177:         my ($classlist,undef,$fullname) = &getclasslist($sections,'1',$groups,'','','',$chosen);
                   1178:         if (keys(%$fullname)) {
                   1179:             $newcommand = 'passbackscores';
                   1180:             $result .= &build_section_inputs().
                   1181:                        &checkselect_js('passbackusers').
                   1182:                        '<p><br />'.
                   1183:                        &mt("To send scores, check box(es) next to the student's name(s), then push 'Send Scores'.").
                   1184:                        '</p>'.
                   1185:                        &check_script('passbackusers', 'stuinfo')."\n".
                   1186:                        '<input type="button" '."\n".
                   1187:                        'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1188:                        'value="'.&mt('Send Scores').'" /> <br />'."\n".
                   1189:                        &check_buttons()."\n".
                   1190:                        &Apache::loncommon::start_data_table().
                   1191:                        &Apache::loncommon::start_data_table_header_row();
                   1192:             my $loop = 0;
                   1193:             while ($loop < 2) {
                   1194:                 $result .= '<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1195:                            '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
                   1196:                 $loop++;
                   1197:             }
                   1198:             $result .= &Apache::loncommon::end_data_table_header_row()."\n";
                   1199:             foreach my $student (sort
                   1200:                                  {
                   1201:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1202:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1203:                                      }
                   1204:                                      return $a cmp $b;
                   1205:                                  }
                   1206:                                  (keys(%$fullname))) {
                   1207:                 $ctr++;
                   1208:                 my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                   1209:                 my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
                   1210:                 my $udom = $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                   1211:                 my $uname = $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                   1212:                 if ( $perm{'vgr'} eq 'F' ) {
                   1213:                     if ($ctr%2 ==1) {
                   1214:                         $result.= &Apache::loncommon::start_data_table_row();
                   1215:                     }
                   1216:                     $result .= '<td align="right">'.$ctr.'&nbsp;</td>'.
                   1217:                                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
                   1218:                                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1219:                                ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1220:                                &nameUserString(undef,$$fullname{$student},$uname,$udom).
                   1221:                                '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
                   1222: 
                   1223:                     if ($ctr%2 ==0) {
                   1224:                         $result .= &Apache::loncommon::end_data_table_row()."\n";
                   1225:                     }
                   1226:                 }
                   1227:             }
                   1228:             if ($ctr%2 ==1) {
                   1229:                 $result .= &Apache::loncommon::end_data_table_row();
                   1230:             }
                   1231:             $result .= &Apache::loncommon::end_data_table()."\n";
                   1232:             if ($ctr) {
                   1233:                 $result .= '<input type="button" '.
                   1234:                            'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1235:                            'value="'.&mt('Send Scores').'" />'."\n";
                   1236:             }
                   1237:         } else {
                   1238:             $submittext = '&larr; '.&mt('Previous');
                   1239:             $newcommand = 'passback';
                   1240:             $result .= '<span class="LC_warning">'.&mt('No students match the selection criteria').'</p>';
                   1241:         }
                   1242:     } else {
                   1243:         $newcommand = 'initialpassback';
                   1244:         $submittext = &mt('Start over');
                   1245:         if ($env{'form.passback'}) {
                   1246:             $result .= '<span class="LC_warning">'.&mt('Invalid launcher').'</span>'."\n";
                   1247:         } else {
                   1248:             $result .= '<span class="LC_warning">'.&mt('No launcher selected').'</span>'."\n";
                   1249:         }
                   1250:     }
                   1251:     $result .=  '<input type="hidden" name="command" value="'.$newcommand.'" />'."\n";
                   1252:     if (!$ctr) {
                   1253:         $result .= '<div>'."\n".
                   1254:                    '<input type="submit" value="'.$submittext.'" />'."\n".
                   1255:                    '</div>'."\n";
                   1256:     }
                   1257:     $result .= '</form>'."\n";
                   1258:     return $result;
                   1259: }
                   1260: 
                   1261: sub do_passback {
                   1262:     my ($request,$symb) = @_;
                   1263:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1264:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1265:     my $crstype = &Apache::loncommon::course_type();
                   1266:     my ($launcher,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
                   1267:     if ($env{'form.passback'} ne '') {
                   1268:         $chosen = &unescape($env{'form.passback'});
                   1269:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1270:         ($launcher,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
                   1271:     }
                   1272:     if ($launcher ne '') {
                   1273:         $request->print(&launcher_info_box($launcher,$appname,$setter,$linkuri,$scope));
                   1274:     }
                   1275:     my $error;
                   1276:     if ($perm{'mgr'}) {
                   1277:         if ($launcher ne '') {
                   1278:             my @poss_students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   1279:             if (@poss_students) {
                   1280:                 my %possibles;
                   1281:                 foreach my $item (@poss_students) {
                   1282:                     my ($stuname,$studom) = split(/:/,$item,3);
                   1283:                     $possibles{$stuname.':'.$studom} = 1;
                   1284:                 }
                   1285:                 my ($sections,$groups,$group_display,$disabled) = &sections_and_groups();
                   1286:                 my ($classlist,undef,$fullname,$pbinfo) =
                   1287:                     &getclasslist($sections,'1',$groups,'','','',$chosen,\%possibles);
                   1288:                 if ((ref($classlist) eq 'HASH') && (ref($pbinfo) eq 'HASH')) {
                   1289:                     my %passback = %{$pbinfo};
                   1290:                     my (%tosend,%remotenotok,%scorenotok,%zeroposs,%nopbinfo);
                   1291:                     foreach my $possible (keys(%possibles)) {
                   1292:                         if ((exists($classlist->{$possible})) &&
                   1293:                             (exists($passback{$possible})) && (ref($passback{$possible}) eq 'ARRAY')) {
                   1294:                             $tosend{$possible} = 1;
                   1295:                         }
                   1296:                     }
                   1297:                     if (keys(%tosend)) {
                   1298:                         my ($lti_in_use,$crsdef);
                   1299:                         my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
                   1300:                         if ($ltitype eq 'c') {
                   1301:                             my %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1302:                             $lti_in_use = $crslti{$ltinum};
                   1303:                             $crsdef = 1;
                   1304:                         } else {
                   1305:                             my %domlti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1306:                             $lti_in_use = $domlti{$ltinum};
                   1307:                         }
                   1308:                         if (ref($lti_in_use) eq 'HASH') {
                   1309:                             my $msgformat = $lti_in_use->{'passbackformat'};
                   1310:                             my $keynum = $lti_in_use->{'cipher'};
                   1311:                             my $scoretype = 'decimal';
                   1312:                             if ($lti_in_use->{'scoreformat'} =~ /^(decimal|ratio|percentage)$/) {
                   1313:                                 $scoretype = $1;
                   1314:                             }
                   1315:                             my $pbsymb = &Apache::loncommon::symb_from_tinyurl($linkuri,$cnum,$cdom);
                   1316:                             my $pbmap;
                   1317:                             if ($pbsymb =~ /\.(page|sequence)$/) {
                   1318:                                 $pbmap = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pbsymb))[2]);
                   1319:                             } else {
                   1320:                                 $pbmap = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pbsymb))[0]);
                   1321:                             }
                   1322:                             $pbmap = &Apache::lonnet::clutter($pbmap);
                   1323:                             my $pbscope;
                   1324:                             if ($scope eq 'res') {
                   1325:                                 $pbscope = 'resource';
                   1326:                             } elsif ($scope eq 'map') {
                   1327:                                 $pbscope = 'nonrec';
                   1328:                             } elsif ($scope eq 'rec') {
                   1329:                                 $pbscope = 'map';
                   1330:                             }
1.798     raeburn  1331:                             my %pb = &common_passback_info();
1.796     raeburn  1332:                             my $numstudents = scalar(keys(%tosend));
                   1333:                             my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($request,$numstudents);
                   1334:                             my $outcome = &Apache::loncommon::start_data_table().
                   1335:                                          &Apache::loncommon::start_data_table_header_row();
                   1336:                             my $loop = 0;
                   1337:                             while ($loop < 2) {
                   1338:                                 $outcome .= '<th>'.&mt('No.').'</th>'.
                   1339:                                            '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>'.
                   1340:                                            '<th>'.&mt('Score').'</th>';
                   1341:                                  $loop++;
                   1342:                             }
                   1343:                             $outcome .= &Apache::loncommon::end_data_table_header_row()."\n";
                   1344:                             my $ctr=0;
                   1345:                             foreach my $student (sort
                   1346:                                 {
                   1347:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1348:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1349:                                      }
                   1350:                                      return $a cmp $b;
                   1351:                                 } (keys(%$fullname))) {
                   1352:                                 next unless ($tosend{$student});
                   1353:                                 my ($uname,$udom) = split(/:/,$student);
                   1354:                                 &Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last student');
                   1355:                                 my ($uname,$udom) = split(/:/,$student);
                   1356:                                 my $uhome = &Apache::lonnet::homeserver($uname,$udom),
                   1357:                                 my $id = $passback{$student}[0],
                   1358:                                 my $url = $passback{$student}[1],
                   1359:                                 my ($total,$possible,$usec);
                   1360:                                 if (ref($classlist->{$student}) eq 'ARRAY') {
                   1361:                                     $usec = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION];
                   1362:                                 }
                   1363:                                 if ($pbscope eq 'resource') {
                   1364:                                     $total = 0;
                   1365:                                     $possible = 0;
                   1366:                                     my $navmap = Apache::lonnavmaps::navmap->new($uname,$udom);
                   1367:                                     if (ref($navmap)) {
                   1368:                                         my $res = $navmap->getBySymb($pbsymb);
                   1369:                                         if (ref($res)) {
                   1370:                                             my $partlist = $res->parts();
                   1371:                                             if (ref($partlist) eq 'ARRAY') {
                   1372:                                                 my %record = &Apache::lonnet::restore($pbsymb,$env{'request.course.id'},$udom,$uname);
                   1373:                                                 foreach my $part (@{$partlist}) {
                   1374:                                                     next if ($record{"resource.$part.solved"} =~/^excused/);
                   1375:                                                     my $weight = &Apache::lonnet::EXT("resource.$part.weight",$pbsymb,$udom,$uname,$usec);
                   1376:                                                     $possible += $weight;
                   1377:                                                     if (($record{'version'}) && (exists($record{"resource.$part.awarded"}))) {
                   1378:                                                         my $awarded = $record{"resource.$part.awarded"};
                   1379:                                                         if ($awarded) {
                   1380:                                                             $total += $weight * $awarded;
                   1381:                                                         }
                   1382:                                                     }
                   1383:                                                 }
                   1384:                                             }
                   1385:                                         }
                   1386:                                     }
                   1387:                                 } elsif (($pbscope eq 'map') || ($pbscope eq 'nonrec')) {
                   1388:                                     ($total,$possible) =
                   1389:                                         &Apache::lonhomework::get_lti_score($uname,$udom,$pbmap,$pbscope);
                   1390:                                 }
                   1391:                                 if (($id ne '') && ($url ne '') && ($possible)) {
                   1392:                                     my ($sent,$score,$code,$result) =
1.798     raeburn  1393:                                         &LONCAPA::ltiutils::send_grade($cdom,$cnum,$crsdef,$pb{'type'},$ltinum,$keynum,$id,
                   1394:                                                                        $url,$scoretype,$pb{'sigmethod'},$msgformat,$total,$possible);
1.796     raeburn  1395:                                     my $no_passback;
                   1396:                                     if ($sent) {
                   1397:                                         if ($code == 200) {
                   1398:                                             delete($tosend{$student});
                   1399:                                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
                   1400:                                             my $store = {
                   1401:                                                  'score' => $score,
1.798     raeburn  1402:                                                  'ip' => $pb{'ip'},
                   1403:                                                  'host' => $pb{'lonhost'},
1.796     raeburn  1404:                                                  'protector' => $linkprotector,
                   1405:                                                  'deeplink' => $linkuri,
                   1406:                                                  'scope' => $scope,
                   1407:                                                  'url' => $url,
                   1408:                                                  'id' => $id,
1.798     raeburn  1409:                                                  'clientip' => $pb{'clientip'},
1.796     raeburn  1410:                                                  'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
                   1411:                                                 };
                   1412:                                             my $value='';
                   1413:                                             foreach my $key (keys(%{$store})) {
                   1414:                                                 $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
                   1415:                                             }
                   1416:                                             $value=~s/\&$//;
                   1417:                                             &Apache::lonnet::courselog(&escape($linkuri).':'.$uname.':'.$udom.':EXPORT:'.$value);
1.798     raeburn  1418:                                             &Apache::lonnet::cstore({'score' => $score},$chosen,$namespace,$udom,$uname,'',$pb{'ip'},1);
1.796     raeburn  1419:                                             $ctr++;
                   1420:                                             if ($ctr%2 ==1) {
                   1421:                                                 $outcome .= &Apache::loncommon::start_data_table_row();
                   1422:                                             }
                   1423:                                             my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                   1424:                                             my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
                   1425:                                             $outcome .= '<td align="right">'.$ctr.'&nbsp;</td>'.
                   1426:                                                        '<td>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).
                   1427:                                                        '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'.
                   1428:                                                        '<td>'.$score.'</td>'."\n";
                   1429:                                             if ($ctr%2 ==0) {
                   1430:                                                 $outcome .= &Apache::loncommon::end_data_table_row()."\n";
                   1431:                                             }
                   1432:                                         } else {
                   1433:                                             $remotenotok{$student} = 1;
                   1434:                                             $no_passback = "Passback response for ".$linkprotector." was $code ($result)";
                   1435:                                             &Apache::lonnet::logthis($no_passback." for $uname:$udom in ${cdom}_${cnum}");
                   1436:                                         }
                   1437:                                     } else {
                   1438:                                         $scorenotok{$student} = 1;
                   1439:                                         $no_passback = "Passback of grades not sent for ".$linkprotector;
                   1440:                                         &Apache::lonnet::logthis($no_passback." for $uname:$udom in ${cdom}_${cnum}");
                   1441:                                     }
                   1442:                                     if ($no_passback) {
                   1443:                                         &Apache::lonnet::log($udom,$uname,$uhome,$no_passback." score: $score; total: $total; possible: $possible");
                   1444:                                         my $ltigrade = {
                   1445:                                             'ltinum'   => $ltinum,
                   1446:                                             'lti'      => $lti_in_use,
                   1447:                                             'crsdef'   => $crsdef,
                   1448:                                             'cid'      => $cdom.'_'.$cnum,
                   1449:                                             'uname'    => $uname,
                   1450:                                             'udom'     => $udom,
                   1451:                                             'uhome'    => $uhome,
                   1452:                                             'pbid'     => $id,
                   1453:                                             'pburl'    => $url,
1.798     raeburn  1454:                                             'pbtype'   => $pb{'type'},
1.796     raeburn  1455:                                             'pbscope'  => $pbscope,
                   1456:                                             'pbmap'    => $pbmap,
                   1457:                                             'pbsymb'   => $pbsymb,
                   1458:                                             'format'   => $scoretype,
                   1459:                                             'scope'    => $scope,
1.798     raeburn  1460:                                             'clientip' => $pb{'clientip'},
1.799     raeburn  1461:                                             'linkprot' => $linkprotector.':'.$linkuri,
1.796     raeburn  1462:                                             'total'    => $total,
                   1463:                                             'possible' => $possible,
                   1464:                                             'score'    => $score,
                   1465:                                         };
                   1466:                                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1467:                                     }
                   1468:                                 } else {
                   1469:                                     if (($id ne '') && ($url ne '')) {
                   1470:                                         $zeroposs{$student} = 1;
                   1471:                                     } else {
                   1472:                                         $nopbinfo{$student} = 1;
                   1473:                                     }
                   1474:                                 }
                   1475:                             }
                   1476:                             &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
                   1477:                             if ($ctr%2 ==1) {
                   1478:                                 $outcome .= &Apache::loncommon::end_data_table_row();
                   1479:                             }
                   1480:                             $outcome .= &Apache::loncommon::end_data_table();
                   1481:                             if ($ctr) {
                   1482:                                 $request->print('<p><br />'.&mt('Scores sent to launcher CMS').'</p>'.
                   1483:                                                 '<p>'.$outcome.'</p>');
                   1484:                             } else {
                   1485:                                 $request->print('<p>'.&mt('No scores sent to launcher CMS').'</p>');
                   1486:                             }
                   1487:                             if (keys(%tosend)) {
                   1488:                                 $request->print('<p>'.&mt('No scores sent for following'));
                   1489:                                 my ($zeros,$nopbcreds,$noconfirm,$noscore);
                   1490:                                 foreach my $student (sort
                   1491:                                 {
                   1492:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1493:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1494:                                      }
                   1495:                                      return $a cmp $b;
                   1496:                                 } (keys(%$fullname))) {
                   1497:                                     next unless ($tosend{$student});
                   1498:                                     my ($uname,$udom) = split(/:/,$student);
                   1499:                                     my $line = '<li>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).'</li>'."\n";
                   1500:                                     if ($zeroposs{$student}) {
                   1501:                                         $zeros .= $line;
                   1502:                                     } elsif ($nopbinfo{$student}) {
                   1503:                                         $nopbcreds .= $line;
                   1504:                                     } elsif ($remotenotok{$student}) {
                   1505:                                         $noconfirm .= $line;
                   1506:                                     } elsif ($scorenotok{$student}) {
                   1507:                                         $noscore .= $line;
                   1508:                                     }
                   1509:                                 }
                   1510:                                 if ($zeros) {
                   1511:                                     $request->print('<br />'.&mt('Total points possible was 0').':'.
                   1512:                                                     '<ul>'.$zeros.'</ul><br />');
                   1513:                                 }
                   1514:                                 if ($nopbcreds) {
                   1515:                                     $request->print('<br />'.&mt('Missing unique identifier and/or passback location').':'.
                   1516:                                                     '<ul>'.$nopbcreds.'</ul><br />');
                   1517:                                 }
                   1518:                                 if ($noconfirm) {
                   1519:                                     $request->print('<br />'.&mt('Score receipt not confirmed by receiving CMS').':'.
                   1520:                                                     '<ul>'.$noconfirm.'</ul><br />');
                   1521:                                 }
                   1522:                                 if ($noscore) {
                   1523:                                     $request->print('<br />'.&mt('Score computation or transmission failed').':'.
                   1524:                                                     '<ul>'.$noscore.'</ul><br />');
                   1525:                                 }
                   1526:                                 $request->print('</p>');
                   1527:                             }
                   1528:                         } else {
                   1529:                             $error = &mt('Settings for deep-link launch target unavailable, so no scores were sent');
                   1530:                         }
                   1531:                     } else {
                   1532:                         $error = &mt('No available students for whom scores can be sent.');
                   1533:                     }
                   1534:                 } else {
                   1535:                     $error = &mt('Classlist could not be retrieved so no scores were sent.');
                   1536:                 }
                   1537:             } else {
                   1538:                 $error = &mt('No students selected to receive scores so none were sent.');
                   1539:             }
                   1540:         } else {
                   1541:             if ($env{'form.passback'}) {
                   1542:                 $error = &mt('Deep-link launch target was invalid so no scores were sent.');
                   1543:             } else {
                   1544:                 $error = &mt('Deep-link launch target was missing so no scores were sent.');
                   1545:             }
                   1546:         }
                   1547:     } else {
                   1548:         $error = &mt('You do not have permission to manage grades, so no scores were sent');
                   1549:     }
                   1550:     if ($error) {
                   1551:         $request->print('<p class="LC_info">'.$error.'</p>');
                   1552:     }
                   1553:     return;
                   1554: }
                   1555: 
                   1556: sub get_passback_launcher {
                   1557:     my ($cdom,$cnum,$chosen) = @_;
                   1558:     my ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1559:     my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
                   1560:     my ($appname,$setter);
                   1561:     if ($ltitype eq 'c') {
                   1562:         my %lti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1563:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1564:             $appname = $lti{$ltinum}{'name'};
                   1565:             if ($appname) {
                   1566:                 $setter = ' (defined in course)';
                   1567:             }
                   1568:         }
                   1569:     } elsif ($ltitype eq 'd') {
                   1570:         my %lti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1571:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1572:             $appname = $lti{$ltinum}{'name'};
                   1573:             if ($appname) {
                   1574:                 $setter = ' (defined in domain)';
                   1575:             }
                   1576:         }
                   1577:     }
                   1578:     if ($linkuri =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   1579:         my $key = $1;
                   1580:         my $tinyurl;
                   1581:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   1582:         if (defined($cached)) {
                   1583:             $tinyurl = $result;
                   1584:         } else {
                   1585:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   1586:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   1587:             if ($currtiny{$key} ne '') {
                   1588:                 $tinyurl = $currtiny{$key};
                   1589:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   1590:             }
                   1591:         }
                   1592:         if ($tinyurl) {
                   1593:             my ($crsnum,$launchsymb) = split(/\&/,$tinyurl);
                   1594:             if ($crsnum eq $cnum) {
                   1595:                 my %passback = &Apache::lonnet::get('nohist_linkprot_passback',[$launchsymb],$cdom,$cnum);
                   1596:                 if (ref($passback{$launchsymb}) eq 'HASH') {
                   1597:                     if (exists($passback{$launchsymb}{$chosen})) {
1.798     raeburn  1598:                         return ($launchsymb,$appname,$setter);
1.796     raeburn  1599:                     }
                   1600:                 }
                   1601:             }
                   1602:         }
                   1603:     }
                   1604:     return ();
                   1605: }
                   1606: 
                   1607: sub sections_and_groups {
                   1608:     my (@sections,@groups,$group_display);
                   1609:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   1610:     if (grep(/^all$/,@groups)) {
                   1611:          @groups = ('all');
                   1612:          $group_display = 'all';
                   1613:     } elsif (grep(/^none$/,@groups)) {
                   1614:          @groups = ('none');
                   1615:          $group_display = 'none';
                   1616:     } elsif (@groups > 0) {
                   1617:          $group_display = join(', ',@groups);
                   1618:     }
                   1619:     if ($env{'request.course.sec'} ne '') {
                   1620:         @sections = ($env{'request.course.sec'});
                   1621:     } else {
                   1622:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1623:     }
                   1624:     my $disabled = ' disabled="disabled"';
                   1625:     if ($perm{'mgr'}) {
                   1626:         if (grep(/^all$/,@sections)) {
                   1627:             undef($disabled);
                   1628:         } else {
                   1629:             foreach my $sec (@sections) {
                   1630:                 if (&canmodify($sec)) {
                   1631:                     undef($disabled);
                   1632:                     last;
                   1633:                 }
                   1634:             }
                   1635:         }
                   1636:     }
                   1637:     if (grep(/^all$/,@sections)) {
                   1638:         @sections = ('all');
                   1639:     }
                   1640:     return(\@sections,\@groups,$group_display,$disabled);
                   1641: }
                   1642: 
                   1643: sub launcher_info_box {
                   1644:     my ($launcher,$appname,$setter,$linkuri,$scope) = @_;
                   1645:     my $shownscope;
                   1646:     if ($scope eq 'res') {
                   1647:         $shownscope = &mt('Resource');
                   1648:     } elsif ($scope eq 'map') {
                   1649:         $shownscope = &mt('Folder');
                   1650:     }  elsif ($scope eq 'rec') {
                   1651:         $shownscope = &mt('Folder + sub-folders');
                   1652:     }
                   1653:     return '<p>'.
                   1654:            &Apache::lonhtmlcommon::start_pick_box().
                   1655:            &Apache::lonhtmlcommon::row_title(&mt('Launch Item Title')).
1.797     raeburn  1656:            &Apache::lonnet::gettitle($launcher).
1.796     raeburn  1657:            &Apache::lonhtmlcommon::row_closure().
                   1658:            &Apache::lonhtmlcommon::row_title(&mt('Deep-link')).
                   1659:            $linkuri.
                   1660:            &Apache::lonhtmlcommon::row_closure().
                   1661:            &Apache::lonhtmlcommon::row_title(&mt('Launcher')).
                   1662:            $appname.' '.$setter.
                   1663:            &Apache::lonhtmlcommon::row_closure().
                   1664:            &Apache::lonhtmlcommon::row_title(&mt('Score Type')).
                   1665:            $shownscope.      
                   1666:            &Apache::lonhtmlcommon::row_closure(1).
                   1667:            &Apache::lonhtmlcommon::end_pick_box().'</p>'."\n";
                   1668: }
                   1669: 
1.798     raeburn  1670: sub passbacks_for_symb {
                   1671:     my ($cdom,$cnum,$symb) = @_;
                   1672:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   1673:     my %needpb;
                   1674:     if (keys(%passback)) {
                   1675:         my $checkpb = 1;
                   1676:         if (exists($passback{$symb})) {
                   1677:             if (keys(%passback) == 1) {
                   1678:                 undef($checkpb);
                   1679:             }
                   1680:             if (ref($passback{$symb}) eq 'HASH') {
                   1681:                 foreach my $launcher (keys(%{$passback{$symb}})) {
                   1682:                     $needpb{$launcher} = 1;
                   1683:                 }
                   1684:             }
                   1685:         }
                   1686:         if ($checkpb) {
                   1687:             my ($map,$id,$url) = &Apache::lonnet::decode_symb($symb);
                   1688:             my $navmap = Apache::lonnavmaps::navmap->new();
                   1689:             if (ref($navmap)) {
                   1690:                 my $mapres = $navmap->getResourceByUrl($map);
                   1691:                 if (ref($mapres)) {
                   1692:                     my $mapsymb = $mapres->symb();
                   1693:                     if (exists($passback{$mapsymb})) {
                   1694:                         if (keys(%passback) == 1) {
                   1695:                             undef($checkpb);
                   1696:                         }
                   1697:                         if (ref($passback{$mapsymb}) eq 'HASH') {
                   1698:                             foreach my $launcher (keys(%{$passback{$mapsymb}})) {
                   1699:                                 $needpb{$launcher} = 1;
                   1700:                             }
                   1701:                         }
                   1702:                     }
                   1703:                     my %posspb;
                   1704:                     if ($checkpb) {
                   1705:                         my @recurseup = $navmap->recurseup_maps($map,1);
                   1706:                         if (@recurseup) {
                   1707:                             map { $posspb{$_} = 1; } @recurseup;
                   1708:                         }
                   1709:                     }
                   1710:                     foreach my $key (keys(%passback)) {
                   1711:                         if (exists($posspb{$key})) {
                   1712:                             if (ref($passback{$key}) eq 'HASH') {
                   1713:                                 foreach my $launcher (keys(%{$passback{$key}})) {
                   1714:                                     my ($linkuri,$linkprotector,$scope) = split("\0",$launcher);
                   1715:                                     next unless ($scope eq 'rec');
                   1716:                                     $needpb{$launcher} = 1;
                   1717:                                 }
                   1718:                             }
                   1719:                         }
                   1720:                     }
                   1721:                 }
                   1722:             }
                   1723:         }
                   1724:     }
                   1725:     return %needpb;
                   1726: }
                   1727: 
                   1728: sub process_passbacks {
1.802     raeburn  1729:     my ($context,$symbs,$cdom,$cnum,$udom,$uname,$usec,$weights,$awardeds,$excuseds,$needpb,
1.798     raeburn  1730:         $skip_passback,$pbsave,$pbids) = @_;
                   1731:     if ((ref($needpb) eq 'HASH') && (ref($skip_passback) eq 'HASH') && (ref($pbsave) eq 'HASH')) {
                   1732:         my (%weight,%awarded,%excused);
                   1733:         if ((ref($symbs) eq 'ARRAY') && (ref($weights) eq 'HASH') && (ref($awardeds) eq 'HASH') &&
                   1734:             (ref($excuseds) eq 'HASH')) {
                   1735:             %weight = %{$weights};
                   1736:             %awarded = %{$awardeds};
                   1737:             %excused = %{$excuseds};
                   1738:         }
                   1739:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
                   1740:         my @launchers = keys(%{$needpb});
                   1741:         my %pbinfo;
                   1742:         if (ref($pbids) eq 'HASH') {
                   1743:             %pbinfo = %{$pbids};
                   1744:         } else {
                   1745:             %pbinfo = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@launchers,$udom,$uname);
                   1746:         }
                   1747:         my %pbc = &common_passback_info();
                   1748:         foreach my $launcher (@launchers) {
                   1749:             if (ref($pbinfo{$launcher}) eq 'ARRAY') {
                   1750:                 my $pbid = $pbinfo{$launcher}[0];
                   1751:                 my $pburl = $pbinfo{$launcher}[1];
                   1752:                 my (%total_by_symb,%possible_by_symb);
                   1753:                 if (($pbid ne '') && ($pburl ne '')) {
                   1754:                     next if ($skip_passback->{$launcher});
                   1755:                     my %pb = %pbc;
                   1756:                     if ((exists($pbsave->{$launcher})) &&
                   1757:                         (ref($pbsave->{$launcher}) eq 'HASH')) {
                   1758:                         foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
                   1759:                                           'symb','map','pbscope','linkuri','linkprotector','scope') {
                   1760:                             $pb{$item} = $pbsave->{$launcher}{$item};
                   1761:                         }
                   1762:                     } else {
                   1763:                         my $ltitype;
                   1764:                         ($pb{'linkuri'},$pb{'linkprotector'},$pb{'scope'}) = split("\0",$launcher);
                   1765:                         ($pb{'ltinum'},$ltitype) = ($pb{'linkprotector'} =~ /^(\d+)(c|d)$/);
                   1766:                         if ($ltitype eq 'c') {
                   1767:                             my %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1768:                             $pb{'lti_in_use'} = $crslti{$pb{'ltinum'}};
                   1769:                             $pb{'crsdef'} = 1;
                   1770:                         } else {
                   1771:                             my %domlti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1772:                             $pb{'lti_in_use'} = $domlti{$pb{'ltinum'}};
                   1773:                         }
                   1774:                         if (ref($pb{'lti_in_use'}) eq 'HASH') {
                   1775:                             $pb{'msgformat'} = $pb{'lti_in_use'}->{'passbackformat'};
                   1776:                             $pb{'keynum'} = $pb{'lti_in_use'}->{'cipher'};
                   1777:                             $pb{'scoretype'} = 'decimal';
                   1778:                             if ($pb{'lti_in_use'}->{'scoreformat'} =~ /^(decimal|ratio|percentage)$/) {
                   1779:                                 $pb{'scoretype'} = $1;
                   1780:                             }
                   1781:                             $pb{'symb'} = &Apache::loncommon::symb_from_tinyurl($pb{'linkuri'},$cnum,$cdom);
                   1782:                             if ($pb{'symb'} =~ /\.(page|sequence)$/) {
                   1783:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[2]);
                   1784:                             } else {
                   1785:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[0]);
                   1786:                             }
                   1787:                             $pb{'map'} = &Apache::lonnet::clutter($pb{'map'});
                   1788:                             if ($pb{'scope'} eq 'res') {
                   1789:                                 $pb{'pbscope'} = 'resource';
                   1790:                             } elsif ($pb{'scope'} eq 'map') {
                   1791:                                 $pb{'pbscope'} = 'nonrec';
                   1792:                             } elsif ($pb{'scope'} eq 'rec') {
                   1793:                                 $pb{'pbscope'} = 'map';
                   1794:                             }
                   1795:                             foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
                   1796:                                               'symb','map','pbscope','linkuri','linkprotector','scope') {
                   1797:                                 $pbsave->{$launcher}{$item} = $pb{$item};
                   1798:                             }
                   1799:                         } else {
                   1800:                             $skip_passback->{$launcher} = 1;
                   1801:                         }
                   1802:                     }
                   1803:                     if (ref($symbs) eq 'ARRAY') {
                   1804:                         foreach my $symb (@{$symbs}) {
                   1805:                             if ((ref($weight{$symb}) eq 'HASH') && (ref($awarded{$symb}) eq 'HASH') &&
                   1806:                                 (ref($excused{$symb}) eq 'HASH')) {
                   1807:                                 foreach my $part (keys(%{$weight{$symb}})) {
                   1808:                                     if ($excused{$symb}{$part}) {
                   1809:                                         next;
                   1810:                                     }
                   1811:                                     my $partweight = $weight{$symb}{$part} eq '' ? 1 :
                   1812:                                                      $weight{$symb}{$part};
                   1813:                                     if ($awarded{$symb}{$part}) {
                   1814:                                         $total_by_symb{$symb} += $partweight * $awarded{$symb}{$part};
                   1815:                                     }
                   1816:                                     $possible_by_symb{$symb} += $partweight;
                   1817:                                 }
                   1818:                             }
                   1819:                         }
                   1820:                     }
                   1821:                     if ($context eq 'updatebypage') {
                   1822:                         my $ltigrade = {
                   1823:                                         'ltinum'     => $pb{'ltinum'},
                   1824:                                         'lti'        => $pb{'lti_in_use'},
                   1825:                                         'crsdef'     => $pb{'crsdef'},
                   1826:                                         'cid'        => $cdom.'_'.$cnum,
                   1827:                                         'uname'      => $uname,
                   1828:                                         'udom'       => $udom,
                   1829:                                         'uhome'      => $uhome,
1.802     raeburn  1830:                                         'usec'       => $usec,
1.798     raeburn  1831:                                         'pbid'       => $pbid,
                   1832:                                         'pburl'      => $pburl,
                   1833:                                         'pbtype'     => $pb{'type'},
                   1834:                                         'pbscope'    => $pb{'pbscope'},
                   1835:                                         'pbmap'      => $pb{'map'},
                   1836:                                         'pbsymb'     => $pb{'symb'},
                   1837:                                         'format'     => $pb{'scoretype'},
                   1838:                                         'scope'      => $pb{'scope'},
                   1839:                                         'clientip'   => $pb{'clientip'},
1.799     raeburn  1840:                                         'linkprot'   => $pb{'linkprotector'}.':'.$pb{'linkuri'},
1.798     raeburn  1841:                                         'total_s'    => \%total_by_symb,
                   1842:                                         'possible_s' => \%possible_by_symb,
                   1843:                         };
1.801     raeburn  1844:                         push(@Apache::grades::ltipassback,$ltigrade);
1.798     raeburn  1845:                         next;
                   1846:                     }
                   1847:                     my ($total,$possible);
                   1848:                     if ($pb{'pbscope'} eq 'resource') {
                   1849:                         $total = $total_by_symb{$pb{'symb'}};
                   1850:                         $possible = $possible_by_symb{$pb{'symb'}};
                   1851:                     } elsif (($pb{'pbscope'} eq 'map') || ($pb{'pbscope'} eq 'nonrec')) {
                   1852:                         ($total,$possible) =
                   1853:                             &Apache::lonhomework::get_lti_score($uname,$udom,$pb{'map'},$pb{'pbscope'},
                   1854:                                                                 \%total_by_symb,\%possible_by_symb);
                   1855:                     }
                   1856:                     if (!$possible) {
                   1857:                         $total = 0;
                   1858:                         $possible = 1;
                   1859:                     }
                   1860:                     my ($sent,$score,$code,$result) =
                   1861:                         &LONCAPA::ltiutils::send_grade($cdom,$cnum,$pb{'crsdef'},$pb{'type'},$pb{'ltinum'},
                   1862:                                                        $pb{'keynum'},$pbid,$pburl,$pb{'scoretype'},$pb{'sigmethod'},
                   1863:                                                        $pb{'msgformat'},$total,$possible);
                   1864:                     my $no_passback;
                   1865:                     if ($sent) {
                   1866:                         if ($code == 200) {
                   1867:                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
                   1868:                             my $store = {
                   1869:                                 'score' => $score,
                   1870:                                 'ip' => $pb{'ip'},
                   1871:                                 'host' => $pb{'lonhost'},
                   1872:                                 'protector' => $pb{'linkprotector'},
                   1873:                                 'deeplink' => $pb{'linkuri'},
                   1874:                                 'scope' => $pb{'scope'},
                   1875:                                 'url' => $pburl,
                   1876:                                 'id' => $pbid,
                   1877:                                 'clientip' => $pb{'clientip'},
                   1878:                                 'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
                   1879:                             };
                   1880:                             my $value='';
                   1881:                             foreach my $key (keys(%{$store})) {
                   1882:                                  $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
                   1883:                             }
                   1884:                             $value=~s/\&$//;
                   1885:                             &Apache::lonnet::courselog(&escape($pb{'linkuri'}).':'.$uname.':'.$udom.':EXPORT:'.$value);
                   1886:                             &Apache::lonnet::cstore({'score' => $score},$launcher,$namespace,$udom,$uname,'',$pb{'ip'},1);
                   1887:                         } else {
                   1888:                             $no_passback = 1;
                   1889:                         }
                   1890:                     } else {
                   1891:                         $no_passback = 1;
                   1892:                     }
                   1893:                     if ($no_passback) {
                   1894:                         &Apache::lonnet::log($udom,$uname,$uhome,$no_passback." score: $score; total: $total; possible: $possible");
                   1895:                         my $ltigrade = {
                   1896:                            'ltinum'   => $pb{'ltinum'},
                   1897:                            'lti'      => $pb{'lti_in_use'},
                   1898:                            'crsdef'   => $pb{'crsdef'},
                   1899:                            'cid'      => $cdom.'_'.$cnum,
                   1900:                            'uname'    => $uname,
                   1901:                            'udom'     => $udom,
                   1902:                            'uhome'    => $uhome,
                   1903:                            'pbid'     => $pbid,
                   1904:                            'pburl'    => $pburl,
                   1905:                            'pbtype'   => $pb{'type'},
                   1906:                            'pbscope'  => $pb{'pbscope'},
                   1907:                            'pbmap'    => $pb{'map'},
                   1908:                            'pbsymb'   => $pb{'symb'},
                   1909:                            'format'   => $pb{'scoretype'},
                   1910:                            'scope'    => $pb{'scope'},
                   1911:                            'clientip' => $pb{'clientip'},
1.799     raeburn  1912:                            'linkprot' => $pb{'linkprotector'}.':'.$pb{'linkuri'},
1.798     raeburn  1913:                            'total'    => $total,
                   1914:                            'possible' => $possible,
                   1915:                            'score'    => $score,
                   1916:                         };
                   1917:                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1918:                     }
                   1919:                 }
                   1920:             }
                   1921:         }
                   1922:     }
                   1923:     return;
                   1924: }
                   1925: 
                   1926: sub common_passback_info {
                   1927:     my %pbc = (
                   1928:                sigmethod => 'HMAC-SHA1',
                   1929:                type      => 'linkprot',
                   1930:                clientip  => &Apache::lonnet::get_requestor_ip(),
                   1931:                lonhost   => $Apache::lonnet::perlvar{'lonHostID'},
                   1932:                ip        => &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}),
                   1933:              );
                   1934:     return %pbc;
                   1935: }
                   1936: 
1.44      ng       1937: #--- This is called by a number of programs.
                   1938: #--- Called from the Grading Menu - View/Grade an individual student
                   1939: #--- Also called directly when one clicks on the subm button 
                   1940: #    on the problem page.
1.30      ng       1941: sub listStudents {
1.773     raeburn  1942:     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1943: 
1.747     raeburn  1944:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1945:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1946:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1947:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1948:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www      1949:     unless ($submitonly) {
1.766     raeburn  1950:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www      1951:     }
1.49      albertel 1952: 
1.632     www      1953:     my $result='';
1.623     www      1954:     my $res_error;
1.773     raeburn  1955:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   1956: 
                   1957:     my $table;
                   1958:     if (ref($partlist) eq 'ARRAY') {
                   1959:         if (scalar(@$partlist) > 1 ) {
                   1960:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1961:         } elsif ($divforres) {
                   1962:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1963:         } else {
                   1964:             $table = '<br clear="all" />';
                   1965:         }
                   1966:     }
1.49      albertel 1967: 
1.796     raeburn  1968:     $request->print(&checkselect_js());
1.597     wenzelju 1969:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1970: 
                   1971:     function reLoadList(formname) {
1.112     ng       1972: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1973: 	formname.command.value = 'submission';
                   1974: 	formname.submit();
                   1975:     }
1.45      ng       1976: LISTJAVASCRIPT
                   1977: 
1.118     ng       1978:     &commonJSfunctions($request);
1.41      ng       1979:     $request->print($result);
1.39      ng       1980: 
1.154     albertel 1981:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.773     raeburn  1982: 	"\n".$table;
                   1983: 
1.561     bisitz   1984:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn  1985:     unless ($is_tool) {
                   1986:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1987:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1988:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1989:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1990:                       .&Apache::lonhtmlcommon::row_closure();
                   1991:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1992:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1993:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1994:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1995:                       .&Apache::lonhtmlcommon::row_closure();
                   1996:     }
1.485     albertel 1997: 
1.442     banghart 1998:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1999:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 2000:     $env{'form.Status'} = $saveStatus;
1.745     raeburn  2001:     my %optiontext;
                   2002:     if ($is_tool) {
                   2003:         %optiontext = &Apache::lonlocal::texthash (
                   2004:                           lastonly => 'last transaction',
                   2005:                           last     => 'last transaction with details',
                   2006:                           datesub  => 'all transactions',
                   2007:                           all      => 'all transactions with details',
                   2008:                       );
                   2009:     } else {
                   2010:         %optiontext = &Apache::lonlocal::texthash (
                   2011:                           lastonly => 'last submission',
                   2012:                           last     => 'last submission with details',
                   2013:                           datesub  => 'all submissions',
                   2014:                           all      => 'all submissions with details',
                   2015:                       );
                   2016:     }
1.773     raeburn  2017:     my $submission_options =
1.592     bisitz   2018:         '<span class="LC_nobreak">'.
1.624     www      2019:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  2020:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   2021:         '<span class="LC_nobreak">'.
                   2022:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  2023:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   2024:         '<span class="LC_nobreak">'.
1.628     www      2025:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  2026:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   2027:         '<span class="LC_nobreak">'.
                   2028:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  2029:         $optiontext{'all'}.'</label></span>';
                   2030:     my $viewtitle;
                   2031:     if ($is_tool) {
                   2032:         $viewtitle = &mt('View Transactions');
                   2033:     } else {
                   2034:         $viewtitle = &mt('View Submissions');
                   2035:     }
1.773     raeburn  2036:     my ($compmsg,$nocompmsg);
                   2037:     $nocompmsg = ' checked="checked"';
                   2038:     if ($numessay) {
                   2039:         $compmsg = $nocompmsg;
                   2040:         $nocompmsg = '';
                   2041:     }
1.745     raeburn  2042:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.780     raeburn  2043:                   .$submission_options;
                   2044: # Check if any gradable
                   2045:     my $showmore;
                   2046:     if ($perm{'mgr'}) {
                   2047:         my @sections;
                   2048:         if ($env{'request.course.sec'} ne '') {
                   2049:             @sections = ($env{'request.course.sec'});
1.783     raeburn  2050:         } elsif ($env{'form.section'} eq '') {
                   2051:             @sections = ('all');
1.780     raeburn  2052:         } else {
                   2053:             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   2054:         }
                   2055:         if (grep(/^all$/,@sections)) {
                   2056:             $showmore = 1;
                   2057:         } else {
                   2058:             foreach my $sec (@sections) {
                   2059:                 if (&canmodify($sec)) {
                   2060:                     $showmore = 1;
                   2061:                     last;
                   2062:                 }
                   2063:             }
                   2064:         }
                   2065:     }
                   2066: 
                   2067:     if ($showmore) {
                   2068:         $gradeTable .=
                   2069:                    &Apache::lonhtmlcommon::row_closure()
1.773     raeburn  2070:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   2071:                   .'<span class="LC_nobreak">'
                   2072:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   2073:                   .&mt('No').('&nbsp;'x2).'</label>'
                   2074:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   2075:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   2076:                   .&Apache::lonhtmlcommon::row_closure();
                   2077: 
1.780     raeburn  2078:         $gradeTable .= 
                   2079:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   2080:                   .'<select name="increment">'
                   2081:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   2082:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   2083:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   2084:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773     raeburn  2085:                   .'</select>';
1.780     raeburn  2086:     }
1.485     albertel 2087:     $gradeTable .= 
1.432     banghart 2088:         &build_section_inputs().
1.45      ng       2089: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 2090: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       2091: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      2092:     if (exists($env{'form.Status'})) {
1.784     raeburn  2093: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng       2094:     } else {
1.773     raeburn  2095:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2096:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   2097:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773     raeburn  2098:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       2099:     }
1.773     raeburn  2100:     if ($numessay) {
                   2101:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2102:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   2103:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  2104:     }
1.773     raeburn  2105:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
                   2106:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  2107:     my $regrademsg;
                   2108:     if ($is_tool) {
                   2109:         $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.");
                   2110:     } else {
                   2111:         $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.");
                   2112:     }
1.561     bisitz   2113:     $gradeTable .= '<p>'
1.745     raeburn  2114:                   .$regrademsg."\n"
1.561     bisitz   2115:                   .'<input type="hidden" name="command" value="processGroup" />'
                   2116:                   .'</p>';
1.249     albertel 2117: 
                   2118: # checkall buttons
                   2119:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       2120:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   2121:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   2122:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 2123:     $gradeTable.=&check_buttons();
1.450     banghart 2124:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 2125:     $gradeTable.= &Apache::loncommon::start_data_table().
                   2126: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       2127:     my $loop = 0;
                   2128:     while ($loop < 2) {
1.485     albertel 2129: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   2130: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      2131: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 2132: 	    foreach my $part (sort(@$partlist)) {
                   2133: 		my $display_part=
                   2134: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   2135: 		$gradeTable.=
                   2136: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       2137: 	    }
1.301     albertel 2138: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 2139: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       2140: 	}
                   2141: 	$loop++;
1.126     ng       2142: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       2143:     }
1.474     albertel 2144:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       2145: 
1.45      ng       2146:     my $ctr = 0;
1.294     albertel 2147:     foreach my $student (sort 
                   2148: 			 {
                   2149: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2150: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2151: 			     }
                   2152: 			     return $a cmp $b;
                   2153: 			 }
                   2154: 			 (keys(%$fullname))) {
1.41      ng       2155: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2156: 
1.110     ng       2157: 	my %status = ();
1.301     albertel 2158: 
                   2159: 	if ($submitonly eq 'queued') {
                   2160: 	    my %queue_status = 
                   2161: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2162: 							$udom,$uname);
                   2163: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2164: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   2165: 	}
                   2166: 
1.618     www      2167: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 2168: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2169: 	    my $submitted = 0;
1.164     albertel 2170: 	    my $graded = 0;
1.248     albertel 2171: 	    my $incorrect = 0;
1.110     ng       2172: 	    foreach (keys(%status)) {
1.145     albertel 2173: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2174: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   2175: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   2176: 		
1.110     ng       2177: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2178: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 2179: 		    $submitted = 0;
1.150     albertel 2180: 		    my ($part)=split(/\./,$partid);
1.110     ng       2181: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 2182: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       2183: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   2184: 		}
1.41      ng       2185: 	    }
1.248     albertel 2186: 	    
1.156     albertel 2187: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2188: 				     $submitonly eq 'incorrect' ||
                   2189: 				     $submitonly eq 'graded'));
1.248     albertel 2190: 	    next if (!$graded && ($submitonly eq 'graded'));
                   2191: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2192: 	}
1.34      ng       2193: 
1.45      ng       2194: 	$ctr++;
1.249     albertel 2195: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 2196:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 2197: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 2198: 	    if ($ctr%2 ==1) {
                   2199: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   2200: 	    }
1.126     ng       2201: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   2202:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 2203:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   2204: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   2205: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 2206: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       2207: 
1.618     www      2208: 	    if ($submitonly ne 'all') {
1.524     raeburn  2209: 		foreach (sort(keys(%status))) {
1.485     albertel 2210: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   2211: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       2212: 		}
1.41      ng       2213: 	    }
1.126     ng       2214: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 2215: 	    if ($ctr%2 ==0) {
                   2216: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   2217: 	    }
1.41      ng       2218: 	}
                   2219:     }
1.110     ng       2220:     if ($ctr%2 ==1) {
1.126     ng       2221: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      2222: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       2223: 		foreach (@$partlist) {
                   2224: 		    $gradeTable.='<td>&nbsp;</td>';
                   2225: 		}
1.301     albertel 2226: 	    } elsif ($submitonly eq 'queued') {
                   2227: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       2228: 	    }
1.474     albertel 2229: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       2230:     }
                   2231: 
1.474     albertel 2232:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   2233:         '<input type="button" '.
                   2234:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   2235:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       2236:     if ($ctr == 0) {
1.96      albertel 2237: 	my $num_students=(scalar(keys(%$fullname)));
                   2238: 	if ($num_students eq 0) {
1.485     albertel 2239: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 2240: 	} else {
1.171     albertel 2241: 	    my $submissions='submissions';
                   2242: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   2243: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 2244: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 2245: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   2246: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 2247: 		    $num_students).
                   2248: 		'</span><br />';
1.96      albertel 2249: 	}
1.46      ng       2250:     } elsif ($ctr == 1) {
1.474     albertel 2251: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       2252:     }
                   2253:     $request->print($gradeTable);
1.44      ng       2254:     return '';
1.10      ng       2255: }
                   2256: 
1.796     raeburn  2257: #---- Called from the listStudents and the names_for_passback routines.
                   2258: 
                   2259: sub checkselect_js {
                   2260:     my ($formname) = @_;
                   2261:     if ($formname eq '') {
                   2262:         $formname = 'gradesub';
                   2263:     }
                   2264:     my %js_lt;
                   2265:     if ($formname eq 'passbackusers') {
                   2266:         %js_lt = &Apache::lonlocal::texthash (
                   2267:                      'multiple' => 'Please select a student or group of students before pushing the Save Scores button.',
                   2268:                      'single'   => 'Please select the student before pushing the Save Scores button.',
                   2269:                  );
                   2270:     } else {
                   2271:         %js_lt = &Apache::lonlocal::texthash (
                   2272:                      'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   2273:                      'single'   => 'Please select the student before clicking on the Next button.',
                   2274:                  );
                   2275:     }
                   2276:     &js_escape(\%js_lt);
                   2277:     return &Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT);
                   2278: 
                   2279:     function checkSelect(checkBox) {
                   2280:         var ctr=0;
                   2281:         var sense="";
                   2282:         var len = checkBox.length;
                   2283:         if (len == undefined) len = 1;
                   2284:         if (len > 1) {
                   2285:             for (var i=0; i<len; i++) {
                   2286:                 if (checkBox[i].checked) {
                   2287:                     ctr++;
                   2288:                 }
                   2289:             }
                   2290:             sense = '$js_lt{'multiple'}';
                   2291:         } else {
                   2292:             if (checkBox.checked) {
                   2293:                 ctr = 1;
                   2294:             }
                   2295:             sense = '$js_lt{'single'}';
                   2296:         }
                   2297:         if (ctr == 0) {
                   2298:             alert(sense);
                   2299:             return false;
                   2300:         }
                   2301:         document.$formname.submit();
                   2302:     }
                   2303: LISTJAVASCRIPT
                   2304: 
                   2305: }
1.249     albertel 2306: 
                   2307: sub check_script {
1.766     raeburn  2308:     my ($form,$type) = @_;
                   2309:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 2310:     function checkall() {
                   2311:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2312:             ele = document.forms.'.$form.'.elements[i];
                   2313:             if (ele.name == "'.$type.'") {
                   2314:             document.forms.'.$form.'.elements[i].checked=true;
                   2315:                                        }
                   2316:         }
                   2317:     }
                   2318: 
                   2319:     function checksec() {
                   2320:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2321:             ele = document.forms.'.$form.'.elements[i];
                   2322:            string = document.forms.'.$form.'.chksec.value;
                   2323:            if
                   2324:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   2325:               document.forms.'.$form.'.elements[i].checked=true;
                   2326:             }
                   2327:         }
                   2328:     }
                   2329: 
                   2330: 
                   2331:     function uncheckall() {
                   2332:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2333:             ele = document.forms.'.$form.'.elements[i];
                   2334:             if (ele.name == "'.$type.'") {
                   2335:             document.forms.'.$form.'.elements[i].checked=false;
                   2336:                                        }
                   2337:         }
                   2338:     }
                   2339: 
1.597     wenzelju 2340: '."\n");
1.249     albertel 2341:     return $chkallscript;
                   2342: }
                   2343: 
                   2344: sub check_buttons {
1.485     albertel 2345:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   2346:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   2347:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 2348:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   2349:     return $buttons;
                   2350: }
                   2351: 
1.44      ng       2352: #     Displays the submissions for one student or a group of students
1.34      ng       2353: sub processGroup {
1.766     raeburn  2354:     my ($request,$symb) = @_;
1.41      ng       2355:     my $ctr        = 0;
1.155     albertel 2356:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       2357:     my $total      = scalar(@stuchecked)-1;
1.45      ng       2358: 
1.396     banghart 2359:     foreach my $student (@stuchecked) {
                   2360: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 2361: 	$env{'form.student'}        = $uname;
                   2362: 	$env{'form.userdom'}        = $udom;
                   2363: 	$env{'form.fullname'}       = $fullname;
1.619     www      2364: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2365: 	$ctr++;
                   2366:     }
                   2367:     return '';
1.35      ng       2368: }
1.34      ng       2369: 
1.44      ng       2370: #------------------------------------------------------------------------------------
                   2371: #
                   2372: #-------------------------- Next few routines handles grading by student, essentially
                   2373: #                           handles essay response type problem/part
                   2374: #
                   2375: #--- Javascript to handle the submission page functionality ---
                   2376: sub sub_page_js {
                   2377:     my $request = shift;
1.736     damieng  2378:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   2379:     &js_escape(\$alertmsg);
1.597     wenzelju 2380:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       2381:     function updateRadio(formname,id,weight) {
1.125     ng       2382: 	var gradeBox = formname["GD_BOX"+id];
                   2383: 	var radioButton = formname["RADVAL"+id];
                   2384: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       2385: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       2386: 	gradeBox.value = pts;
                   2387: 	var resetbox = false;
                   2388: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  2389: 	    alert("$alertmsg"+pts);
1.71      ng       2390: 	    for (var i=0; i<radioButton.length; i++) {
                   2391: 		if (radioButton[i].checked) {
                   2392: 		    gradeBox.value = i;
                   2393: 		    resetbox = true;
                   2394: 		}
                   2395: 	    }
                   2396: 	    if (!resetbox) {
                   2397: 		formtextbox.value = "";
                   2398: 	    }
                   2399: 	    return;
1.44      ng       2400: 	}
1.71      ng       2401: 
                   2402: 	if (pts > weight) {
                   2403: 	    var resp = confirm("You entered a value ("+pts+
                   2404: 			       ") greater than the weight for the part. Accept?");
                   2405: 	    if (resp == false) {
1.125     ng       2406: 		gradeBox.value = oldpts;
1.71      ng       2407: 		return;
                   2408: 	    }
1.44      ng       2409: 	}
1.13      albertel 2410: 
1.71      ng       2411: 	for (var i=0; i<radioButton.length; i++) {
                   2412: 	    radioButton[i].checked=false;
                   2413: 	    if (pts == i && pts != "") {
                   2414: 		radioButton[i].checked=true;
                   2415: 	    }
                   2416: 	}
                   2417: 	updateSelect(formname,id);
1.125     ng       2418: 	formname["stores"+id].value = "0";
1.41      ng       2419:     }
1.5       albertel 2420: 
1.72      ng       2421:     function writeBox(formname,id,pts) {
1.125     ng       2422: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2423: 	if (checkSolved(formname,id) == 'update') {
                   2424: 	    gradeBox.value = pts;
                   2425: 	} else {
1.125     ng       2426: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       2427: 	    gradeBox.value = oldpts;
1.125     ng       2428: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       2429: 	    for (var i=0; i<radioButton.length; i++) {
                   2430: 		radioButton[i].checked=false;
1.72      ng       2431: 		if (i == oldpts) {
1.71      ng       2432: 		    radioButton[i].checked=true;
                   2433: 		}
                   2434: 	    }
1.41      ng       2435: 	}
1.125     ng       2436: 	formname["stores"+id].value = "0";
1.71      ng       2437: 	updateSelect(formname,id);
                   2438: 	return;
1.41      ng       2439:     }
1.44      ng       2440: 
1.71      ng       2441:     function clearRadBox(formname,id) {
                   2442: 	if (checkSolved(formname,id) == 'noupdate') {
                   2443: 	    updateSelect(formname,id);
                   2444: 	    return;
                   2445: 	}
1.125     ng       2446: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       2447: 	for (var i=0; i<gradeSelect.length; i++) {
                   2448: 	    if (gradeSelect[i].selected) {
                   2449: 		var selectx=i;
                   2450: 	    }
                   2451: 	}
1.125     ng       2452: 	var stores = formname["stores"+id];
1.71      ng       2453: 	if (selectx == stores.value) { return };
1.125     ng       2454: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2455: 	gradeBox.value = "";
1.125     ng       2456: 	var radioButton = formname["RADVAL"+id];
1.71      ng       2457: 	for (var i=0; i<radioButton.length; i++) {
                   2458: 	    radioButton[i].checked=false;
                   2459: 	}
                   2460: 	stores.value = selectx;
                   2461:     }
1.5       albertel 2462: 
1.71      ng       2463:     function checkSolved(formname,id) {
1.125     ng       2464: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       2465: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   2466: 	    if (!reply) {return "noupdate";}
1.120     ng       2467: 	    formname.overRideScore.value = 'yes';
1.41      ng       2468: 	}
1.71      ng       2469: 	return "update";
1.13      albertel 2470:     }
1.71      ng       2471: 
                   2472:     function updateSelect(formname,id) {
1.125     ng       2473: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       2474: 	return;
1.41      ng       2475:     }
1.33      ng       2476: 
1.121     ng       2477: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       2478:     function checksubmit(formname,val,total,parttot) {
1.121     ng       2479: 	formname.gradeOpt.value = val;
1.71      ng       2480: 	if (val == "Save & Next") {
                   2481: 	    for (i=0;i<=total;i++) {
                   2482: 		for (j=0;j<parttot;j++) {
1.125     ng       2483: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       2484: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2485: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       2486: 			if (points == "") {
1.125     ng       2487: 			    var name = formname["name"+i].value;
1.129     ng       2488: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   2489: 			    var resp = confirm("You did not assign a score for "+studentID+
                   2490: 					       ", part "+partid+". Continue?");
1.71      ng       2491: 			    if (resp == false) {
1.125     ng       2492: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       2493: 				return false;
                   2494: 			    }
                   2495: 			}
                   2496: 		    }
                   2497: 		}
                   2498: 	    }
                   2499: 	}
1.120     ng       2500: 	formname.submit();
                   2501:     }
                   2502: 
1.71      ng       2503: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   2504:     function checkSubmitPage(formname,total) {
                   2505: 	noscore = new Array(100);
                   2506: 	var ptr = 0;
                   2507: 	for (i=1;i<total;i++) {
1.125     ng       2508: 	    var partid = formname["q_"+i].value;
1.127     ng       2509: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2510: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   2511: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       2512: 		if (points == "" && status != "correct_by_student") {
                   2513: 		    noscore[ptr] = i;
                   2514: 		    ptr++;
                   2515: 		}
                   2516: 	    }
                   2517: 	}
                   2518: 	if (ptr != 0) {
                   2519: 	    var sense = ptr == 1 ? ": " : "s: ";
                   2520: 	    var prolist = "";
                   2521: 	    if (ptr == 1) {
                   2522: 		prolist = noscore[0];
                   2523: 	    } else {
                   2524: 		var i = 0;
                   2525: 		while (i < ptr-1) {
                   2526: 		    prolist += noscore[i]+", ";
                   2527: 		    i++;
                   2528: 		}
                   2529: 		prolist += "and "+noscore[i];
                   2530: 	    }
                   2531: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   2532: 	    if (resp == false) {
                   2533: 		return false;
                   2534: 	    }
                   2535: 	}
1.45      ng       2536: 
1.71      ng       2537: 	formname.submit();
                   2538:     }
                   2539: SUBJAVASCRIPT
                   2540: }
1.45      ng       2541: 
1.773     raeburn  2542: #--- javascript for grading message center
                   2543: sub sub_grademessage_js {
1.71      ng       2544:     my $request = shift;
1.80      ng       2545:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       2546:     &commonJSfunctions($request);
1.350     albertel 2547: 
1.629     www      2548:     my $inner_js_msg_central= (<<INNERJS);
                   2549: <script type="text/javascript">
1.350     albertel 2550:     function checkInput() {
                   2551:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   2552:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   2553:       var usrctr = document.msgcenter.usrctr.value;
                   2554:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   2555:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   2556: 
                   2557:       var msgchk = "";
                   2558:       if (document.msgcenter.subchk.checked) {
                   2559:          msgchk = "msgsub,";
                   2560:       }
                   2561:       var includemsg = 0;
                   2562:       for (var i=1; i<=nmsg; i++) {
                   2563:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   2564:           var frmmsg = document.msgcenter["msg"+i];
                   2565:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   2566:           var showflg = opener.document.SCORE["shownOnce"+i];
                   2567:           showflg.value = "1";
                   2568:           var chkbox = document.msgcenter["msgn"+i];
                   2569:           if (chkbox.checked) {
                   2570:              msgchk += "savemsg"+i+",";
                   2571:              includemsg = 1;
                   2572:           }
                   2573:       }
                   2574:       if (document.msgcenter.newmsgchk.checked) {
                   2575:          msgchk += "newmsg"+usrctr;
                   2576:          includemsg = 1;
                   2577:       }
                   2578:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   2579:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   2580:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   2581:       includemsg.value = msgchk;
                   2582: 
                   2583:       self.close()
                   2584: 
                   2585:     }
1.629     www      2586: </script>
1.350     albertel 2587: INNERJS
                   2588: 
1.773     raeburn  2589:     my $start_page_msg_central =
1.351     albertel 2590:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   2591: 				       {'js_ready'  => 1,
                   2592: 					'only_body' => 1,
                   2593: 					'bgcolor'   =>'#FFFFFF',});
1.773     raeburn  2594:     my $end_page_msg_central =
1.350     albertel 2595: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   2596: 
1.219     www      2597:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 2598:     $docopen=~s/^document\.//;
1.773     raeburn  2599: 
1.736     damieng  2600:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  2601:                 comp => 'Compose Message for: ',
                   2602:                 incl => 'Include',
1.656     raeburn  2603:                 type => 'Type',
1.652     raeburn  2604:                 subj => 'Subject',
                   2605:                 mesa => 'Message',
                   2606:                 new  => 'New',
                   2607:                 save => 'Save',
                   2608:                 canc => 'Cancel',
                   2609:              );
1.736     damieng  2610:     &html_escape(\%html_js_lt);
                   2611:     &js_escape(\%html_js_lt);
1.597     wenzelju 2612:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       2613: 
1.44      ng       2614: //===================== Script to view submitted by ==================
                   2615:   function viewSubmitter(submitter) {
                   2616:     document.SCORE.refresh.value = "on";
                   2617:     document.SCORE.NCT.value = "1";
                   2618:     document.SCORE.unamedom0.value = submitter;
                   2619:     document.SCORE.submit();
                   2620:     return;
                   2621:   }
                   2622: 
                   2623: //====================== Script for composing message ==============
1.80      ng       2624:    // preload images
                   2625:    img1 = new Image();
                   2626:    img1.src = "$iconpath/mailbkgrd.gif";
                   2627:    img2 = new Image();
                   2628:    img2.src = "$iconpath/mailto.gif";
                   2629: 
1.44      ng       2630:   function msgCenter(msgform,usrctr,fullname) {
                   2631:     var Nmsg  = msgform.savemsgN.value;
                   2632:     savedMsgHeader(Nmsg,usrctr,fullname);
                   2633:     var subject = msgform.msgsub.value;
1.127     ng       2634:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       2635:     re = /msgsub/;
                   2636:     var shwsel = "";
                   2637:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       2638:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   2639:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       2640:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       2641: 	var testmsg = "savemsg"+i+",";
                   2642: 	re = new RegExp(testmsg,"g");
1.44      ng       2643: 	shwsel = "";
                   2644: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       2645: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       2646: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       2647: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   2648: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       2649:     }
1.125     ng       2650:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       2651:     shwsel = "";
                   2652:     re = /newmsg/;
                   2653:     if (re.test(msgchk)) { shwsel = "checked" }
                   2654:     newMsg(newmsg,shwsel);
                   2655:     msgTail(); 
                   2656:     return;
                   2657:   }
                   2658: 
1.123     ng       2659:   function checkEntities(strx) {
                   2660:     if (strx.length == 0) return strx;
                   2661:     var orgStr = ["&", "<", ">", '"']; 
                   2662:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   2663:     var counter = 0;
                   2664:     while (counter < 4) {
                   2665: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   2666: 	counter++;
                   2667:     }
                   2668:     return strx;
                   2669:   }
                   2670: 
                   2671:   function strReplace(strx, orgStr, newStr) {
                   2672:     return strx.split(orgStr).join(newStr);
                   2673:   }
                   2674: 
1.44      ng       2675:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       2676:     var height = 70*Nmsg+250;
1.44      ng       2677:     if (height > 600) {
                   2678: 	height = 600;
                   2679:     }
1.118     ng       2680:     var xpos = (screen.width-600)/2;
                   2681:     xpos = (xpos < 0) ? '0' : xpos;
                   2682:     var ypos = (screen.height-height)/2-30;
                   2683:     ypos = (ypos < 0) ? '0' : ypos;
                   2684: 
1.668     www      2685:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       2686:     pWin.focus();
                   2687:     pDoc = pWin.document;
1.219     www      2688:     pDoc.$docopen;
1.351     albertel 2689:     pDoc.write('$start_page_msg_central');
1.76      ng       2690: 
                   2691:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   2692:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  2693:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       2694: 
1.676     golterma 2695:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  2696:     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       2697: }
                   2698:     function displaySubject(msg,shwsel) {
1.76      ng       2699:     pDoc = pWin.document;
1.676     golterma 2700:     pDoc.write("<tr>");
                   2701:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2702:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 2703:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       2704: }
                   2705: 
1.72      ng       2706:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       2707:     pDoc = pWin.document;
1.676     golterma 2708:     pDoc.write("<tr>");
                   2709:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 2710:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   2711:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2712: }
                   2713: 
                   2714:   function newMsg(newmsg,shwsel) {
1.76      ng       2715:     pDoc = pWin.document;
1.676     golterma 2716:     pDoc.write("<tr>");
                   2717:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2718:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 2719:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2720: }
                   2721: 
                   2722:   function msgTail() {
1.76      ng       2723:     pDoc = pWin.document;
1.676     golterma 2724:     //pDoc.write("<\\/table>");
1.465     albertel 2725:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  2726:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   2727:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 2728:     pDoc.write("<\\/form>");
1.351     albertel 2729:     pDoc.write('$end_page_msg_central');
1.128     ng       2730:     pDoc.close();
1.44      ng       2731: }
                   2732: 
1.773     raeburn  2733: SUBJAVASCRIPT
                   2734: }
                   2735: 
                   2736: #--- javascript for essay type problem --
                   2737: sub sub_page_kw_js {
                   2738:     my $request = shift;
                   2739: 
                   2740:     unless ($env{'form.compmsg'}) {
                   2741:         &commonJSfunctions($request);
                   2742:     }
                   2743: 
                   2744:     my $inner_js_highlight_central= (<<INNERJS);
                   2745: <script type="text/javascript">
                   2746:     function updateChoice(flag) {
                   2747:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   2748:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   2749:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   2750:       opener.document.SCORE.refresh.value = "on";
                   2751:       if (opener.document.SCORE.keywords.value!=""){
                   2752:          opener.document.SCORE.submit();
                   2753:       }
                   2754:       self.close()
                   2755:     }
                   2756: </script>
                   2757: INNERJS
                   2758: 
                   2759:     my $start_page_highlight_central =
                   2760:         &Apache::loncommon::start_page('Highlight Central',
                   2761:                                        $inner_js_highlight_central,
                   2762:                                        {'js_ready'  => 1,
                   2763:                                         'only_body' => 1,
                   2764:                                         'bgcolor'   =>'#FFFFFF',});
                   2765:     my $end_page_highlight_central =
                   2766:         &Apache::loncommon::end_page({'js_ready' => 1});
                   2767: 
                   2768:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   2769:     $docopen=~s/^document\.//;
                   2770: 
                   2771:     my %js_lt = &Apache::lonlocal::texthash(
                   2772:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   2773:                 plse => 'Please select a word or group of words from document and then click this link.',
                   2774:                 adds => 'Add selection to keyword list? Edit if desired.',
                   2775:                 col1 => 'red',
                   2776:                 col2 => 'green',
                   2777:                 col3 => 'blue',
                   2778:                 siz1 => 'normal',
                   2779:                 siz2 => '+1',
                   2780:                 siz3 => '+2',
                   2781:                 sty1 => 'normal',
                   2782:                 sty2 => 'italic',
                   2783:                 sty3 => 'bold',
                   2784:              );
                   2785:     my %html_js_lt = &Apache::lonlocal::texthash(
                   2786:                 save => 'Save',
                   2787:                 canc => 'Cancel',
                   2788:                 kehi => 'Keyword Highlight Options',
                   2789:                 txtc => 'Text Color',
                   2790:                 font => 'Font Size',
                   2791:                 fnst => 'Font Style',
                   2792:              );
                   2793:     &js_escape(\%js_lt);
                   2794:     &html_escape(\%html_js_lt);
                   2795:     &js_escape(\%html_js_lt);
                   2796:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   2797: 
                   2798: //===================== Show list of keywords ====================
                   2799:   function keywords(formname) {
                   2800:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   2801:     if (nret==null) return;
                   2802:     formname.keywords.value = nret;
                   2803: 
                   2804:     if (formname.keywords.value != "") {
                   2805:         formname.refresh.value = "on";
                   2806:         formname.submit();
                   2807:     }
                   2808:     return;
                   2809:   }
                   2810: 
                   2811: //===================== Script to add keyword(s) ==================
                   2812:   function getSel() {
                   2813:     if (document.getSelection) txt = document.getSelection();
                   2814:     else if (document.selection) txt = document.selection.createRange().text;
                   2815:     else return;
                   2816:     if (typeof(txt) != 'string') {
                   2817:         txt = String(txt);
                   2818:     }
                   2819:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   2820:     if (cleantxt=="") {
                   2821:         alert("$js_lt{'plse'}");
                   2822:         return;
                   2823:     }
                   2824:     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   2825:     if (nret==null) return;
                   2826:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   2827:     if (document.SCORE.keywords.value != "") {
                   2828:         document.SCORE.refresh.value = "on";
                   2829:         document.SCORE.submit();
                   2830:     }
                   2831:     return;
                   2832:   }
                   2833: 
1.44      ng       2834: //====================== Script for keyword highlight options ==============
                   2835:   function kwhighlight() {
                   2836:     var kwclr    = document.SCORE.kwclr.value;
                   2837:     var kwsize   = document.SCORE.kwsize.value;
                   2838:     var kwstyle  = document.SCORE.kwstyle.value;
                   2839:     var redsel = "";
                   2840:     var grnsel = "";
                   2841:     var blusel = "";
1.736     damieng  2842:     var txtcol1 = "$js_lt{'col1'}";
                   2843:     var txtcol2 = "$js_lt{'col2'}";
                   2844:     var txtcol3 = "$js_lt{'col3'}";
                   2845:     var txtsiz1 = "$js_lt{'siz1'}";
                   2846:     var txtsiz2 = "$js_lt{'siz2'}";
                   2847:     var txtsiz3 = "$js_lt{'siz3'}";
                   2848:     var txtsty1 = "$js_lt{'sty1'}";
                   2849:     var txtsty2 = "$js_lt{'sty2'}";
                   2850:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   2851:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   2852:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   2853:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       2854:     var sznsel = "";
                   2855:     var sz1sel = "";
                   2856:     var sz2sel = "";
1.718     bisitz   2857:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   2858:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   2859:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       2860:     var synsel = "";
                   2861:     var syisel = "";
                   2862:     var sybsel = "";
1.718     bisitz   2863:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   2864:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   2865:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       2866:     highlightCentral();
1.718     bisitz   2867:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   2868:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   2869:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       2870:     highlightend();
                   2871:     return;
                   2872:   }
                   2873: 
                   2874:   function highlightCentral() {
1.76      ng       2875: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       2876:     var xpos = (screen.width-400)/2;
                   2877:     xpos = (xpos < 0) ? '0' : xpos;
                   2878:     var ypos = (screen.height-330)/2-30;
                   2879:     ypos = (ypos < 0) ? '0' : ypos;
                   2880: 
1.206     albertel 2881:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       2882:     hwdWin.focus();
                   2883:     var hDoc = hwdWin.document;
1.219     www      2884:     hDoc.$docopen;
1.351     albertel 2885:     hDoc.write('$start_page_highlight_central');
1.76      ng       2886:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  2887:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       2888: 
1.718     bisitz   2889:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  2890:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       2891:   }
                   2892: 
                   2893:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       2894:     var hDoc = hwdWin.document;
1.718     bisitz   2895:     hDoc.write("<tr>");
1.76      ng       2896:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2897:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       2898:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2899:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       2900:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2901:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 2902:     hDoc.write("<\\/tr>");
1.44      ng       2903:   }
                   2904: 
                   2905:   function highlightend() { 
1.76      ng       2906:     var hDoc = hwdWin.document;
1.718     bisitz   2907:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  2908:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   2909:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 2910:     hDoc.write("<\\/form>");
1.351     albertel 2911:     hDoc.write('$end_page_highlight_central');
1.128     ng       2912:     hDoc.close();
1.44      ng       2913:   }
                   2914: 
                   2915: SUBJAVASCRIPT
                   2916: }
                   2917: 
1.349     albertel 2918: sub get_increment {
1.348     bowersj2 2919:     my $increment = $env{'form.increment'};
                   2920:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   2921:         $increment != .1) {
                   2922:         $increment = 1;
                   2923:     }
                   2924:     return $increment;
                   2925: }
                   2926: 
1.585     bisitz   2927: sub gradeBox_start {
                   2928:     return (
                   2929:         &Apache::loncommon::start_data_table()
                   2930:        .&Apache::loncommon::start_data_table_header_row()
                   2931:        .'<th>'.&mt('Part').'</th>'
                   2932:        .'<th>'.&mt('Points').'</th>'
                   2933:        .'<th>&nbsp;</th>'
                   2934:        .'<th>'.&mt('Assign Grade').'</th>'
                   2935:        .'<th>'.&mt('Weight').'</th>'
                   2936:        .'<th>'.&mt('Grade Status').'</th>'
                   2937:        .&Apache::loncommon::end_data_table_header_row()
                   2938:     );
                   2939: }
                   2940: 
                   2941: sub gradeBox_end {
                   2942:     return (
                   2943:         &Apache::loncommon::end_data_table()
                   2944:     );
                   2945: }
1.71      ng       2946: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   2947: sub gradeBox {
1.322     albertel 2948:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 2949:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2950: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2951:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2952:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2953:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2954:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2955:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2956: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   2957:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2958:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2959:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2960: 				       [$partid]);
                   2961:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2962:     if ($last_resets{$partid}) {
                   2963:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2964:     }
1.695     bisitz   2965:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2966:     my $ctr = 0;
1.348     bowersj2 2967:     my $thisweight = 0;
1.349     albertel 2968:     my $increment = &get_increment();
1.485     albertel 2969: 
                   2970:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2971:     while ($thisweight<=$wgt) {
1.532     bisitz   2972: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2973:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2974: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2975: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2976: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2977:         $thisweight += $increment;
1.71      ng       2978: 	$ctr++;
                   2979:     }
1.485     albertel 2980:     $radio.='</tr></table>';
                   2981: 
                   2982:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2983: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2984: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2985: 	$wgt.')" /></td>'."\n";
1.485     albertel 2986:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2987: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2988: 	' </td>'."\n";
                   2989:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2990: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2991:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2992: 	$line.='<option></option>'.
                   2993: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2994:     } else {
1.485     albertel 2995: 	$line.='<option selected="selected"></option>'.
                   2996: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2997:     }
1.485     albertel 2998:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2999: 
                   3000: 
                   3001:     $result .= 
1.695     bisitz   3002: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   3003:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   3004:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       3005:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   3006: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   3007: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  3008: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   3009:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   3010:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   3011:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   3012:         $aggtries.'" />'."\n";
1.582     raeburn  3013:     my $res_error;
                   3014:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   3015:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  3016:     if ($res_error) {
                   3017:         return &navmap_errormsg();
                   3018:     }
1.318     banghart 3019:     return $result;
                   3020: }
1.322     albertel 3021: 
                   3022: sub handback_box {
1.623     www      3023:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773     raeburn  3024:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   3025:     return unless ($numessay);
1.323     banghart 3026:     my (@respids);
1.652     raeburn  3027:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 3028:     foreach my $part_response_id (@part_response_id) {
                   3029:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 3030:         if ($part eq $partid) {
1.375     albertel 3031:             push(@respids,$resp);
1.323     banghart 3032:         }
                   3033:     }
1.318     banghart 3034:     my $result;
1.323     banghart 3035:     foreach my $respid (@respids) {
1.322     albertel 3036: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   3037: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3038: 	next if (!@$files);
1.654     raeburn  3039: 	my $file_counter = 0;
1.313     banghart 3040: 	foreach my $file (@$files) {
1.368     banghart 3041: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  3042:                 $file_counter++;
1.368     banghart 3043:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  3044:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 3045:     	        $file_disp = "$name.$ext";
                   3046:     	        $file = $file_path.$file_disp;
                   3047:     	        $result.=&mt('Return commented version of [_1] to student.',
                   3048:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   3049:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  3050:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 3051: 	    }
1.322     albertel 3052: 	}
1.654     raeburn  3053:         if ($file_counter) {
                   3054:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   3055:                        '<span class="LC_info">'.
                   3056:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   3057:         }
1.313     banghart 3058:     }
1.318     banghart 3059:     return $result;    
1.71      ng       3060: }
1.44      ng       3061: 
1.58      albertel 3062: sub show_problem {
1.382     albertel 3063:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 3064:     my $rendered;
1.382     albertel 3065:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 3066:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 3067:     if ($mode eq 'both' or $mode eq 'text') {
                   3068: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 3069: 						       $env{'request.course.id'},
                   3070: 						       undef,\%form);
1.144     albertel 3071:     }
1.58      albertel 3072:     if ($removeform) {
                   3073: 	$rendered=~s|<form(.*?)>||g;
                   3074: 	$rendered=~s|</form>||g;
1.374     albertel 3075: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 3076:     }
1.144     albertel 3077:     my $companswer;
                   3078:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 3079: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 3080: 	$companswer=
                   3081: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   3082: 						    $env{'request.course.id'},
                   3083: 						    %form);
1.144     albertel 3084:     }
1.58      albertel 3085:     if ($removeform) {
                   3086: 	$companswer=~s|<form(.*?)>||g;
                   3087: 	$companswer=~s|</form>||g;
1.144     albertel 3088: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 3089:     }
1.671     raeburn  3090:     my $renderheading = &mt('View of the problem');
                   3091:     my $answerheading = &mt('Correct answer');
                   3092:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   3093:         my $stu_fullname = $env{'form.fullname'};
                   3094:         if ($stu_fullname eq '') {
                   3095:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3096:         }
                   3097:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   3098:         if ($forwhom ne '') {
                   3099:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   3100:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   3101:         }
                   3102:     }
1.468     albertel 3103:     $rendered=
1.588     bisitz   3104:         '<div class="LC_Box">'
1.671     raeburn  3105:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   3106:        .$rendered
                   3107:        .'</div>';
1.468     albertel 3108:     $companswer=
1.588     bisitz   3109:         '<div class="LC_Box">'
1.671     raeburn  3110:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   3111:        .$companswer
                   3112:        .'</div>';
1.468     albertel 3113:     my $result;
1.144     albertel 3114:     if ($mode eq 'both') {
1.588     bisitz   3115:         $result=$rendered.$companswer;
1.144     albertel 3116:     } elsif ($mode eq 'text') {
1.588     bisitz   3117:         $result=$rendered;
1.144     albertel 3118:     } elsif ($mode eq 'answer') {
1.588     bisitz   3119:         $result=$companswer;
1.144     albertel 3120:     }
1.71      ng       3121:     return $result;
1.58      albertel 3122: }
1.397     albertel 3123: 
1.396     banghart 3124: sub files_exist {
                   3125:     my ($r, $symb) = @_;
                   3126:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   3127:     foreach my $student (@students) {
                   3128:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 3129:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3130: 					      $udom,$uname);
1.792     raeburn  3131:         my ($string)= &get_last_submission(\%record);
1.397     albertel 3132:         foreach my $submission (@$string) {
                   3133:             my ($partid,$respid) =
                   3134: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3135:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   3136: 					   \%record);
                   3137:             return 1 if (@$files);
1.396     banghart 3138:         }
                   3139:     }
1.397     albertel 3140:     return 0;
1.396     banghart 3141: }
1.397     albertel 3142: 
1.394     banghart 3143: sub download_all_link {
                   3144:     my ($r,$symb) = @_;
1.621     www      3145:     unless (&files_exist($r, $symb)) {
1.766     raeburn  3146:         $r->print(&mt('There are currently no submitted documents.'));
                   3147:         return;
1.621     www      3148:     }
1.395     albertel 3149:     my $all_students = 
                   3150: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   3151: 
                   3152:     my $parts =
                   3153: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   3154: 
1.394     banghart 3155:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  3156:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   3157:                              'cgi.'.$identifier.'.symb' => $symb,
                   3158:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 3159:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   3160: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      3161:     return;
                   3162: }
                   3163: 
                   3164: sub submit_download_link {
                   3165:     my ($request,$symb) = @_;
                   3166:     if (!$symb) { return ''; }
1.750     raeburn  3167:     my $res_error;
1.773     raeburn  3168:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   3169:         &response_type($symb,\$res_error);
                   3170:     if ($res_error) {
                   3171:         $request->print(&mt('An error occurred retrieving response types'));
                   3172:         return;
                   3173:     }
                   3174:     unless ($numessay) {
                   3175:         $request->print(&mt('No essayresponse items found'));
                   3176:         return;
1.750     raeburn  3177:     }
1.773     raeburn  3178:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3179:     if (@chosenparts) {
                   3180:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   3181:                                           undef,undef,1));
1.750     raeburn  3182:     }
1.773     raeburn  3183:     if ($numessay) {
1.750     raeburn  3184:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   3185:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3186:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   3187:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   3188:         if (ref($fullname) eq 'HASH') {
                   3189:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   3190:             if (@students) {
                   3191:                 @{$env{'form.stuinfo'}} = @students;
1.773     raeburn  3192:                 if ($numdropbox) {
1.750     raeburn  3193:                     &download_all_link($request,$symb);
1.773     raeburn  3194:                 } else {
                   3195:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  3196:                 }
1.773     raeburn  3197: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  3198: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   3199:             } else {
                   3200:                 $request->print(&mt('No students match the criteria you selected'));
                   3201:             }
                   3202:         } else {
                   3203:             $request->print(&mt('Could not retrieve student information'));
                   3204:         }
                   3205:     } else {
                   3206:         $request->print(&mt('No essayresponse items found'));
                   3207:     }
                   3208:     return;
1.394     banghart 3209: }
1.395     albertel 3210: 
1.432     banghart 3211: sub build_section_inputs {
                   3212:     my $section_inputs;
                   3213:     if ($env{'form.section'} eq '') {
                   3214:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   3215:     } else {
                   3216:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 3217:         foreach my $section (@sections) {
1.432     banghart 3218:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   3219:         }
                   3220:     }
                   3221:     return $section_inputs;
                   3222: }
                   3223: 
1.44      ng       3224: # --------------------------- show submissions of a student, option to grade 
                   3225: sub submission {
1.773     raeburn  3226:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 3227:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   3228:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   3229:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3230:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      3231: 
1.324     albertel 3232:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773     raeburn  3233:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  3234:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  3235:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 3236: 
                   3237:     if (!&canview($usec)) {
1.712     bisitz   3238:         $request->print(
                   3239:             '<span class="LC_warning">'.
1.713     bisitz   3240:             &mt('Unable to view requested student.').
1.712     bisitz   3241:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3242:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3243:             '</span>');
1.104     albertel 3244: 	return;
                   3245:     }
                   3246: 
1.773     raeburn  3247:     my $res_error;
                   3248:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   3249:         &response_type($symb,\$res_error);
                   3250:     if ($res_error) {
                   3251:         $request->print(&navmap_errormsg());
                   3252:         return;
                   3253:     }
                   3254: 
1.257     albertel 3255:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  3256:     unless ($is_tool) { 
                   3257:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   3258:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   3259:     }
1.773     raeburn  3260:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   3261:         $env{'form.compmsg'} = 1;
                   3262:     }
1.257     albertel 3263:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 3264:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   3265: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       3266: 	'/check.gif" height="16" border="0" />';
1.41      ng       3267: 
                   3268:     # header info
                   3269:     if ($counter == 0) {
1.773     raeburn  3270:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3271:         if (@chosenparts) {
                   3272:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   3273:         } elsif ($divforres) {
                   3274:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   3275:         } else {
                   3276:             $request->print('<br clear="all" />');
                   3277:         }
1.41      ng       3278: 	&sub_page_js($request);
1.773     raeburn  3279:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   3280: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       3281: 
1.44      ng       3282: 	# option to display problem, only once else it cause problems 
                   3283:         # with the form later since the problem has a form.
1.257     albertel 3284: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 3285: 	    my $mode;
1.257     albertel 3286: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 3287: 		$mode='both';
1.257     albertel 3288: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 3289: 		$mode='text';
1.257     albertel 3290: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 3291: 		$mode='answer';
                   3292: 	    }
1.329     albertel 3293: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 3294: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       3295: 	}
1.441     www      3296: 
1.41      ng       3297: 	my %keyhash = ();
1.773     raeburn  3298: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       3299: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 3300: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   3301: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773     raeburn  3302: 	}
                   3303: 	# kwclr is the only variable that is guaranteed not to be blank
                   3304: 	# if this subroutine has been called once.
                   3305: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 3306: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3307: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   3308: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   3309: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   3310: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773     raeburn  3311: 	}
                   3312: 	if ($env{'form.compmsg'}) {
                   3313: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      3314: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 3315: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       3316: 	}
1.773     raeburn  3317: 
1.257     albertel 3318: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 3319: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 3320: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       3321: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 3322: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       3323: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       3324: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       3325: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   3326: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 3327: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3328: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   3329: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   3330: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773     raeburn  3331: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 3332: 			&build_section_inputs().
1.326     albertel 3333: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       3334: 			'<input type="hidden" name="NCT"'.
1.257     albertel 3335: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773     raeburn  3336: 	if ($env{'form.compmsg'}) {
                   3337: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   3338: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   3339: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   3340: 	}
                   3341: 	if ($numessay) {
1.257     albertel 3342: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   3343: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   3344: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773     raeburn  3345: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       3346: 	}
1.773     raeburn  3347: 
1.41      ng       3348: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 3349: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       3350: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       3351: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 3352: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       3353: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       3354: 		'" />'."\n".
                   3355: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       3356: 	    $cts++;
                   3357: 	}
                   3358: 	$request->print($prnmsg);
1.32      ng       3359: 
1.773     raeburn  3360: 	if ($numessay) {
1.652     raeburn  3361: 
                   3362:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   3363:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  3364:                           keyw => 'Keyword Options',
1.655     raeburn  3365:                           list => 'List',
1.652     raeburn  3366:                           past => 'Paste Selection to List',
1.661     www      3367:                           high => 'Highlight Attribute',
1.773     raeburn  3368:                      );
1.88      www      3369: #
                   3370: # Print out the keyword options line
                   3371: #
1.718     bisitz   3372: 	    $request->print(
                   3373:                 '<div class="LC_columnSection">'
                   3374:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   3375:                .&Apache::lonhtmlcommon::funclist_from_array(
                   3376:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   3377:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   3378:  class="page">'.$lt{'past'}.'</a>',
                   3379:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   3380:                     {legend => $lt{'keyw'}})
                   3381:                .'</fieldset></div>'
                   3382:             );
                   3383: 
1.88      www      3384: #
                   3385: # Load the other essays for similarity check
                   3386: #
1.753     raeburn  3387:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   3388:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3389:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3390:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3391:                 if ($cdom ne '' && $cnum ne '') {
                   3392:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   3393:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   3394:                         my $apath = $1.'_'.$id;
                   3395:                         $apath=~s/\W/\_/gs;
                   3396:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   3397:                     }
                   3398:                 }
                   3399:             } else {
                   3400: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   3401: 	        $apath=&escape($apath);
                   3402: 	        $apath=~s/\W/\_/gs;
                   3403:                 &init_old_essays($symb,$apath,$adom,$aname);
                   3404:             }
1.41      ng       3405:         }
                   3406:     }
1.44      ng       3407: 
1.441     www      3408: # This is where output for one specific student would start
1.592     bisitz   3409:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   3410:     $request->print(
                   3411:         "\n\n"
                   3412:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   3413:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   3414:        ."\n"
                   3415:     );
1.441     www      3416: 
1.592     bisitz   3417:     # Show additional functions if allowed
                   3418:     if ($perm{'vgr'}) {
                   3419:         $request->print(
                   3420:             &Apache::loncommon::track_student_link(
1.708     bisitz   3421:                 'View recent activity',
1.592     bisitz   3422:                 $uname,$udom,'check')
                   3423:            .' '
                   3424:         );
                   3425:     }
                   3426:     if ($perm{'opa'}) {
                   3427:         $request->print(
                   3428:             &Apache::loncommon::pprmlink(
                   3429:                 &mt('Set/Change parameters'),
                   3430:                 $uname,$udom,$symb,'check'));
                   3431:     }
                   3432: 
                   3433:     # Show Problem
1.257     albertel 3434:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 3435: 	my $mode;
1.257     albertel 3436: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 3437: 	    $mode='both';
1.257     albertel 3438: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 3439: 	    $mode='text';
1.257     albertel 3440: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 3441: 	    $mode='answer';
                   3442: 	}
1.329     albertel 3443: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 3444: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 3445:     }
1.144     albertel 3446: 
1.257     albertel 3447:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       3448: 
1.44      ng       3449:     # Display student info
1.41      ng       3450:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   3451: 
1.745     raeburn  3452:     my $boxtitle = &mt('Submissions');
                   3453:     if ($is_tool) {
                   3454:         $boxtitle = &mt('Transactions')
                   3455:     }
1.590     bisitz   3456:     my $result='<div class="LC_Box">'
1.745     raeburn  3457:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       3458:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   3459:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773     raeburn  3460:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   3461:         $result.='<p class="LC_info">'
                   3462:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   3463:                 ."</p>\n";
1.469     albertel 3464:     }
                   3465: 
1.773     raeburn  3466:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 3467:     my $fullname;
                   3468:     my $col_fullnames = [];
1.773     raeburn  3469:     if ($numessay) {
1.464     albertel 3470: 	(my $sub_result,$fullname,$col_fullnames)=
                   3471: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   3472: 				 $counter);
                   3473: 	$result.=$sub_result;
1.41      ng       3474:     }
1.44      ng       3475:     $request->print($result."\n");
1.773     raeburn  3476: 
1.44      ng       3477:     # print student answer/submission
1.773     raeburn  3478:     # Options are (1) Last submission only
                   3479:     #             (2) Last submission (with detailed information for that submission)
                   3480:     #             (3) All transactions (by date)
                   3481:     #             (4) The whole record (with detailed information for all transactions)
                   3482: 
1.793     raeburn  3483:     my ($lastsubonly,$partinfo) =
                   3484:         &show_last_submission($uname,$udom,$symb,$essayurl,$responseType,$env{'form.lastSub'},
                   3485:                               $is_tool,$fullname,\%record,\%coursedesc_by_cid);
                   3486:     $request->print($partinfo);
                   3487:     $request->print($lastsubonly);
                   3488: 
                   3489:     if ($env{'form.lastSub'} eq 'datesub') {
                   3490:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3491: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
                   3492:     }
                   3493:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   3494:         my $identifier = (&canmodify($usec)? $counter : '');
                   3495:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
                   3496: 								 $env{'request.course.id'},
                   3497: 								 $last,'.submission',
                   3498: 								 'Apache::grades::keywords_highlight',
                   3499:                                                                  $usec,$identifier));
                   3500:     }
                   3501:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   3502: 	.$udom.'" />'."\n");
                   3503:     # return if view submission with no grading option
                   3504:     if (!&canmodify($usec)) {
                   3505: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   3506: 	return;
                   3507:     } else {
                   3508: 	$request->print('</div>'."\n");
                   3509:     }
                   3510: 
                   3511:     # grading message center
                   3512: 
                   3513:     if ($env{'form.compmsg'}) {
                   3514:         my $result='<div class="LC_Box">'.
                   3515:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   3516:                    '<div class="LC_grade_message_center_body">';
                   3517:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   3518:         my $msgfor = $givenn.' '.$lastname;
                   3519:         if (scalar(@$col_fullnames) > 0) {
                   3520:             my $lastone = pop(@$col_fullnames);
                   3521:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   3522:         }
                   3523:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   3524:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   3525:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   3526:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   3527:                  ',\''.$msgfor.'\');" target="_self">'.
                   3528:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   3529:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   3530:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   3531:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   3532:                  '<br />&nbsp;('.
                   3533:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   3534:                  '</div></div>';
                   3535:         $request->print($result);
                   3536:     }
                   3537: 
                   3538:     my %seen = ();
                   3539:     my @partlist;
                   3540:     my @gradePartRespid;
                   3541:     my @part_response_id;
                   3542:     if ($is_tool) {
                   3543:         @part_response_id = ([0,'']);
                   3544:     } else {
                   3545:         @part_response_id = &flatten_responseType($responseType);
                   3546:     }
                   3547:     $request->print(
                   3548:         '<div class="LC_Box">'
                   3549:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
                   3550:     );
                   3551:     $request->print(&gradeBox_start());
                   3552:     foreach my $part_response_id (@part_response_id) {
                   3553:     	my ($partid,$respid) = @{ $part_response_id };
                   3554: 	my $part_resp = join('_',@{ $part_response_id });
                   3555: 	next if ($seen{$partid} > 0);
                   3556: 	$seen{$partid}++;
                   3557: 	push(@partlist,$partid);
                   3558: 	push(@gradePartRespid,$partid.'.'.$respid);
                   3559: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
                   3560:     }
                   3561:     $request->print(&gradeBox_end()); # </div>
                   3562:     $request->print('</div>');
                   3563: 
                   3564:     $request->print('<div class="LC_grade_info_links">');
                   3565:     $request->print('</div>');
                   3566: 
                   3567:     $result='<input type="hidden" name="partlist'.$counter.
                   3568: 	'" value="'.(join ":",@partlist).'" />'."\n";
                   3569:     $result.='<input type="hidden" name="gradePartRespid'.
                   3570: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
                   3571:     my $ctr = 0;
                   3572:     while ($ctr < scalar(@partlist)) {
                   3573: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   3574: 	    $partlist[$ctr].'" />'."\n";
                   3575: 	$ctr++;
                   3576:     }
                   3577:     $request->print($result.''."\n");
                   3578: 
                   3579: # Done with printing info for one student
                   3580: 
                   3581:     $request->print('</div>');#LC_grade_show_user
                   3582: 
                   3583: 
                   3584:     # print end of form
                   3585:     if ($counter == $total) {
                   3586:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
                   3587: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
                   3588: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
                   3589: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
                   3590: 	my $ntstu ='<select name="NTSTU">'.
                   3591: 	    '<option>1</option><option>2</option>'.
                   3592: 	    '<option>3</option><option>5</option>'.
                   3593: 	    '<option>7</option><option>10</option></select>'."\n";
                   3594: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
                   3595: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
                   3596:         $endform.=&mt('[_1]student(s)',$ntstu);
                   3597: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
                   3598: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
                   3599: 	    '<input type="button" value="'.&mt('Next').'" '.
                   3600: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
                   3601:         $endform.='<span class="LC_warning">'.
                   3602:                   &mt('(Next and Previous (student) do not save the scores.)').
                   3603:                   '</span>'."\n" ;
                   3604:         $endform.="<input type='hidden' value='".&get_increment().
                   3605:             "' name='increment' />";
                   3606: 	$endform.='</td></tr></table></form>';
                   3607: 	$request->print($endform);
                   3608:     }
                   3609:     return '';
                   3610: }
                   3611: 
                   3612: sub show_last_submission {
                   3613:     my ($uname,$udom,$symb,$essayurl,$responseType,$viewtype,$is_tool,$fullname,
                   3614:         $record,$coursedesc_by_cid) = @_;
1.792     raeburn  3615:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
1.793     raeburn  3616:         &get_last_submission($record,$is_tool);
1.468     albertel 3617: 
1.793     raeburn  3618:     my ($lastsubonly,$partinfo);
1.792     raeburn  3619:     if ($timestamp eq '') {
1.793     raeburn  3620:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>';
1.745     raeburn  3621:     } elsif ($is_tool) {
                   3622:         $lastsubonly =
                   3623:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3624:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$timestamp."</div>\n";
1.702     kruse    3625:     } else {
1.792     raeburn  3626:         my ($shownsubmdate,$showngradedate);
                   3627:         if ($lastsubmittime && $lastgradetime) {
                   3628:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
                   3629:             if ($lastgradetime > $lastsubmittime) {
                   3630:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
                   3631:              }
                   3632:         } else {
                   3633:             $shownsubmdate = $timestamp;
                   3634:         }
1.702     kruse    3635:         $lastsubonly =
                   3636:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3637:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
                   3638:         if ($showngradedate) {
                   3639:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
                   3640:         }
1.702     kruse    3641: 
1.793     raeburn  3642:         my %seenparts;
                   3643:         my @part_response_id = &flatten_responseType($responseType);
                   3644:         foreach my $part (@part_response_id) {
                   3645:             my ($partid,$respid) = @{ $part };
                   3646:             my $display_part=&get_display_part($partid,$symb);
                   3647:             if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   3648:                 if (exists($seenparts{$partid})) { next; }
                   3649:                 $seenparts{$partid}=1;
                   3650:                 $partinfo .=
1.702     kruse    3651:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3652:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   3653:                                '<a href="javascript:viewSubmitter(\''.
                   3654:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   3655:                                '\');" target="_self">'.
                   3656:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
1.793     raeburn  3657:                     '<br />';
                   3658:                 next;
                   3659:             }
                   3660:             my $responsetype = $responseType->{$partid}->{$respid};
                   3661:             if (!exists($record->{"resource.$partid.$respid.submission"})) {
1.702     kruse    3662:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   3663:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3664:                     ' <span class="LC_internal_info">'.
                   3665:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   3666:                     '</span>&nbsp; &nbsp;'.
1.793     raeburn  3667:                     '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   3668:                 next;
                   3669:             }
                   3670:             foreach my $submission (@$string) {
                   3671:                 my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3672:                 if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   3673:                 my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   3674:                 # Similarity check
1.702     kruse    3675:                 my $similar='';
                   3676:                 my ($type,$trial,$rndseed);
                   3677:                 if ($hide eq 'rand') {
                   3678:                     $type = 'randomizetry';
1.793     raeburn  3679:                     $trial = $record->{"resource.$partid.tries"};
                   3680:                     $rndseed = $record->{"resource.$partid.rndseed"};
1.702     kruse    3681:                 }
1.793     raeburn  3682:                 if ($env{'form.checkPlag'}) {
                   3683:                     my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   3684:                     &most_similar($uname,$udom,$symb,$subval);
                   3685:                     if ($osim) {
                   3686:                         $osim=int($osim*100.0);
1.702     kruse    3687:                         if ($hide eq 'anon') {
                   3688:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   3689:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   3690:                         } else {
1.793     raeburn  3691:                             $similar='<hr />';
1.753     raeburn  3692:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3693:                                 $similar .= '<h3><span class="LC_warning">'.
                   3694:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   3695:                                                 $osim,
                   3696:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3697:                                             '</span></h3>';
                   3698:                             } else {
                   3699:                                 my %old_course_desc;
                   3700:                                 if ($ocrsid ne '') {
1.793     raeburn  3701:                                     if (ref($coursedesc_by_cid->{$ocrsid}) eq 'HASH') {
                   3702:                                         %old_course_desc = %{$coursedesc_by_cid->{$ocrsid}};
1.753     raeburn  3703:                                     } else {
                   3704:                                         my $args;
                   3705:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   3706:                                             $args = {'one_time' => 1};
                   3707:                                         }
                   3708:                                         %old_course_desc =
                   3709:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
1.793     raeburn  3710:                                         $coursedesc_by_cid->{$ocrsid} = \%old_course_desc;
1.753     raeburn  3711:                                     }
                   3712:                                     $similar .=
                   3713:                                         '<h3><span class="LC_warning">'.
                   3714:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   3715:                                             $osim,
                   3716:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   3717:                                             $old_course_desc{'description'},
                   3718:                                             $old_course_desc{'num'},
                   3719:                                             $old_course_desc{'domain'}).
                   3720:                                         '</span></h3>';
                   3721:                                 } else {
                   3722:                                     $similar .=
                   3723:                                         '<h3><span class="LC_warning">'.
                   3724:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   3725:                                             $osim,
                   3726:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3727:                                         '</span></h3>';
                   3728:                                 }
                   3729:                             }
                   3730:                             $similar .= '<blockquote><i>'.
                   3731:                                         &keywords_highlight($oessay).
                   3732:                                         '</i></blockquote><hr />';
1.702     kruse    3733:                         }
1.793     raeburn  3734:                     }
                   3735:                 }
                   3736:                 my $order=&get_order($partid,$respid,$symb,$uname,$udom,
1.702     kruse    3737:                                      undef,$type,$trial,$rndseed);
1.793     raeburn  3738:                 if (($viewtype eq 'lastonly') ||
                   3739:                     ($viewtype eq 'datesub')  ||
                   3740:                     ($viewtype =~ /^(last|all)$/)) {
                   3741:                     my $display_part=&get_display_part($partid,$symb);
1.702     kruse    3742:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   3743:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3744:                         ' <span class="LC_internal_info">'.
                   3745:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   3746:                         '</span>&nbsp; &nbsp;';
1.793     raeburn  3747:                     my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3748:                     if (@$files) {
1.702     kruse    3749:                         if ($hide eq 'anon') {
                   3750:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   3751:                         } else {
                   3752:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   3753:                                         .'<br /><span class="LC_warning">';
                   3754:                             if(@$files == 1) {
                   3755:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  3756:                             } else {
1.702     kruse    3757:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   3758:                             }
1.774     raeburn  3759:                             $lastsubonly .= '</span>';
1.702     kruse    3760:                             foreach my $file (@$files) {
                   3761:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   3762:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  3763:                             }
                   3764:                         }
1.793     raeburn  3765:                         $lastsubonly.='<br />';
1.702     kruse    3766:                     }
                   3767:                     if ($hide eq 'anon') {
1.793     raeburn  3768:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
1.702     kruse    3769:                     } else {
1.774     raeburn  3770:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  3771:                         if ($draft) {
                   3772:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   3773:                         }
                   3774:                         $subval =
1.793     raeburn  3775:                             &cleanRecord($subval,$responsetype,$symb,$partid,
                   3776:                                          $respid,$record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  3777:                         if ($responsetype eq 'essay') {
                   3778:                             $subval =~ s{\n}{<br />}g;
                   3779:                         }
                   3780:                         $lastsubonly.=$subval."\n";
1.702     kruse    3781:                     }
1.774     raeburn  3782:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.793     raeburn  3783:                     $lastsubonly.='</div>';
                   3784:                 }
1.702     kruse    3785:             }
1.773     raeburn  3786:         }
1.793     raeburn  3787:         $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.118     ng       3788:     }
1.793     raeburn  3789:     return ($lastsubonly,$partinfo);
1.38      ng       3790: }
                   3791: 
1.464     albertel 3792: sub check_collaborators {
                   3793:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   3794:     my ($result,@col_fullnames);
                   3795:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   3796:     foreach my $part (keys(%$handgrade)) {
                   3797: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   3798: 					'.maxcollaborators',
                   3799: 					$symb,$udom,$uname);
                   3800: 	next if ($ncol <= 0);
                   3801: 	$part =~ s/\_/\./g;
                   3802: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   3803: 	my (@good_collaborators, @bad_collaborators);
                   3804: 	foreach my $possible_collaborator
1.630     www      3805: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 3806: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   3807: 	    next if ($possible_collaborator eq '');
1.631     www      3808: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 3809: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   3810: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   3811: 	    # Doing this grep allows 'fuzzy' specification
                   3812: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   3813: 			       keys(%$classlist));
                   3814: 	    if (! scalar(@matches)) {
                   3815: 		push(@bad_collaborators, $possible_collaborator);
                   3816: 	    } else {
                   3817: 		push(@good_collaborators, @matches);
                   3818: 	    }
                   3819: 	}
                   3820: 	if (scalar(@good_collaborators) != 0) {
1.630     www      3821: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 3822: 	    foreach my $name (@good_collaborators) {
                   3823: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   3824: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      3825: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 3826: 	    }
1.630     www      3827: 	    $result.='</ol><br />'."\n";
1.466     albertel 3828: 	    my ($part)=split(/\./,$part);
1.464     albertel 3829: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   3830: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   3831: 		"\n";
                   3832: 	}
                   3833: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 3834: 	    $result.='<div class="LC_warning">';
1.464     albertel 3835: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   3836: 	    $result .= '</div>';
                   3837: 	}         
                   3838: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 3839: 	    $result .= '<div class="LC_warning">';
1.464     albertel 3840: 	    $result .= &mt('This student has submitted too many '.
                   3841: 		'collaborators.  Maximum is [_1].',$ncol);
                   3842: 	    $result .= '</div>';
                   3843: 	}
                   3844:     }
                   3845:     return ($result,$fullname,\@col_fullnames);
                   3846: }
                   3847: 
1.44      ng       3848: #--- Retrieve the last submission for all the parts
1.38      ng       3849: sub get_last_submission {
1.745     raeburn  3850:     my ($returnhash,$is_tool)=@_;
1.792     raeburn  3851:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
1.119     ng       3852:     if ($$returnhash{'version'}) {
1.46      ng       3853: 	my %lasthash=();
1.792     raeburn  3854:         my %prevsolved=();
                   3855:         my %solved=();
                   3856: 	my $version;
1.119     ng       3857: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.792     raeburn  3858:             my %handgraded = ();
1.397     albertel 3859: 	    foreach my $key (sort(split(/\:/,
                   3860: 					$$returnhash{$version.':keys'}))) {
                   3861: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
1.792     raeburn  3862:                 if ($key =~ /\.([^.]+)\.regrader$/) {
                   3863:                     $handgraded{$1} = 1;
                   3864:                 } elsif ($key =~ /\.portfiles$/) {
                   3865:                     if (($$returnhash{$version.':'.$key} ne '') &&
                   3866:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
                   3867:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3868:                     }
                   3869:                 } elsif ($key =~ /\.submission$/) {
                   3870:                     if ($$returnhash{$version.':'.$key} ne '') {
                   3871:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3872:                     }
                   3873:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
                   3874:                     $prevsolved{$1} = $solved{$1};
                   3875:                     $solved{$1} = $lasthash{$key};
                   3876:                 }
                   3877:             }
                   3878:             foreach my $partid (keys(%handgraded)) {
                   3879:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
                   3880:                     (($solved{$partid} eq 'incorrect_by_override') ||
                   3881:                      ($solved{$partid} eq 'correct_by_override'))) {
                   3882:                     $lastgradetime = $$returnhash{$version.':timestamp'};
                   3883:                 }
                   3884:                 if ($solved{$partid} ne '') {
                   3885:                     $prevsolved{$partid} = $solved{$partid};
                   3886:                 }
1.46      ng       3887: 	    }
                   3888: 	}
1.795     raeburn  3889: #
                   3890: # Timestamp is for last transaction for this resource, which does not
                   3891: # necessarily correspond to the time of last submission for problem (or part).
                   3892: #
                   3893:         if ($lasthash{'timestamp'} ne '') {
                   3894:             $timestamp = &Apache::lonlocal::locallocaltime($lasthash{'timestamp'});
                   3895:         }
1.640     raeburn  3896:         my (%typeparts,%randombytry);
1.596     raeburn  3897:         my $showsurv = 
                   3898:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   3899:         foreach my $key (sort(keys(%lasthash))) {
                   3900:             if ($key =~ /\.type$/) {
                   3901:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  3902:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   3903:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  3904:                     my ($ign,@parts) = split(/\./,$key);
                   3905:                     pop(@parts);
1.641     raeburn  3906:                     my $id = join('.',@parts);
1.640     raeburn  3907:                     if ($lasthash{$key} eq 'randomizetry') {
                   3908:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   3909:                     } else {
                   3910:                         unless ($showsurv) {
                   3911:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   3912:                         }
1.596     raeburn  3913:                     }
                   3914:                     delete($lasthash{$key});
                   3915:                 }
                   3916:             }
                   3917:         }
                   3918:         my @hidden = keys(%typeparts);
1.640     raeburn  3919:         my @randomize = keys(%randombytry);
1.397     albertel 3920: 	foreach my $key (keys(%lasthash)) {
                   3921: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  3922:             my $hide;
                   3923:             if (@hidden) {
                   3924:                 foreach my $id (@hidden) {
                   3925:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  3926:                         $hide = 'anon';
1.596     raeburn  3927:                         last;
                   3928:                     }
                   3929:                 }
                   3930:             }
1.640     raeburn  3931:             unless ($hide) {
                   3932:                 if (@randomize) {
1.732     raeburn  3933:                     foreach my $id (@randomize) {
1.640     raeburn  3934:                         if ($key =~ /^\Q$id\E/) {
                   3935:                             $hide = 'rand';
                   3936:                             last;
                   3937:                         }
                   3938:                     }
                   3939:                 }
                   3940:             }
1.397     albertel 3941: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  3942: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   3943:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   3944:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   3945:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       3946: 	}
                   3947:     }
1.397     albertel 3948:     if (!@string) {
1.745     raeburn  3949:         my $msg;
                   3950:         if ($is_tool) {
1.747     raeburn  3951:             $msg = &mt('No grade passed back.');
1.745     raeburn  3952:         } else {
                   3953:             $msg = &mt('Nothing submitted - no attempts.');
                   3954:         }
1.397     albertel 3955: 	$string[0] =
1.745     raeburn  3956: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 3957:     }
1.792     raeburn  3958:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       3959: }
1.35      ng       3960: 
1.44      ng       3961: #--- High light keywords, with style choosen by user.
1.38      ng       3962: sub keywords_highlight {
1.44      ng       3963:     my $string    = shift;
1.257     albertel 3964:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   3965:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       3966:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 3967:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 3968:     foreach my $keyword (@keylist) {
                   3969: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       3970:     }
                   3971:     return $string;
1.38      ng       3972: }
1.36      ng       3973: 
1.671     raeburn  3974: # For Tasks provide a mechanism to display previous version for one specific student
                   3975: 
                   3976: sub show_previous_task_version {
                   3977:     my ($request,$symb) = @_;
                   3978:     if ($symb eq '') {
1.717     bisitz   3979:         $request->print(
                   3980:             '<span class="LC_error">'.
                   3981:             &mt('Unable to handle ambiguous references.').
                   3982:             '</span>');
1.671     raeburn  3983:         return '';
                   3984:     }
                   3985:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3986:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3987:     if (!&canview($usec)) {
1.712     bisitz   3988:         $request->print(
                   3989:             '<span class="LC_warning">'.
1.713     bisitz   3990:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   3991:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3992:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3993:             '</span>');
1.671     raeburn  3994:         return;
                   3995:     }
                   3996:     my $mode = 'both';
                   3997:     my $isTask = ($symb =~/\.task$/);
                   3998:     if ($isTask) {
                   3999:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   4000:             if ($env{'form.fullname'} eq '') {
                   4001:                 $env{'form.fullname'} =
                   4002:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   4003:             }
                   4004:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   4005:             $request->print("\n\n".
                   4006:                             '<div class="LC_grade_show_user">'.
                   4007:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   4008:                             '</h2>'."\n");
                   4009:             &Apache::lonxml::clear_problem_counter();
                   4010:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   4011:                             {'previousversion' => $env{'form.previousversion'} }));
                   4012:             $request->print("\n</div>");
                   4013:         }
                   4014:     }
                   4015:     return;
                   4016: }
                   4017: 
                   4018: sub choose_task_version_form {
                   4019:     my ($symb,$uname,$udom,$nomenu) = @_;
                   4020:     my $isTask = ($symb =~/\.task$/);
                   4021:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   4022:     if ($isTask) {
                   4023:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4024:                                               $udom,$uname);
                   4025:         if (($record{'resource.0.version'} eq '') ||
                   4026:             ($record{'resource.0.version'} < 2)) {
                   4027:             return ($record{'resource.0.version'},
                   4028:                     $record{'resource.0.version'},$result,$js);
                   4029:         } else {
                   4030:             $current = $record{'resource.0.version'};
                   4031:         }
                   4032:         if ($env{'form.previousversion'}) {
                   4033:             $displayed = $env{'form.previousversion'};
                   4034:             $rowtitle = &mt('Choose another version:')
                   4035:         } else {
                   4036:             $displayed = $current;
                   4037:             $rowtitle = &mt('Show earlier version:');
                   4038:         }
                   4039:         $result = '<div class="LC_left_float">';
                   4040:         my $list;
                   4041:         my $numversions = 0;
                   4042:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   4043:             if ($i == $current) {
                   4044:                 if (!$env{'form.previousversion'} || $nomenu) {
                   4045:                     next;
                   4046:                 } else {
                   4047:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   4048:                     $numversions ++;
                   4049:                 }
                   4050:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   4051:                 unless ($i == $env{'form.previousversion'}) {
                   4052:                     $numversions ++;
                   4053:                 }
                   4054:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   4055:             }
                   4056:         }
                   4057:         if ($numversions) {
                   4058:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   4059:             $result .=
                   4060:                 '<form name="getprev" method="post" action=""'.
                   4061:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   4062:                 &Apache::loncommon::start_data_table().
                   4063:                 &Apache::loncommon::start_data_table_row().
                   4064:                 '<th align="left">'.$rowtitle.'</th>'.
                   4065:                 '<td><select name="version">'.
                   4066:                 '<option>'.&mt('Select').'</option>'.
                   4067:                 $list.
                   4068:                 '</select></td>'.
                   4069:                 &Apache::loncommon::end_data_table_row();
                   4070:             unless ($nomenu) {
                   4071:                 $result .= &Apache::loncommon::start_data_table_row().
                   4072:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   4073:                 '<td><span class="LC_nobreak">'.
                   4074:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   4075:                 &mt('Yes').'</label>'.
                   4076:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   4077:                 '</span></td>'.
                   4078:                 &Apache::loncommon::end_data_table_row();
                   4079:             }
                   4080:             $result .=
                   4081:                 &Apache::loncommon::start_data_table_row().
                   4082:                 '<th align="left">&nbsp;</th>'.
                   4083:                 '<td>'.
                   4084:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   4085:                 '</td>'.
                   4086:                 &Apache::loncommon::end_data_table_row().
                   4087:                 &Apache::loncommon::end_data_table().
                   4088:                 '</form>';
                   4089:             $js = &previous_display_javascript($nomenu,$current);
                   4090:         } elsif ($displayed && $nomenu) {
                   4091:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   4092:         } else {
                   4093:             $result .= &mt('No previous versions to show for this student');
                   4094:         }
                   4095:         $result .= '</div>';
                   4096:     }
                   4097:     return ($current,$displayed,$result,$js);
                   4098: }
                   4099: 
                   4100: sub previous_display_javascript {
                   4101:     my ($nomenu,$current) = @_;
                   4102:     my $js = <<"JSONE";
                   4103: <script type="text/javascript">
                   4104: // <![CDATA[
                   4105: function previousVersion(uname,udom,symb) {
                   4106:     var current = '$current';
                   4107:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   4108:     var prevstr = new RegExp("^\\\\d+\$");
                   4109:     if (!prevstr.test(version)) {
                   4110:         return false;
                   4111:     }
                   4112:     var url = '';
                   4113:     if (version == current) {
                   4114:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   4115:     } else {
                   4116:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   4117:     }
                   4118: JSONE
                   4119:     if ($nomenu) {
                   4120:         $js .= <<"JSTWO";
                   4121:     document.location.href = url;
                   4122: JSTWO
                   4123:     } else {
                   4124:         $js .= <<"JSTHREE";
                   4125:     var newwin = 0;
                   4126:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   4127:         if (document.getprev.prevwin[i].checked == true) {
                   4128:             newwin = document.getprev.prevwin[i].value;
                   4129:         }
                   4130:     }
                   4131:     if (newwin == 1) {
                   4132:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   4133:         url = url+'&inhibitmenu=yes';
                   4134:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   4135:             previousWin = window.open(url,'',options,1);
                   4136:         } else {
                   4137:             previousWin.location.href = url;
                   4138:         }
                   4139:         previousWin.focus();
                   4140:         return false;
                   4141:     } else {
                   4142:         document.location.href = url;
                   4143:         return false;
                   4144:     }
                   4145: JSTHREE
                   4146:     }
                   4147:     $js .= <<"ENDJS";
                   4148:     return false;
                   4149: }
                   4150: // ]]>
                   4151: </script>
                   4152: ENDJS
                   4153: 
                   4154: }
                   4155: 
1.44      ng       4156: #--- Called from submission routine
1.38      ng       4157: sub processHandGrade {
1.608     www      4158:     my ($request,$symb) = @_;
1.324     albertel 4159:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 4160:     my $button = $env{'form.gradeOpt'};
                   4161:     my $ngrade = $env{'form.NCT'};
                   4162:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 4163:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4164:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.786     raeburn  4165:     my ($res_error,%queueable);
                   4166:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   4167:     if ($res_error) {
                   4168:         $request->print(&navmap_errormsg());
                   4169:         return;
                   4170:     } else {
                   4171:         foreach my $part (@{$partlist}) {
                   4172:             if (ref($responseType->{$part}) eq 'HASH') {
                   4173:                 foreach my $id (keys(%{$responseType->{$part}})) {
                   4174:                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   4175:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   4176:                         $queueable{$part} = 1;
                   4177:                         last;
                   4178:                     }
                   4179:                 }
                   4180:             }
                   4181:         }
                   4182:     }
1.301     albertel 4183: 
1.44      ng       4184:     if ($button eq 'Save & Next') {
1.798     raeburn  4185:         my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   4186:         my (%skip_passback,%pbsave,%pbcollab);
1.44      ng       4187: 	my $ctr = 0;
                   4188: 	while ($ctr < $ngrade) {
1.257     albertel 4189: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  4190: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
1.798     raeburn  4191:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable,\%needpb,\%skip_passback,\%pbsave);
1.71      ng       4192: 	    if ($errorflag eq 'no_score') {
                   4193: 		$ctr++;
                   4194: 		next;
                   4195: 	    }
1.104     albertel 4196: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   4197: 		$request->print(
                   4198:                     '<span class="LC_error">'
                   4199:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   4200:                    .'</span>');
1.104     albertel 4201: 		$ctr++;
                   4202: 		next;
                   4203: 	    }
1.726     raeburn  4204:             if ($numhidden) {
                   4205:                 $request->print(
                   4206:                     '<span class="LC_info">'
                   4207:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   4208:                    .'</span><br />');
                   4209:             }
1.257     albertel 4210: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       4211: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 4212: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   4213:             my ($feedurl,$showsymb) =
                   4214: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   4215: 	    my $messagetail;
1.62      albertel 4216: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      4217: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      4218: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  4219: 		$subject.=' ['.$restitle.']';
1.44      ng       4220: 		my (@msgnum) = split(/,/,$includemsg);
                   4221: 		foreach (@msgnum) {
1.257     albertel 4222: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       4223: 		}
1.80      ng       4224: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      4225: 		if ($env{'form.withgrades'.$ctr}) {
                   4226: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  4227: 		    $messagetail = " for <a href=\"".
1.605     www      4228: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  4229: 		}
                   4230: 		$msgstatus = 
                   4231:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   4232: 						     $message.$messagetail,
1.418     albertel 4233:                                                      undef,$feedurl,undef,
1.386     raeburn  4234:                                                      undef,undef,$showsymb,
                   4235:                                                      $restitle);
1.574     bisitz   4236: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  4237: 				$msgstatus.'<br />');
1.44      ng       4238: 	    }
1.257     albertel 4239: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 4240: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 4241: 		foreach my $collabstr (@collabstrs) {
                   4242: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 4243: 		    foreach my $collaborator (@collaborators) {
1.803     raeburn  4244: 			my ($errorflag,$pts,$wgt,$numchg,$numupdate) = 
1.324     albertel 4245: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.803     raeburn  4246: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 4247: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 4248: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 4249: 			    next;
1.798     raeburn  4250: 			} else {
1.803     raeburn  4251:                             if ($numchg || $numupdate) { 
                   4252:                                 $pbcollab{$collaborator}{$part} = [$pts,$wgt];
                   4253:                             }
1.798     raeburn  4254:                             if ($message ne '') {
1.800     raeburn  4255: 			        my ($baseurl,$showsymb) = 
                   4256: 				    &get_feedurl_and_symb($symb,$collaborator,
1.801     raeburn  4257: 						          $udom);
1.800     raeburn  4258: 			        if ($env{'form.withgrades'.$ctr}) {
                   4259: 				    $messagetail = " for <a href=\"".
                   4260:                                         $baseurl."?symb=$showsymb\">$restitle</a>";
                   4261: 			        }
                   4262: 			        $msgstatus =
                   4263: 				    &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.150     albertel 4264: 			    }
1.800     raeburn  4265: 		        }
1.44      ng       4266: 		    }
                   4267: 		}
                   4268: 	    }
                   4269: 	    $ctr++;
                   4270: 	}
1.798     raeburn  4271:         if ((keys(%pbcollab)) && (keys(%needpb))) {
1.803     raeburn  4272:             foreach my $user (keys(%pbcollab)) {
                   4273:                 my ($clbuname,$clbudom) = split(/:/,$user);
                   4274:                 my $clbusec = &Apache::lonnet::getsection($clbudom,$clbuname,$cdom.'_'.$cnum); 
                   4275:                 if (ref($pbcollab{$user}) eq 'HASH') {
                   4276:                     my @clparts = keys(%{$pbcollab{$user}});
                   4277:                     if (@clparts) {
                   4278:                         my $navmap = Apache::lonnavmaps::navmap->new($clbuname,$clbudom,$clbusec);
                   4279:                         if (ref($navmap)) {
                   4280:                             my $res = $navmap->getBySymb($symb);
                   4281:                             if (ref($res)) {
                   4282:                                 my $partlist = $res->parts();
                   4283:                                 if (ref($partlist) eq 'ARRAY') {
                   4284:                                     my (%weights,%awardeds,%excuseds);
                   4285:                                     foreach my $part (@{$partlist}) {
                   4286:                                         if ($res->status($part) eq $res->EXCUSED) {
                   4287:                                             $excuseds{$symb}{$part} = 1;
                   4288:                                         } else { 
                   4289:                                             $excuseds{$symb}{$part} = '';
                   4290:                                         }
                   4291:                                         if ((exists($pbcollab{$user}{$part})) && (ref($pbcollab{$user}{$part}) eq 'ARRAY')) {
                   4292:                                             my $pts = $pbcollab{$user}{$part}[0];
                   4293:                                             my $wt = $pbcollab{$user}{$part}[1];
                   4294:                                             if ($wt) {
                   4295:                                                 $awardeds{$symb}{$part} = $pts/$wt;
                   4296:                                                 $weights{$symb}{$part} = $wt;
                   4297:                                             } else {
                   4298:                                                 $awardeds{$symb}{$part} = 0;
                   4299:                                                 $weights{$symb}{$part} = 0;
                   4300:                                             }
                   4301:                                         } else {
                   4302:                                             $awardeds{$symb}{$part} = $res->awarded($part);
                   4303:                                             $weights{$symb}{$part} = $res->weight($part);
                   4304:                                         }
                   4305:                                     }
                   4306:                                     &process_passbacks('handgrade',[$symb],$cdom,$cnum,$clbudom,$clbuname,$clbusec,\%weights,
                   4307:                                                        \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   4308:                                 }
                   4309:                             }
                   4310:                         }
                   4311:                     }
                   4312:                 }
                   4313:             }
1.798     raeburn  4314:         }
1.44      ng       4315:     }
                   4316: 
1.773     raeburn  4317:     my %keyhash = ();
                   4318:     if ($numessay) {
1.119     ng       4319: 	# Keywords sorted in alphabatical order
1.257     albertel 4320: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   4321: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  4322: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 4323: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   4324: 	$env{'form.keywords'} = join(' ',@keywords);
                   4325: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   4326: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   4327: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   4328: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   4329: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  4330:     }
1.119     ng       4331: 
1.773     raeburn  4332:     if ($env{'form.compmsg'}) {
1.119     ng       4333: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 4334: 	# New messages are saved in env for the next student.
1.119     ng       4335: 	# All messages are saved in nohist_handgrade.db
                   4336: 	my ($ctr,$idx) = (1,1);
1.257     albertel 4337: 	while ($ctr <= $env{'form.savemsgN'}) {
                   4338: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   4339: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       4340: 		$idx++;
                   4341: 	    }
                   4342: 	    $ctr++;
1.41      ng       4343: 	}
1.119     ng       4344: 	$ctr = 0;
                   4345: 	while ($ctr < $ngrade) {
1.257     albertel 4346: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  4347: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4348: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4349: 	        $idx++;
1.119     ng       4350: 	    }
                   4351: 	    $ctr++;
1.41      ng       4352: 	}
1.257     albertel 4353: 	$env{'form.savemsgN'} = --$idx;
                   4354: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       4355:     }
1.773     raeburn  4356:     if (($numessay) || ($env{'form.compmsg'})) {
                   4357:         my $putresult = &Apache::lonnet::put
                   4358:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   4359:     }
                   4360: 
1.44      ng       4361:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 4362:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   4363:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       4364: 	my ($ctr,$total) = (0,0);
                   4365: 	while ($ctr < $ngrade) {
1.257     albertel 4366: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       4367: 	    $ctr++;
                   4368: 	}
1.257     albertel 4369: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       4370: 	$ctr = 0;
                   4371: 	while ($ctr < $total) {
1.257     albertel 4372: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   4373: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   4374: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      4375: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       4376: 	    $ctr++;
                   4377: 	}
                   4378: 	return '';
                   4379:     }
1.36      ng       4380: 
1.44      ng       4381:     # Get the next/previous one or group of students
1.257     albertel 4382:     my $firststu = $env{'form.unamedom0'};
                   4383:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       4384:     my $ctr = 2;
1.41      ng       4385:     while ($laststu eq '') {
1.257     albertel 4386: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       4387: 	$ctr++;
                   4388: 	$laststu = $firststu if ($ctr > $ngrade);
                   4389:     }
1.44      ng       4390: 
1.41      ng       4391:     my (@parsedlist,@nextlist);
                   4392:     my ($nextflg) = 0;
1.524     raeburn  4393:     foreach my $item (sort 
1.294     albertel 4394: 	     {
                   4395: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4396: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4397: 		 }
                   4398: 		 return $a cmp $b;
                   4399: 	     } (keys(%$fullname))) {
1.41      ng       4400: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  4401: 	    push(@parsedlist,$item);
1.41      ng       4402: 	}
1.524     raeburn  4403: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       4404: 	if ($button eq 'Previous') {
1.524     raeburn  4405: 	    last if ($item eq $firststu);
                   4406: 	    push(@parsedlist,$item);
1.41      ng       4407: 	}
                   4408:     }
                   4409:     $ctr = 0;
                   4410:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   4411:     foreach my $student (@parsedlist) {
1.257     albertel 4412: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       4413: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 4414: 	
                   4415: 	if ($submitonly eq 'queued') {
                   4416: 	    my %queue_status = 
                   4417: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4418: 							$udom,$uname);
                   4419: 	    next if (!defined($queue_status{'gradingqueue'}));
                   4420: 	}
                   4421: 
1.156     albertel 4422: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 4423: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 4424: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 4425: 	    my $submitted = 0;
1.248     albertel 4426: 	    my $ungraded = 0;
                   4427: 	    my $incorrect = 0;
1.524     raeburn  4428: 	    foreach my $item (keys(%status)) {
                   4429: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   4430: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   4431: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   4432: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 4433: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   4434: 		    $submitted = 0;
                   4435: 		}
1.41      ng       4436: 	    }
1.156     albertel 4437: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   4438: 				     $submitonly eq 'incorrect' ||
                   4439: 				     $submitonly eq 'graded'));
1.248     albertel 4440: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   4441: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       4442: 	}
1.524     raeburn  4443: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       4444: 	last if ($ctr == $ntstu);
1.41      ng       4445: 	$ctr++;
                   4446:     }
1.36      ng       4447: 
1.41      ng       4448:     $ctr = 0;
                   4449:     my $total = scalar(@nextlist)-1;
1.39      ng       4450: 
1.524     raeburn  4451:     foreach (sort(@nextlist)) {
1.41      ng       4452: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 4453: 	$env{'form.student'}  = $uname;
                   4454: 	$env{'form.userdom'}  = $udom;
                   4455: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      4456: 	&submission($request,$ctr,$total,$symb);
1.41      ng       4457: 	$ctr++;
                   4458:     }
                   4459:     if ($total < 0) {
1.653     raeburn  4460: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       4461: 	$request->print($the_end);
                   4462:     }
                   4463:     return '';
1.38      ng       4464: }
1.36      ng       4465: 
1.44      ng       4466: #---- Save the score and award for each student, if changed
1.38      ng       4467: sub saveHandGrade {
1.798     raeburn  4468:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable,$needpb,$skip_passback,$pbsave) = @_;
1.342     banghart 4469:     my @version_parts;
1.104     albertel 4470:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 4471: 					   $env{'request.course.id'});
1.104     albertel 4472:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 4473:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 4474:     my @parts_graded;
1.77      ng       4475:     my %newrecord  = ();
1.803     raeburn  4476:     my ($pts,$wgt,$totchg,$sendupdate) = ('','',0,0);
1.269     raeburn  4477:     my %aggregate = ();
                   4478:     my $aggregateflag = 0;
1.726     raeburn  4479:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  4480:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  4481:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  4482:         $totchg += $numchgs;
                   4483:     }
1.798     raeburn  4484:     my (%weights,%awardeds,%excuseds);
1.301     albertel 4485:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   4486:     foreach my $new_part (@parts) {
1.803     raeburn  4487: 	#collaborator ($submitter may vary for different parts)
1.259     banghart 4488: 	if ($submitter && $new_part ne $part) { next; }
                   4489: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.798     raeburn  4490:         if ($env{'form.WGT'.$newflg.'_'.$new_part} eq '') {
                   4491:             $weights{$symb}{$new_part} = 1;
                   4492:         } else {
                   4493:             $weights{$symb}{$new_part} = $env{'form.WGT'.$newflg.'_'.$new_part};
                   4494:         }
1.125     ng       4495: 	if ($dropMenu eq 'excused') {
1.798     raeburn  4496:             $excuseds{$symb}{$new_part} = 1;
                   4497:             $awardeds{$symb}{$new_part} = '';
1.259     banghart 4498: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   4499: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   4500: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   4501: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 4502: 		}
1.364     banghart 4503: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.803     raeburn  4504:                 $sendupdate ++;
1.58      albertel 4505: 	    }
1.125     ng       4506: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 4507: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  4508: 	    foreach my $key (keys(%record)) {
1.259     banghart 4509: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 4510: 	    }
1.259     banghart 4511: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4512: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 4513:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   4514: 
                   4515:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   4516: 					       [$new_part]);
                   4517:             my $aggtries =$totaltries;
1.269     raeburn  4518:             if ($last_resets{$new_part}) {
1.270     albertel 4519:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   4520: 					   $new_part);
1.269     raeburn  4521:             }
1.270     albertel 4522: 
                   4523:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  4524:             if ($aggtries > 0) {
1.327     albertel 4525:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  4526:                 $aggregateflag = 1;
                   4527:             }
1.803     raeburn  4528:             $sendupdate ++;
1.798     raeburn  4529:             $excuseds{$symb}{$new_part} = '';
                   4530:             $awardeds{$symb}{$new_part} = '';
1.125     ng       4531: 	} elsif ($dropMenu eq '') {
1.259     banghart 4532: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   4533: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   4534: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   4535: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 4536: 		next;
                   4537: 	    }
1.259     banghart 4538: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   4539: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       4540: 	    my $partial= $pts/$wgt;
1.798     raeburn  4541:             $awardeds{$symb}{$new_part} = $partial;
                   4542:             $excuseds{$symb}{$new_part} = '';
1.259     banghart 4543: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 4544: 		#do not update score for part if not changed.
1.346     banghart 4545:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 4546: 		next;
1.251     banghart 4547: 	    } else {
1.524     raeburn  4548: 	        push(@parts_graded,$new_part);
1.803     raeburn  4549:                 $sendupdate ++;
1.153     albertel 4550: 	    }
1.259     banghart 4551: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   4552: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 4553: 	    }
1.259     banghart 4554: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       4555: 	    if ($partial == 0) {
1.153     albertel 4556: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   4557: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   4558: 		}
1.41      ng       4559: 	    } else {
1.153     albertel 4560: 		if ($record{$reckey} ne 'correct_by_override') {
                   4561: 		    $newrecord{$reckey} = 'correct_by_override';
                   4562: 		}
                   4563: 	    }	    
                   4564: 	    if ($submitter && 
1.259     banghart 4565: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   4566: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       4567: 	    }
1.259     banghart 4568: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4569: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       4570: 	}
1.259     banghart 4571: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 4572: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   4573: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   4574: 	        $dropMenu eq 'reset status')
                   4575: 	   {
1.524     raeburn  4576: 	    push(@version_parts,$new_part);
1.259     banghart 4577: 	}
1.41      ng       4578:     }
1.301     albertel 4579:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4580:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4581: 
1.344     albertel 4582:     if (%newrecord) {
                   4583:         if (@version_parts) {
1.364     banghart 4584:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   4585:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 4586: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 4587: 	    foreach my $new_part (@version_parts) {
                   4588: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   4589: 				$new_part,\%newrecord);
                   4590: 	    }
1.259     banghart 4591:         }
1.44      ng       4592: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 4593: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 4594: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.786     raeburn  4595: 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       4596:     }
1.269     raeburn  4597:     if ($aggregateflag) {
                   4598:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4599: 			      $cdom,$cnum);
1.269     raeburn  4600:     }
1.803     raeburn  4601:     if (($sendupdate || $totchg) && (!$submitter)) {
1.798     raeburn  4602:         if ((ref($needpb) eq 'HASH') &&
                   4603:             (keys(%{$needpb}))) {
1.802     raeburn  4604:             &process_passbacks('handgrade',[$symb],$cdom,$cnum,$domain,$stuname,$usec,\%weights,
1.798     raeburn  4605:                                \%awardeds,\%excuseds,$needpb,$skip_passback,$pbsave);
                   4606:         }
                   4607:     }
1.803     raeburn  4608:     return ('',$pts,$wgt,$totchg,$sendupdate);
1.726     raeburn  4609: }
                   4610: 
                   4611: sub makehidden {
1.728     raeburn  4612:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  4613:     return unless (ref($record) eq 'HASH');
                   4614:     my %modified;
                   4615:     my $numchanged = 0;
                   4616:     if (exists($record->{$version.':keys'})) {
                   4617:         my $partsregexp = $parts;
                   4618:         $partsregexp =~ s/,/|/g;
                   4619:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   4620:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   4621:                  my $item = $1;
                   4622:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   4623:                      $modified{$key} = $record->{$version.':'.$key};
                   4624:                  }
                   4625:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   4626:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   4627:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   4628:                 $modified{$key} = $record->{$version.':'.$key};
                   4629:             }
                   4630:         }
                   4631:         if (keys(%modified)) {
                   4632:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  4633:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  4634:                 $numchanged ++;
                   4635:             }
                   4636:         }
                   4637:     }
                   4638:     return $numchanged;
1.36      ng       4639: }
1.322     albertel 4640: 
1.380     albertel 4641: sub check_and_remove_from_queue {
1.786     raeburn  4642:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 4643:     my @ungraded_parts;
                   4644:     foreach my $part (@{$parts}) {
                   4645: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   4646: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   4647: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   4648: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   4649: 		) {
1.786     raeburn  4650:             if ($queueable->{$part}) {
                   4651: 	        push(@ungraded_parts, $part);
                   4652:             }
1.380     albertel 4653: 	}
                   4654:     }
                   4655:     if ( !@ungraded_parts ) {
                   4656: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   4657: 					       $cnum,$domain,$stuname);
                   4658:     }
                   4659: }
                   4660: 
1.337     banghart 4661: sub handback_files {
                   4662:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  4663:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  4664:     my $res_error;
                   4665:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4666:     if ($res_error) {
                   4667:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   4668:         return;
                   4669:     }
1.654     raeburn  4670:     my @handedback;
                   4671:     my $file_msg;
1.375     albertel 4672:     my @part_response_id = &flatten_responseType($responseType);
                   4673:     foreach my $part_response_id (@part_response_id) {
                   4674:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   4675: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  4676:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   4677:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   4678:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   4679:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   4680:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 4681:                     my ($directory,$answer_file) = 
1.654     raeburn  4682:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 4683:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  4684: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 4685: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  4686:                     my $getpropath = 1;
1.773     raeburn  4687:                     my ($dir_list,$listerror) =
1.662     raeburn  4688:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   4689:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  4690: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   4691:                     # fix filename
1.355     banghart 4692:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   4693:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  4694:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 4695:             	                                $save_file_name);
1.337     banghart 4696:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  4697:                         $request->print('<br /><span class="LC_error">'.
                   4698:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  4699:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  4700:                                         '</span>');
1.356     banghart 4701:                     } else {
1.360     banghart 4702:                         # mark the file as read only
1.654     raeburn  4703:                         push(@handedback,$save_file_name);
1.367     albertel 4704: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   4705: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   4706: 			}
                   4707:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  4708: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 4709:                     }
1.686     bisitz   4710:                     $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 4711:                 }
                   4712:             }
                   4713:         }
1.654     raeburn  4714:     }
                   4715:     if (@handedback > 0) {
                   4716:         $request->print('<br />');
                   4717:         my @what = ($symb,$env{'request.course.id'},'handback');
                   4718:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   4719:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   4720:         my ($subject,$message);
                   4721:         if (scalar(@handedback) == 1) {
                   4722:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   4723:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   4724:         } else {
                   4725:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   4726:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   4727:         }
                   4728:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   4729:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   4730:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   4731:         my ($feedurl,$showsymb) =
                   4732:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   4733:         my $restitle = &Apache::lonnet::gettitle($symb);
                   4734:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   4735:         my $msgstatus =
                   4736:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   4737:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   4738:                  $restitle);
                   4739:         if ($msgstatus) {
                   4740:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   4741:         }
                   4742:     }
1.338     banghart 4743:     return;
1.337     banghart 4744: }
                   4745: 
1.418     albertel 4746: sub get_feedurl_and_symb {
                   4747:     my ($symb,$uname,$udom) = @_;
                   4748:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   4749:     $url = &Apache::lonnet::clutter($url);
                   4750:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   4751: 					$symb,$udom,$uname);
                   4752:     if ($encrypturl =~ /^yes$/i) {
                   4753: 	&Apache::lonenc::encrypted(\$url,1);
                   4754: 	&Apache::lonenc::encrypted(\$symb,1);
                   4755:     }
                   4756:     return ($url,$symb);
                   4757: }
                   4758: 
1.313     banghart 4759: sub get_submitted_files {
                   4760:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   4761:     my @files;
                   4762:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   4763:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   4764:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   4765:     	    push(@files,$file_url.$file);
                   4766:         }
                   4767:     }
                   4768:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   4769:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   4770:     }
                   4771:     return (\@files);
                   4772: }
1.322     albertel 4773: 
1.269     raeburn  4774: # ----------- Provides number of tries since last reset.
                   4775: sub get_num_tries {
                   4776:     my ($record,$last_reset,$part) = @_;
                   4777:     my $timestamp = '';
                   4778:     my $num_tries = 0;
                   4779:     if ($$record{'version'}) {
                   4780:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   4781:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   4782:                 $timestamp = $$record{$version.':timestamp'};
                   4783:                 if ($timestamp > $last_reset) {
                   4784:                     $num_tries ++;
                   4785:                 } else {
                   4786:                     last;
                   4787:                 }
                   4788:             }
                   4789:         }
                   4790:     }
                   4791:     return $num_tries;
                   4792: }
                   4793: 
                   4794: # ----------- Determine decrements required in aggregate totals 
                   4795: sub decrement_aggs {
                   4796:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   4797:     my %decrement = (
                   4798:                         attempts => 0,
                   4799:                         users => 0,
                   4800:                         correct => 0
                   4801:                     );
                   4802:     $decrement{'attempts'} = $aggtries;
                   4803:     if ($solvedstatus =~ /^correct/) {
                   4804:         $decrement{'correct'} = 1;
                   4805:     }
                   4806:     if ($aggtries == $totaltries) {
                   4807:         $decrement{'users'} = 1;
                   4808:     }
1.524     raeburn  4809:     foreach my $type (keys(%decrement)) {
1.269     raeburn  4810:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   4811:     }
                   4812:     return;
                   4813: }
                   4814: 
                   4815: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   4816: sub get_last_resets {
1.270     albertel 4817:     my ($symb,$courseid,$partids) =@_;
                   4818:     my %last_resets;
1.269     raeburn  4819:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   4820:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 4821:     my @keys;
                   4822:     foreach my $part (@{$partids}) {
                   4823: 	push(@keys,"$symb\0$part\0resettime");
                   4824:     }
                   4825:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   4826: 				     $cdom,$cname);
                   4827:     foreach my $part (@{$partids}) {
                   4828: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  4829:     }
1.270     albertel 4830:     return %last_resets;
1.269     raeburn  4831: }
                   4832: 
1.251     banghart 4833: # ----------- Handles creating versions for portfolio files as answers
                   4834: sub version_portfiles {
1.343     banghart 4835:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 4836:     my $version_parts = join('|',@$v_flag);
1.343     banghart 4837:     my @returned_keys;
1.255     banghart 4838:     my $parts = join('|', @$parts_graded);
1.277     albertel 4839:     foreach my $key (keys(%$record)) {
1.259     banghart 4840:         my $new_portfiles;
1.263     banghart 4841:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 4842:             my @versioned_portfiles;
1.367     albertel 4843:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  4844:             if (@portfiles) {
                   4845:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   4846:                                                       \@versioned_portfiles);
1.252     banghart 4847:             }
1.343     banghart 4848:             $$record{$key} = join(',',@versioned_portfiles);
                   4849:             push(@returned_keys,$key);
1.251     banghart 4850:         }
1.794     raeburn  4851:     }
                   4852:     return (@returned_keys);
1.305     banghart 4853: }
                   4854: 
1.44      ng       4855: #--------------------------------------------------------------------------------------
                   4856: #
                   4857: #-------------------------- Next few routines handles grading by section or whole class
                   4858: #
                   4859: #--- Javascript to handle grading by section or whole class
1.42      ng       4860: sub viewgrades_js {
                   4861:     my ($request) = shift;
                   4862: 
1.539     riegler  4863:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  4864:     &js_escape(\$alertmsg);
1.597     wenzelju 4865:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       4866:    function writePoint(partid,weight,point) {
1.125     ng       4867: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   4868: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       4869: 	if (point == "textval") {
1.125     ng       4870: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  4871: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4872: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       4873: 		var resetbox = false;
                   4874: 		for (var i=0; i<radioButton.length; i++) {
                   4875: 		    if (radioButton[i].checked) {
                   4876: 			textbox.value = i;
                   4877: 			resetbox = true;
                   4878: 		    }
                   4879: 		}
                   4880: 		if (!resetbox) {
                   4881: 		    textbox.value = "";
                   4882: 		}
                   4883: 		return;
                   4884: 	    }
1.109     matthew  4885: 	    if (parseFloat(point) > parseFloat(weight)) {
                   4886: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4887: 				   ") greater than the weight for the part. Accept?");
                   4888: 		if (resp == false) {
                   4889: 		    textbox.value = "";
                   4890: 		    return;
                   4891: 		}
                   4892: 	    }
1.42      ng       4893: 	    for (var i=0; i<radioButton.length; i++) {
                   4894: 		radioButton[i].checked=false;
1.109     matthew  4895: 		if (parseFloat(point) == i) {
1.42      ng       4896: 		    radioButton[i].checked=true;
                   4897: 		}
                   4898: 	    }
1.41      ng       4899: 
1.42      ng       4900: 	} else {
1.125     ng       4901: 	    textbox.value = parseFloat(point);
1.42      ng       4902: 	}
1.41      ng       4903: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4904: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 4905: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4906: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4907: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4908: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4909: 	    if (saveval != "correct") {
                   4910: 		scorename.value = point;
1.43      ng       4911: 		if (selname[0].selected != true) {
                   4912: 		    selname[0].selected = true;
                   4913: 		}
1.42      ng       4914: 	    }
                   4915: 	}
1.125     ng       4916: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       4917:     }
                   4918: 
                   4919:     function writeRadText(partid,weight) {
1.125     ng       4920: 	var selval   = document.classgrade["SELVAL_"+partid];
                   4921: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      4922:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       4923: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   4924: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       4925: 	    for (var i=0; i<radioButton.length; i++) {
                   4926: 		radioButton[i].checked=false;
                   4927: 
                   4928: 	    }
                   4929: 	    textbox.value = "";
                   4930: 
                   4931: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4932: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4933: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4934: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4935: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4936: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4937: 		if ((saveval != "correct") || override) {
1.42      ng       4938: 		    scorename.value = "";
1.125     ng       4939: 		    if (selval[1].selected) {
                   4940: 			selname[1].selected = true;
                   4941: 		    } else {
                   4942: 			selname[2].selected = true;
                   4943: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   4944: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   4945: 		    }
1.42      ng       4946: 		}
                   4947: 	    }
1.43      ng       4948: 	} else {
                   4949: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4950: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4951: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4952: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4953: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4954: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4955: 		if ((saveval != "correct") || override) {
1.125     ng       4956: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       4957: 		    selname[0].selected = true;
                   4958: 		}
                   4959: 	    }
                   4960: 	}	    
1.42      ng       4961:     }
                   4962: 
                   4963:     function changeSelect(partid,user) {
1.125     ng       4964: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4965: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       4966: 	var point  = textbox.value;
1.125     ng       4967: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       4968: 
1.109     matthew  4969: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4970: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       4971: 	    textbox.value = "";
                   4972: 	    return;
                   4973: 	}
1.109     matthew  4974: 	if (parseFloat(point) > parseFloat(weight)) {
                   4975: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4976: 			       ") greater than the weight of the part. Accept?");
                   4977: 	    if (resp == false) {
                   4978: 		textbox.value = "";
                   4979: 		return;
                   4980: 	    }
                   4981: 	}
1.42      ng       4982: 	selval[0].selected = true;
                   4983:     }
                   4984: 
                   4985:     function changeOneScore(partid,user) {
1.125     ng       4986: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4987: 	if (selval[1].selected || selval[2].selected) {
                   4988: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   4989: 	    if (selval[2].selected) {
                   4990: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   4991: 	    }
1.269     raeburn  4992:         }
1.42      ng       4993:     }
                   4994: 
                   4995:     function resetEntry(numpart) {
                   4996: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       4997: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   4998: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   4999: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   5000: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       5001: 	    for (var i=0; i<radioButton.length; i++) {
                   5002: 		radioButton[i].checked=false;
                   5003: 
                   5004: 	    }
                   5005: 	    textbox.value = "";
                   5006: 	    selval[0].selected = true;
                   5007: 
                   5008: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       5009: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 5010: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       5011: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   5012: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   5013: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   5014: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   5015: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   5016: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       5017: 		if (saveselval == "excused") {
1.43      ng       5018: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       5019: 		} else {
1.43      ng       5020: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       5021: 		}
                   5022: 	    }
1.41      ng       5023: 	}
1.42      ng       5024:     }
                   5025: 
1.41      ng       5026: VIEWJAVASCRIPT
1.42      ng       5027: }
                   5028: 
1.44      ng       5029: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       5030: sub viewgrades {
1.608     www      5031:     my ($request,$symb) = @_;
1.745     raeburn  5032:     my ($is_tool,$toolsymb);
                   5033:     if ($symb =~ /ext\.tool$/) {
                   5034:         $is_tool = 1;
                   5035:         $toolsymb = $symb;
                   5036:     }
1.42      ng       5037:     &viewgrades_js($request);
1.41      ng       5038: 
1.168     albertel 5039:     #need to make sure we have the correct data for later EXT calls, 
                   5040:     #thus invalidate the cache
                   5041:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5042:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5043:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5044:     &Apache::lonnet::clear_EXT_cache_status();
                   5045: 
1.398     albertel 5046:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       5047: 
                   5048:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 5049:     $result.=&jscriptNform($symb);
1.41      ng       5050: 
1.44      ng       5051:     #beginning of class grading form
1.442     banghart 5052:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       5053:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 5054: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       5055: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 5056: 	&build_section_inputs().
1.442     banghart 5057: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       5058: 
1.738     raeburn  5059:     #retrieve selected groups
                   5060:     my (@groups,$group_display);
                   5061:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   5062:     if (grep(/^all$/,@groups)) {
                   5063:         @groups = ('all');
                   5064:     } elsif (grep(/^none$/,@groups)) {
                   5065:         @groups = ('none');
                   5066:     } elsif (@groups > 0) {
                   5067:         $group_display = join(', ',@groups);
                   5068:     }
                   5069: 
                   5070:     my ($common_header,$specific_header,@sections,$section_display);
1.780     raeburn  5071:     if ($env{'request.course.sec'} ne '') {
                   5072:         @sections = ($env{'request.course.sec'});
                   5073:     } else {
                   5074:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   5075:     }
                   5076: 
                   5077: # Check if Save button should be usable
                   5078:     my $disabled = ' disabled="disabled"';
                   5079:     if ($perm{'mgr'}) {
                   5080:         if (grep(/^all$/,@sections)) {
                   5081:             undef($disabled);
                   5082:         } else {
                   5083:             foreach my $sec (@sections) {
                   5084:                 if (&canmodify($sec)) {
                   5085:                     undef($disabled);
                   5086:                     last;
                   5087:                 }
                   5088:             }
                   5089:         }
                   5090:     }
1.738     raeburn  5091:     if (grep(/^all$/,@sections)) {
                   5092:         @sections = ('all');
                   5093:         if ($group_display) {
                   5094:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   5095:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   5096:         } elsif (grep(/^none$/,@groups)) {
                   5097:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   5098:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   5099:         } else {
                   5100: 	    $common_header = &mt('Assign Common Grade to Class');
                   5101:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   5102:         }
                   5103:     } elsif (grep(/^none$/,@sections)) {
                   5104:         @sections = ('none');
                   5105:         if ($group_display) {
                   5106:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   5107:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   5108:         } elsif (grep(/^none$/,@groups)) {
                   5109:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   5110:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   5111:         } else {
                   5112:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   5113: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   5114:         }
                   5115:     } else {
                   5116:         $section_display = join (", ",@sections);
                   5117:         if ($group_display) {
                   5118:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   5119:                                  $section_display,$group_display);
                   5120:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   5121:                                    $section_display,$group_display);
                   5122:         } elsif (grep(/^none$/,@groups)) {
                   5123:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   5124:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   5125:         } else {
                   5126:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   5127: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   5128:         }
                   5129:     }
                   5130:     my %submit_types = &substatus_options();
                   5131:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   5132: 
                   5133:     if ($env{'form.submitonly'} eq 'all') {
                   5134:         $result.= '<h3>'.$common_header.'</h3>';
                   5135:     } else {
1.745     raeburn  5136:         my $text;
                   5137:         if ($is_tool) {
                   5138:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5139:         } else {
                   5140:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5141:         }
                   5142:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 5143:     }
1.738     raeburn  5144:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       5145:     #radio buttons/text box for assigning points for a section or class.
                   5146:     #handles different parts of a problem
1.582     raeburn  5147:     my $res_error;
                   5148:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   5149:     if ($res_error) {
                   5150:         return &navmap_errormsg();
                   5151:     }
1.42      ng       5152:     my %weight = ();
                   5153:     my $ctsparts = 0;
1.45      ng       5154:     my %seen = ();
1.745     raeburn  5155:     my @part_response_id;
                   5156:     if ($is_tool) {
                   5157:         @part_response_id = ([0,'']);
                   5158:     } else {
                   5159:         @part_response_id = &flatten_responseType($responseType);
                   5160:     }
1.375     albertel 5161:     foreach my $part_response_id (@part_response_id) {
                   5162:     	my ($partid,$respid) = @{ $part_response_id };
                   5163: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       5164: 	next if $seen{$partid};
                   5165: 	$seen{$partid}++;
1.42      ng       5166: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   5167: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   5168: 
1.324     albertel 5169: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 5170: 	my $radio.='<table border="0"><tr>';  
1.41      ng       5171: 	my $ctr = 0;
1.42      ng       5172: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 5173: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 5174: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 5175: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       5176: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   5177: 	    $ctr++;
                   5178: 	}
1.485     albertel 5179: 	$radio.='</tr></table>';
                   5180: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   5181: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 5182: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  5183: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   5184:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   5185:             '<select name="SELVAL_'.$partid.'" '.
                   5186:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   5187:                 $weight{$partid}.')"> '.
1.401     albertel 5188: 	    '<option selected="selected"> </option>'.
1.485     albertel 5189: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   5190: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   5191: 	    '</select></td>'.
                   5192:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   5193: 	$line.='<input type="hidden" name="partid_'.
                   5194: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   5195: 	$line.='<input type="hidden" name="weight_'.
                   5196: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   5197: 
                   5198: 	$result.=
                   5199: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   5200: 	    '<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 5201: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       5202: 	$ctsparts++;
1.41      ng       5203:     }
1.474     albertel 5204:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 5205: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 5206:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   5207: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       5208: 
1.44      ng       5209:     #table listing all the students in a section/class
                   5210:     #header of table
1.738     raeburn  5211:     if ($env{'form.submitonly'} eq 'all') {
                   5212:         $result.= '<h3>'.$specific_header.'</h3>';
                   5213:     } else {
1.745     raeburn  5214:         my $text;
                   5215:         if ($is_tool) {
                   5216:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5217:         } else {
                   5218:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5219:         }
                   5220:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  5221:     }
                   5222:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  5223: 	      &Apache::loncommon::start_data_table_header_row().
                   5224: 	      '<th>'.&mt('No.').'</th>'.
                   5225: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  5226:     my $partserror;
                   5227:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5228:     if ($partserror) {
                   5229:         return &navmap_errormsg();
                   5230:     }
1.324     albertel 5231:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  5232:     my @partids = ();
1.41      ng       5233:     foreach my $part (@parts) {
1.745     raeburn  5234: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  5235:         my $narrowtext = &mt('Tries');
                   5236: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  5237: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 5238: 	my ($partid) = &split_part_type($part);
1.524     raeburn  5239:         push(@partids,$partid);
1.628     www      5240: #
                   5241: # FIXME: Looks like $display looks at English text
                   5242: #
1.324     albertel 5243: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       5244: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 5245: 	    $result.='<th>'.
1.697     bisitz   5246: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   5247: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       5248: 	    next;
1.485     albertel 5249: 	    
1.207     albertel 5250: 	} else {
1.485     albertel 5251: 	    if ($display =~ /Problem Status/) {
                   5252: 		my $grade_status_mt = &mt('Grade Status');
                   5253: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   5254: 	    }
                   5255: 	    my $part_mt = &mt('Part:');
                   5256: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       5257: 	}
1.485     albertel 5258: 
1.474     albertel 5259: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       5260:     }
1.474     albertel 5261:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       5262: 
1.270     albertel 5263:     my %last_resets = 
                   5264: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  5265: 
1.41      ng       5266:     #get info for each student
1.44      ng       5267:     #list all the students - with points and grade status
1.738     raeburn  5268:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       5269:     my $ctr = 0;
1.294     albertel 5270:     foreach (sort 
                   5271: 	     {
                   5272: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5273: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5274: 		 }
                   5275: 		 return $a cmp $b;
                   5276: 	     } (keys(%$fullname))) {
1.324     albertel 5277: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  5278: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       5279:     }
1.474     albertel 5280:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       5281:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.780     raeburn  5282:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5283: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  5284:     if ($ctr == 0) {
1.442     banghart 5285:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  5286:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   5287:                 '<span class="LC_warning">';
                   5288:         if ($env{'form.submitonly'} eq 'all') {
                   5289:             if (grep(/^all$/,@sections)) {
                   5290:                 if (grep(/^all$/,@groups)) {
                   5291:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   5292:                                    $stu_status);
                   5293:                 } elsif (grep(/^none$/,@groups)) {
                   5294:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   5295:                                    $stu_status); 
                   5296:                 } else {
                   5297:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5298:                                    $group_display,$stu_status);
                   5299:                 }
                   5300:             } elsif (grep(/^none$/,@sections)) {
                   5301:                 if (grep(/^all$/,@groups)) {
                   5302:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   5303:                                    $stu_status);
                   5304:                 } elsif (grep(/^none$/,@groups)) {
                   5305:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   5306:                                    $stu_status);
                   5307:                 } else {
                   5308:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5309:                                    $group_display,$stu_status);
                   5310:                 }
                   5311:             } else {
                   5312:                 if (grep(/^all$/,@groups)) {
                   5313:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   5314:                                    $section_display,$stu_status);
                   5315:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  5316:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  5317:                                    $section_display,$stu_status);
                   5318:                 } else {
                   5319:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   5320:                                    $section_display,$group_display,$stu_status);
                   5321:                 }
                   5322:             }
                   5323:         } else {
                   5324:             if (grep(/^all$/,@sections)) {
                   5325:                 if (grep(/^all$/,@groups)) {
                   5326:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5327:                                    $stu_status,$submission_status);
                   5328:                 } elsif (grep(/^none$/,@groups)) {
                   5329:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5330:                                    $stu_status,$submission_status);
                   5331:                 } else {
                   5332:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5333:                                    $group_display,$stu_status,$submission_status);
                   5334:                 }
                   5335:             } elsif (grep(/^none$/,@sections)) {
                   5336:                 if (grep(/^all$/,@groups)) {
                   5337:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5338:                                    $stu_status,$submission_status);
                   5339:                 } elsif (grep(/^none$/,@groups)) {
                   5340:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5341:                                    $stu_status,$submission_status);
                   5342:                 } else {
                   5343:                     $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.',
                   5344:                                    $group_display,$stu_status,$submission_status);
                   5345:                 }
                   5346:             } else {
                   5347:                 if (grep(/^all$/,@groups)) {
                   5348: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5349: 	                           $section_display,$stu_status,$submission_status);
                   5350:                 } elsif (grep(/^none$/,@groups)) {
                   5351:                     $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.',
                   5352:                                    $section_display,$stu_status,$submission_status);
                   5353:                 } else {
                   5354:                     $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.',
                   5355:                                    $section_display,$group_display,$stu_status,$submission_status);
                   5356:                 }
                   5357:             }
                   5358:         }
                   5359: 	$result .= '</span><br />';
1.96      albertel 5360:     }
1.41      ng       5361:     return $result;
                   5362: }
                   5363: 
1.738     raeburn  5364: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       5365: sub viewstudentgrade {
1.745     raeburn  5366:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       5367:     my ($uname,$udom) = split(/:/,$student);
                   5368:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  5369:     my $submitonly = $env{'form.submitonly'};
                   5370:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   5371:         my %partstatus = ();
                   5372:         if (ref($parts) eq 'ARRAY') {
                   5373:             foreach my $apart (@{$parts}) {
                   5374:                 my ($part,$type) = &split_part_type($apart);
                   5375:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   5376:                 $status = 'nothing' if ($status eq '');
                   5377:                 $partstatus{$part}      = $status;
                   5378:                 my $subkey = "resource.$part.submitted_by";
                   5379:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   5380:             }
                   5381:             my $submitted = 0;
                   5382:             my $graded = 0;
                   5383:             my $incorrect = 0;
                   5384:             foreach my $key (keys(%partstatus)) {
                   5385:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   5386:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   5387:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   5388: 
                   5389:                 my $partid = (split(/\./,$key))[1];
                   5390:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   5391:                     $submitted = 0;
                   5392:                 }
                   5393:             }
                   5394:             return if (!$submitted && ($submitonly eq 'yes' ||
                   5395:                                        $submitonly eq 'incorrect' ||
                   5396:                                        $submitonly eq 'graded'));
                   5397:             return if (!$graded && ($submitonly eq 'graded'));
                   5398:             return if (!$incorrect && $submitonly eq 'incorrect');
                   5399:         }
                   5400:     }
                   5401:     if ($submitonly eq 'queued') {
                   5402:         my ($cdom,$cnum) = split(/_/,$courseid);
                   5403:         my %queue_status =
                   5404:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   5405:                                                     $udom,$uname);
                   5406:         return if (!defined($queue_status{'gradingqueue'}));
                   5407:     }
                   5408:     $$ctr++;
                   5409:     my %aggregates = ();
1.474     albertel 5410:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  5411: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   5412: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       5413: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 5414: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 5415: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 5416:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 5417:     foreach my $apart (@$parts) {
                   5418: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       5419: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 5420:         $result.='<td align="center">';
1.269     raeburn  5421:         my ($aggtries,$totaltries);
                   5422:         unless (exists($aggregates{$part})) {
1.270     albertel 5423: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   5424: 	    $aggtries = $totaltries;
1.269     raeburn  5425:             if ($$last_resets{$part}) {  
1.270     albertel 5426:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   5427: 					   $part);
                   5428:             }
1.269     raeburn  5429:             $result.='<input type="hidden" name="'.
                   5430:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   5431:             $result.='<input type="hidden" name="'.
                   5432:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   5433:             $aggregates{$part} = 1;
                   5434:         }
1.41      ng       5435: 	if ($type eq 'awarded') {
1.320     albertel 5436: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       5437: 	    $result.='<input type="hidden" name="'.
1.89      albertel 5438: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 5439: 	    $result.='<input type="text" name="'.
1.89      albertel 5440: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   5441:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       5442: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       5443: 	} elsif ($type eq 'solved') {
                   5444: 	    my ($status,$foo)=split(/_/,$score,2);
                   5445: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 5446: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 5447: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 5448: 	    $result.='&nbsp;<select name="'.
1.89      albertel 5449: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   5450:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 5451: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   5452: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   5453: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       5454: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       5455: 	} else {
                   5456: 	    $result.='<input type="hidden" name="'.
                   5457: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   5458: 		    "\n";
1.233     albertel 5459: 	    $result.='<input type="text" name="'.
1.122     ng       5460: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   5461: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       5462: 	}
                   5463:     }
1.474     albertel 5464:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       5465:     return $result;
1.38      ng       5466: }
                   5467: 
1.44      ng       5468: #--- change scores for all the students in a section/class
                   5469: #    record does not get update if unchanged
1.38      ng       5470: sub editgrades {
1.608     www      5471:     my ($request,$symb) = @_;
1.745     raeburn  5472:     my $toolsymb;
                   5473:     if ($symb =~ /ext\.tool$/) {
                   5474:         $toolsymb = $symb;
                   5475:     }
1.41      ng       5476: 
1.433     banghart 5477:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 5478:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  5479:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       5480: 
1.477     albertel 5481:     my $result= &Apache::loncommon::start_data_table().
                   5482: 	&Apache::loncommon::start_data_table_header_row().
                   5483: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   5484: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       5485:     my %scoreptr = (
                   5486: 		    'correct'  =>'correct_by_override',
                   5487: 		    'incorrect'=>'incorrect_by_override',
                   5488: 		    'excused'  =>'excused',
                   5489: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  5490:                     'credited' =>'credit_attempted',
1.43      ng       5491: 		    'nothing'  => '',
                   5492: 		    );
1.257     albertel 5493:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       5494: 
1.798     raeburn  5495:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5496:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5497:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   5498: 
1.44      ng       5499:     my (@partid);
                   5500:     my %weight = ();
1.54      albertel 5501:     my %columns = ();
1.44      ng       5502:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 5503: 
1.582     raeburn  5504:     my $partserror;
                   5505:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5506:     if ($partserror) {
                   5507:         return &navmap_errormsg();
                   5508:     }
1.54      albertel 5509:     my $header;
1.257     albertel 5510:     while ($ctr < $env{'form.totalparts'}) {
                   5511: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  5512: 	push(@partid,$partid);
1.257     albertel 5513: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       5514: 	$ctr++;
1.54      albertel 5515:     }
1.324     albertel 5516:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  5517:     my $totcolspan = 0;
1.54      albertel 5518:     foreach my $partid (@partid) {
1.478     albertel 5519: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   5520: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 5521: 	$columns{$partid}=2;
                   5522: 	foreach my $stores (@parts) {
                   5523: 	    my ($part,$type) = &split_part_type($stores);
                   5524: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   5525: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  5526: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  5527: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  5528:             my $narrowtext = &mt('Tries');
                   5529: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   5530: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   5531: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 5532: 	    $columns{$partid}+=2;
                   5533: 	}
1.748     raeburn  5534:         $totcolspan += $columns{$partid};
1.54      albertel 5535:     }
                   5536:     foreach my $partid (@partid) {
1.324     albertel 5537: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 5538: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   5539: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   5540: 	    '</th>';
1.54      albertel 5541: 
1.44      ng       5542:     }
1.477     albertel 5543:     $result .= &Apache::loncommon::end_data_table_header_row().
                   5544: 	&Apache::loncommon::start_data_table_header_row().
                   5545: 	$header.
                   5546: 	&Apache::loncommon::end_data_table_header_row();
                   5547:     my @noupdate;
1.126     ng       5548:     my ($updateCtr,$noupdateCtr) = (1,1);
1.798     raeburn  5549:     my ($got_types,%queueable,%pbsave,%skip_passback);
1.257     albertel 5550:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   5551: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 5552: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       5553: 	my %newrecord;
                   5554: 	my $updateflag = 0;
1.108     albertel 5555: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  5556: 	my $canmodify = &canmodify($usec);
                   5557: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   5558: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   5559: 	if (!$canmodify) {
1.477     albertel 5560: 	    push(@noupdate,
1.748     raeburn  5561: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   5562: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 5563: 	    next;
                   5564: 	}
1.269     raeburn  5565:         my %aggregate = ();
                   5566:         my $aggregateflag = 0;
1.281     albertel 5567: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.798     raeburn  5568:         my (%weights,%awardeds,%excuseds);
1.44      ng       5569: 	foreach (@partid) {
1.257     albertel 5570: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 5571: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   5572: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 5573: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   5574: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 5575: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   5576: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.798     raeburn  5577:             $awardeds{$symb}{$_} = $partial;
1.44      ng       5578: 	    my $score;
                   5579: 	    if ($partial eq '') {
1.257     albertel 5580: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       5581: 	    } elsif ($partial > 0) {
                   5582: 		$score = 'correct_by_override';
                   5583: 	    } elsif ($partial == 0) {
                   5584: 		$score = 'incorrect_by_override';
                   5585: 	    }
1.257     albertel 5586: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       5587: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   5588: 
1.292     albertel 5589: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   5590: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5591: 	    if ($dropMenu eq 'reset status' &&
                   5592: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 5593: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       5594: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   5595: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 5596: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       5597: 		$updateflag = 1;
1.269     raeburn  5598:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   5599:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   5600:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   5601:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   5602:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5603:                     $aggregateflag = 1;
                   5604:                 }
1.139     albertel 5605: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   5606: 		$updateflag = 1;
                   5607: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   5608: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   5609: 		$rec_update++;
1.125     ng       5610: 	    }
                   5611: 
1.93      albertel 5612: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       5613: 		'<td align="center">'.$awarded.
                   5614: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 5615: 
1.54      albertel 5616: 
                   5617: 	    my $partid=$_;
1.798     raeburn  5618:             if ($score eq 'excused') {
                   5619:                 $excuseds{$symb}{$partid} = 1;
                   5620:             } else {
                   5621:                 $excuseds{$symb}{$partid} = '';
                   5622:             }
1.54      albertel 5623: 	    foreach my $stores (@parts) {
                   5624: 		my ($part,$type) = &split_part_type($stores);
                   5625: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   5626: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 5627: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   5628: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 5629: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   5630: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 5631: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 5632: 		    $updateflag=1;
                   5633: 		}
1.93      albertel 5634: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 5635: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   5636: 	    }
1.44      ng       5637: 	}
1.477     albertel 5638: 	$line.="\n";
1.301     albertel 5639: 
1.44      ng       5640: 	if ($updateflag) {
                   5641: 	    $count++;
1.257     albertel 5642: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 5643: 				    $udom,$uname);
1.301     albertel 5644: 
                   5645: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   5646: 					      $cnum,$udom,$uname)) {
                   5647: 		# need to figure out if should be in queue.
                   5648: 		my %record =  
                   5649: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   5650: 					     $udom,$uname);
                   5651: 		my $all_graded = 1;
                   5652: 		my $none_graded = 1;
1.786     raeburn  5653:                 unless ($got_types) {
                   5654:                     my $error;
                   5655:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   5656:                     unless ($error) {
                   5657:                         foreach my $part (@parts) {
                   5658:                             if (ref($resptype->{$part}) eq 'HASH') {
                   5659:                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   5660:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   5661:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   5662:                                         $queueable{$part} = 1;
                   5663:                                         last;
                   5664:                                     }
                   5665:                                 }
                   5666:                             }
                   5667:                         }
                   5668:                     }
                   5669:                     $got_types = 1;
                   5670:                 }
1.301     albertel 5671: 		foreach my $part (@parts) {
1.786     raeburn  5672:                     if ($queueable{$part}) {
                   5673: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   5674: 			    $all_graded = 0;
                   5675: 		        } else {
                   5676: 			    $none_graded = 0;
                   5677: 		        }
1.301     albertel 5678: 		    }
1.786     raeburn  5679:                 }
1.301     albertel 5680: 		if ($all_graded || $none_graded) {
                   5681: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   5682: 							   $symb,$cdom,$cnum,
                   5683: 							   $udom,$uname);
                   5684: 		}
                   5685: 	    }
                   5686: 
1.477     albertel 5687: 	    $result.=&Apache::loncommon::start_data_table_row().
                   5688: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   5689: 		&Apache::loncommon::end_data_table_row();
1.126     ng       5690: 	    $updateCtr++;
1.798     raeburn  5691:             if (keys(%needpb)) {
                   5692:                 $weights{$symb} = \%weight;
1.802     raeburn  5693:                 &process_passbacks('editgrades',[$symb],$cdom,$cnum,$udom,$uname,$usec,\%weights,
1.798     raeburn  5694:                                    \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   5695:             }
1.93      albertel 5696: 	} else {
1.477     albertel 5697: 	    push(@noupdate,
                   5698: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       5699: 	    $noupdateCtr++;
1.44      ng       5700: 	}
1.269     raeburn  5701:         if ($aggregateflag) {
                   5702:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 5703: 				  $cdom,$cnum);
1.269     raeburn  5704:         }
1.93      albertel 5705:     }
1.477     albertel 5706:     if (@noupdate) {
1.748     raeburn  5707:         my $numcols=$totcolspan+2;
1.477     albertel 5708: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 5709: 	    '<td align="center" colspan="'.$numcols.'">'.
                   5710: 	    &mt('No Changes Occurred For the Students Below').
                   5711: 	    '</td>'.
1.477     albertel 5712: 	    &Apache::loncommon::end_data_table_row();
                   5713: 	foreach my $line (@noupdate) {
                   5714: 	    $result.=
                   5715: 		&Apache::loncommon::start_data_table_row().
                   5716: 		$line.
                   5717: 		&Apache::loncommon::end_data_table_row();
                   5718: 	}
1.44      ng       5719:     }
1.614     www      5720:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 5721:     my $msg = '<p><b>'.
                   5722: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   5723: 	    $rec_update,$count).'</b><br />'.
                   5724: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   5725: 	'</b></p>';
1.44      ng       5726:     return $title.$msg.$result;
1.5       albertel 5727: }
1.54      albertel 5728: 
                   5729: sub split_part_type {
                   5730:     my ($partstr) = @_;
                   5731:     my ($temp,@allparts)=split(/_/,$partstr);
                   5732:     my $type=pop(@allparts);
1.439     albertel 5733:     my $part=join('_',@allparts);
1.54      albertel 5734:     return ($part,$type);
                   5735: }
                   5736: 
1.44      ng       5737: #------------- end of section for handling grading by section/class ---------
                   5738: #
                   5739: #----------------------------------------------------------------------------
                   5740: 
1.5       albertel 5741: 
1.44      ng       5742: #----------------------------------------------------------------------------
                   5743: #
                   5744: #-------------------------- Next few routines handles grading by csv upload
                   5745: #
                   5746: #--- Javascript to handle csv upload
1.27      albertel 5747: sub csvupload_javascript_reverse_associate {
1.743     raeburn  5748:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5749:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5750:   &js_escape(\$error1);
                   5751:   &js_escape(\$error2);
1.27      albertel 5752:   return(<<ENDPICK);
                   5753:   function verify(vf) {
                   5754:     var foundsomething=0;
                   5755:     var founduname=0;
1.243     albertel 5756:     var foundID=0;
1.743     raeburn  5757:     var foundclicker=0;
1.27      albertel 5758:     for (i=0;i<=vf.nfields.value;i++) {
                   5759:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5760:       if (i==0 && tw!=0) { foundID=1; }
                   5761:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  5762:       if (i==2 && tw!=0) { foundclicker=1; }
                   5763:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 5764:     }
1.743     raeburn  5765:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 5766: 	alert('$error1');
                   5767: 	return;
1.27      albertel 5768:     }
                   5769:     if (foundsomething==0) {
1.246     albertel 5770: 	alert('$error2');
                   5771: 	return;
1.27      albertel 5772:     }
                   5773:     vf.submit();
                   5774:   }
                   5775:   function flip(vf,tf) {
                   5776:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5777:     var i;
                   5778:     for (i=0;i<=vf.nfields.value;i++) {
                   5779:       //can not pick the same destination field for both name and domain
                   5780:       if (((i ==0)||(i ==1)) && 
                   5781:           ((tf==0)||(tf==1)) && 
                   5782:           (i!=tf) &&
                   5783:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5784:         eval('vf.f'+i+'.selectedIndex=0;')
                   5785:       }
                   5786:     }
                   5787:   }
                   5788: ENDPICK
                   5789: }
                   5790: 
                   5791: sub csvupload_javascript_forward_associate {
1.743     raeburn  5792:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5793:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5794:   &js_escape(\$error1);
                   5795:   &js_escape(\$error2);
1.27      albertel 5796:   return(<<ENDPICK);
                   5797:   function verify(vf) {
                   5798:     var foundsomething=0;
                   5799:     var founduname=0;
1.243     albertel 5800:     var foundID=0;
1.743     raeburn  5801:     var foundclicker=0;
1.27      albertel 5802:     for (i=0;i<=vf.nfields.value;i++) {
                   5803:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5804:       if (tw==1) { foundID=1; }
                   5805:       if (tw==2) { founduname=1; }
1.745     raeburn  5806:       if (tw==3) { foundclicker=1; }
1.743     raeburn  5807:       if (tw>4) { foundsomething=1; }
1.27      albertel 5808:     }
1.743     raeburn  5809:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 5810: 	alert('$error1');
                   5811: 	return;
1.27      albertel 5812:     }
                   5813:     if (foundsomething==0) {
1.246     albertel 5814: 	alert('$error2');
                   5815: 	return;
1.27      albertel 5816:     }
                   5817:     vf.submit();
                   5818:   }
                   5819:   function flip(vf,tf) {
                   5820:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5821:     var i;
                   5822:     //can not pick the same destination field twice
                   5823:     for (i=0;i<=vf.nfields.value;i++) {
                   5824:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5825:         eval('vf.f'+i+'.selectedIndex=0;')
                   5826:       }
                   5827:     }
                   5828:   }
                   5829: ENDPICK
                   5830: }
                   5831: 
1.26      albertel 5832: sub csvuploadmap_header {
1.324     albertel 5833:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       5834:     my $javascript;
1.257     albertel 5835:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       5836: 	$javascript=&csvupload_javascript_reverse_associate();
                   5837:     } else {
                   5838: 	$javascript=&csvupload_javascript_forward_associate();
                   5839:     }
1.45      ng       5840: 
1.418     albertel 5841:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      5842:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   5843:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   5844:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   5845:     my $reverse=&mt("Reverse Association");
1.41      ng       5846:     $request->print(<<ENDPICK);
1.632     www      5847: <br />
                   5848: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 5849: <input type="hidden" name="associate"  value="" />
                   5850: <input type="hidden" name="phase"      value="three" />
                   5851: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 5852: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   5853: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 5854: <input type="hidden" name="upfile_associate" 
1.257     albertel 5855:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 5856: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 5857: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 5858: <hr />
                   5859: ENDPICK
1.597     wenzelju 5860:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       5861:     return '';
1.26      albertel 5862: 
                   5863: }
                   5864: 
                   5865: sub csvupload_fields {
1.582     raeburn  5866:     my ($symb,$errorref) = @_;
1.745     raeburn  5867:     my $toolsymb;
                   5868:     if ($symb =~ /ext\.tool$/) {
                   5869:         $toolsymb = $symb;
                   5870:     }
1.582     raeburn  5871:     my (@parts) = &getpartlist($symb,$errorref);
                   5872:     if (ref($errorref)) {
                   5873:         if ($$errorref) {
                   5874:             return;
                   5875:         }
                   5876:     }
                   5877: 
1.556     weissno  5878:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 5879: 		['username','Student Username'],
1.743     raeburn  5880: 		['clicker','Clicker ID'],
1.243     albertel 5881: 		['domain','Student Domain']);
1.324     albertel 5882:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       5883:     foreach my $part (sort(@parts)) {
                   5884: 	my @datum;
1.745     raeburn  5885: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       5886: 	my $name=$part;
1.745     raeburn  5887: 	if (!$display) { $display = $name; }
1.41      ng       5888: 	@datum=($name,$display);
1.244     albertel 5889: 	if ($name=~/^stores_(.*)_awarded/) {
                   5890: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   5891: 	}
1.41      ng       5892: 	push(@fields,\@datum);
                   5893:     }
                   5894:     return (@fields);
1.26      albertel 5895: }
                   5896: 
                   5897: sub csvuploadmap_footer {
1.41      ng       5898:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   5899:     my $buttontext = &mt('Assign Grades');
1.41      ng       5900:     $request->print(<<ENDPICK);
1.26      albertel 5901: </table>
                   5902: <input type="hidden" name="nfields" value="$i" />
                   5903: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   5904: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 5905: </form>
                   5906: ENDPICK
                   5907: }
                   5908: 
1.283     albertel 5909: sub checkforfile_js {
1.638     www      5910:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  5911:     &js_escape(\$alertmsg);
1.597     wenzelju 5912:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       5913:     function checkUpload(formname) {
                   5914: 	if (formname.upfile.value == "") {
1.539     riegler  5915: 	    alert("$alertmsg");
1.86      ng       5916: 	    return false;
                   5917: 	}
                   5918: 	formname.submit();
                   5919:     }
                   5920: CSVFORMJS
1.283     albertel 5921:     return $result;
                   5922: }
                   5923: 
                   5924: sub upcsvScores_form {
1.608     www      5925:     my ($request,$symb) = @_;
1.283     albertel 5926:     if (!$symb) {return '';}
                   5927:     my $result=&checkforfile_js();
1.632     www      5928:     $result.=&Apache::loncommon::start_data_table().
                   5929:              &Apache::loncommon::start_data_table_header_row().
                   5930:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   5931:              &Apache::loncommon::end_data_table_header_row().
                   5932:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      5933:     my $upload=&mt("Upload Scores");
1.86      ng       5934:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 5935:     my $ignore=&mt('Ignore First Line');
1.418     albertel 5936:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       5937:     $result.=<<ENDUPFORM;
1.106     albertel 5938: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       5939: <input type="hidden" name="symb" value="$symb" />
                   5940: <input type="hidden" name="command" value="csvuploadmap" />
                   5941: $upfile_select
1.589     bisitz   5942: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       5943: </form>
                   5944: ENDUPFORM
1.370     www      5945:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      5946:                            &mt("How do I create a CSV file from a spreadsheet")).
                   5947:              '</td>'.
                   5948:             &Apache::loncommon::end_data_table_row().
                   5949:             &Apache::loncommon::end_data_table();
1.86      ng       5950:     return $result;
                   5951: }
                   5952: 
                   5953: 
1.26      albertel 5954: sub csvuploadmap {
1.768     raeburn  5955:     my ($request,$symb) = @_;
1.41      ng       5956:     if (!$symb) {return '';}
1.72      ng       5957: 
1.41      ng       5958:     my $datatoken;
1.257     albertel 5959:     if (!$env{'form.datatoken'}) {
1.41      ng       5960: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 5961:     } else {
1.742     raeburn  5962: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5963:         if ($datatoken ne '') {
                   5964: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5965:         }
1.26      albertel 5966:     }
1.41      ng       5967:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 5968:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       5969:     my ($i,$keyfields);
                   5970:     if (@records) {
1.582     raeburn  5971:         my $fieldserror;
                   5972: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   5973:         if ($fieldserror) {
                   5974:             $request->print(&navmap_errormsg());
                   5975:             return;
                   5976:         }
1.257     albertel 5977: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       5978: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   5979: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   5980: 							  \@fields);
                   5981: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   5982: 	    chop($keyfields);
                   5983: 	} else {
                   5984: 	    unshift(@fields,['none','']);
                   5985: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   5986: 							    \@fields);
1.311     banghart 5987:             foreach my $rec (@records) {
                   5988:                 my %temp = &Apache::loncommon::record_sep($rec);
                   5989:                 if (%temp) {
                   5990:                     $keyfields=join(',',sort(keys(%temp)));
                   5991:                     last;
                   5992:                 }
                   5993:             }
1.41      ng       5994: 	}
                   5995:     }
                   5996:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       5997: 
1.41      ng       5998:     return '';
1.27      albertel 5999: }
                   6000: 
1.246     albertel 6001: sub csvuploadoptions {
1.608     www      6002:     my ($request,$symb)= @_;
1.632     www      6003:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 6004:     $request->print(<<ENDPICK);
                   6005: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   6006: <input type="hidden" name="command"    value="csvuploadassign" />
                   6007: <p>
                   6008: <label>
                   6009:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      6010:    $overwrite
1.246     albertel 6011: </label>
                   6012: </p>
                   6013: ENDPICK
                   6014:     my %fields=&get_fields();
                   6015:     if (!defined($fields{'domain'})) {
1.257     albertel 6016: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      6017: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 6018:     }
1.257     albertel 6019:     foreach my $key (sort(keys(%env))) {
1.246     albertel 6020: 	if ($key !~ /^form\.(.*)$/) { next; }
                   6021: 	my $cleankey=$1;
                   6022: 	if ($cleankey eq 'command') { next; }
                   6023: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 6024: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 6025:     }
                   6026:     # FIXME do a check for any duplicated user ids...
                   6027:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   6028:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 6029: <hr /></form>'."\n");
1.246     albertel 6030:     return '';
                   6031: }
                   6032: 
                   6033: sub get_fields {
                   6034:     my %fields;
1.257     albertel 6035:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   6036:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   6037: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   6038: 	    if ($env{'form.f'.$i} ne 'none') {
                   6039: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       6040: 	    }
                   6041: 	} else {
1.257     albertel 6042: 	    if ($env{'form.f'.$i} ne 'none') {
                   6043: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       6044: 	    }
                   6045: 	}
1.27      albertel 6046:     }
1.246     albertel 6047:     return %fields;
                   6048: }
                   6049: 
                   6050: sub csvuploadassign {
1.766     raeburn  6051:     my ($request,$symb) = @_;
1.246     albertel 6052:     if (!$symb) {return '';}
1.345     bowersj2 6053:     my $error_msg = '';
1.742     raeburn  6054:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   6055:     if ($datatoken ne '') { 
                   6056:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   6057:     }
1.246     albertel 6058:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   6059:     my %fields=&get_fields();
1.257     albertel 6060:     my $courseid=$env{'request.course.id'};
1.798     raeburn  6061:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6062:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.97      albertel 6063:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 6064:     my @notallowed;
1.41      ng       6065:     my @skipped;
1.657     raeburn  6066:     my @warnings;
1.41      ng       6067:     my $countdone=0;
1.798     raeburn  6068:     my @parts;
                   6069:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
                   6070:     my $passback;
                   6071:     if (keys(%needpb)) {
                   6072:         $passback = 1;
                   6073:         my $navmap = Apache::lonnavmaps::navmap->new();
                   6074:         if (ref($navmap)) {
                   6075:             my $res = $navmap->getBySymb($symb);
                   6076:             if (ref($res)) {
                   6077:                 my $partlist = $res->parts();
                   6078:                 if (ref($partlist) eq 'ARRAY') {
                   6079:                     @parts = sort(@{$partlist});
                   6080:                 }
                   6081:             }
                   6082:         } else {
                   6083:             return &navmap_errormsg();
                   6084:         }
                   6085:     }
                   6086:     my (%skip_passback,%pbsave,%weights,%awardeds,%excuseds);
                   6087: 
1.41      ng       6088:     foreach my $grade (@gradedata) {
                   6089: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 6090: 	my $domain;
                   6091: 	if ($entries{$fields{'domain'}}) {
                   6092: 	    $domain=$entries{$fields{'domain'}};
                   6093: 	} else {
1.257     albertel 6094: 	    $domain=$env{'form.default_domain'};
1.246     albertel 6095: 	}
1.243     albertel 6096: 	$domain=~s/\s//g;
1.41      ng       6097: 	my $username=$entries{$fields{'username'}};
1.160     albertel 6098: 	$username=~s/\s//g;
1.243     albertel 6099: 	if (!$username) {
                   6100: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 6101: 	    $id=~s/\s//g;
1.737     raeburn  6102:             if ($id ne '') {
                   6103: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   6104: 	        $username=$ids{$id};
                   6105:             } else {
                   6106:                 if ($entries{$fields{'clicker'}}) {
                   6107:                     my $clicker = $entries{$fields{'clicker'}};
                   6108:                     $clicker=~s/\s//g;
                   6109:                     if ($clicker ne '') {
                   6110:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   6111:                         if ($clickers{$clicker} ne '') {  
                   6112:                             my $match = 0;
                   6113:                             my @inclass;
                   6114:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   6115:                                 if (exists($$classlist{"$poss:$domain"})) {
                   6116:                                     $username = $poss;
                   6117:                                     push(@inclass,$poss);
                   6118:                                     $match ++;
                   6119:                                     
                   6120:                                 }
                   6121:                             }
                   6122:                             if ($match > 1) {
                   6123:                                 undef($username); 
                   6124:                                 $request->print('<p class="LC_warning">'.
                   6125:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   6126:                                                 $clicker,join(', ',@inclass)).'</p>');
                   6127:                             }
                   6128:                         }
                   6129:                     }
                   6130:                 }
                   6131:             }
1.243     albertel 6132: 	}
1.41      ng       6133: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 6134: 	    my $id=$entries{$fields{'ID'}};
                   6135: 	    $id=~s/\s//g;
1.737     raeburn  6136:             my $clicker = $entries{$fields{'clicker'}};
                   6137:             $clicker=~s/\s//g;
                   6138:             if ($clicker) {
                   6139:                 push(@skipped,"$clicker:$domain");
                   6140: 	    } elsif ($id) {
1.247     albertel 6141: 		push(@skipped,"$id:$domain");
                   6142: 	    } else {
                   6143: 		push(@skipped,"$username:$domain");
                   6144: 	    }
1.41      ng       6145: 	    next;
                   6146: 	}
1.108     albertel 6147: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 6148: 	if (!&canmodify($usec)) {
                   6149: 	    push(@notallowed,"$username:$domain");
                   6150: 	    next;
                   6151: 	}
1.244     albertel 6152: 	my %points;
1.41      ng       6153: 	my %grades;
                   6154: 	foreach my $dest (keys(%fields)) {
1.244     albertel 6155: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   6156: 		$dest eq 'domain') { next; }
                   6157: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   6158: 	    if ($dest=~/stores_(.*)_points/) {
                   6159: 		my $part=$1;
                   6160: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6161: 					      $symb,$domain,$username);
1.798     raeburn  6162:                 $weights{$symb}{$part} = $wgt;
1.345     bowersj2 6163:                 if ($wgt) {
                   6164:                     $entries{$fields{$dest}}=~s/\s//g;
                   6165:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.798     raeburn  6166:                     if ($passback) {
                   6167:                         $awardeds{$symb}{$part} = $pcr;
                   6168:                         $excuseds{$symb}{$part} = '';
                   6169:                     }
1.463     albertel 6170:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   6171:                                           : 'correct_by_override';
1.638     www      6172:                     if ($pcr>1) {
1.657     raeburn  6173:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      6174:                     }
1.345     bowersj2 6175:                     $grades{"resource.$part.awarded"}=$pcr;
                   6176:                     $grades{"resource.$part.solved"}=$award;
                   6177:                     $points{$part}=1;
                   6178:                 } else {
                   6179:                     $error_msg = "<br />" .
                   6180:                         &mt("Some point values were assigned"
                   6181:                             ." for problems with a weight "
                   6182:                             ."of zero. These values were "
                   6183:                             ."ignored.");
                   6184:                 }
1.244     albertel 6185: 	    } else {
                   6186: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   6187: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   6188: 		my $store_key=$dest;
1.798     raeburn  6189:                 if ($passback) {
                   6190:                     if ($store_key=~/stores_(.*)_(awarded|solved)/) {
                   6191:                         my ($part,$key) = ($1,$2);
                   6192:                         unless ((ref($weights{$symb}) eq 'HASH') && (exists($weights{$symb}{$part}))) {
                   6193:                             $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6194:                                                                           $symb,$domain,$username);
                   6195:                         }
                   6196:                         if ($key eq 'awarded') {
                   6197:                             $awardeds{$symb}{$part} = $entries{$fields{$dest}};
                   6198:                         } elsif ($key eq 'solved') {
                   6199:                             if ($entries{$fields{$dest}} =~ /^excused/) {
                   6200:                                 $excuseds{$symb}{$part} = 1;
                   6201:                             }
                   6202:                         }
                   6203:                     }
                   6204:                 }
1.244     albertel 6205: 		$store_key=~s/^stores/resource/;
                   6206: 		$store_key=~s/_/\./g;
                   6207: 		$grades{$store_key}=$entries{$fields{$dest}};
                   6208: 	    }
1.41      ng       6209: 	}
1.766     raeburn  6210: 	if (! %grades) {
1.508     www      6211:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   6212:         } else {
                   6213: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   6214: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 6215: 					   $env{'request.course.id'},
                   6216: 					   $domain,$username);
1.508     www      6217: 	   if ($result eq 'ok') {
1.627     www      6218: # Successfully stored
1.508     www      6219: 	      $request->print('.');
1.627     www      6220: # Remove from grading queue
1.798     raeburn  6221:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,$cnum,
1.801     raeburn  6222: 						     $domain,$username);
1.627     www      6223:               $countdone++;
1.798     raeburn  6224:               if ($passback) {
                   6225:                   my @parts_in_upload;
                   6226:                   if (ref($weights{$symb}) eq 'HASH') {
                   6227:                       @parts_in_upload = sort(keys(%{$weights{$symb}}));
                   6228:                   }
                   6229:                   my @diffs = &Apache::loncommon::compare_arrays(\@parts_in_upload,\@parts);
                   6230:                   if (@diffs > 0) {
                   6231:                       my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$username);
                   6232:                       foreach my $part (@parts) {
                   6233:                           next if (grep(/^\Q$part\E$/,@parts_in_upload));
                   6234:                           $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6235:                                                                         $symb,$domain,$username);
                   6236:                           if ($record{"resource.$part.solved"} =~/^excused/) {
                   6237:                               $excuseds{$symb}{$part} = 1;
                   6238:                           } else {
                   6239:                               $excuseds{$symb}{$part} = '';
                   6240:                           }
                   6241:                           $awardeds{$symb}{$part} = $record{"resource.$part.awarded"};
                   6242:                       }
                   6243:                   }
1.802     raeburn  6244:                   &process_passbacks('csvupload',[$symb],$cdom,$cnum,$domain,$username,$usec,\%weights,
1.798     raeburn  6245:                                      \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
                   6246:               }
1.627     www      6247:            } else {
1.508     www      6248: 	      $request->print("<p><span class=\"LC_error\">".
                   6249:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   6250:                                   "$username:$domain",$result)."</span></p>");
                   6251: 	   }
                   6252: 	   $request->rflush();
                   6253:         }
1.41      ng       6254:     }
1.570     www      6255:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  6256:     if (@warnings) {
                   6257:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   6258:         $request->print(join(', ',@warnings));
                   6259:     }
1.41      ng       6260:     if (@skipped) {
1.571     www      6261: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   6262:         $request->print(join(', ',@skipped));
1.106     albertel 6263:     }
                   6264:     if (@notallowed) {
1.571     www      6265: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   6266: 	$request->print(join(', ',@notallowed));
1.41      ng       6267:     }
1.106     albertel 6268:     $request->print("<br />\n");
1.345     bowersj2 6269:     return $error_msg;
1.26      albertel 6270: }
1.44      ng       6271: #------------- end of section for handling csv file upload ---------
                   6272: #
                   6273: #-------------------------------------------------------------------
                   6274: #
1.122     ng       6275: #-------------- Next few routines handle grading by page/sequence
1.72      ng       6276: #
                   6277: #--- Select a page/sequence and a student to grade
1.68      ng       6278: sub pickStudentPage {
1.608     www      6279:     my ($request,$symb) = @_;
1.68      ng       6280: 
1.539     riegler  6281:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  6282:     &js_escape(\$alertmsg);
1.597     wenzelju 6283:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       6284: 
                   6285: function checkPickOne(formname) {
1.76      ng       6286:     if (radioSelection(formname.student) == null) {
1.539     riegler  6287: 	alert("$alertmsg");
1.68      ng       6288: 	return;
                   6289:     }
1.125     ng       6290:     ptr = pullDownSelection(formname.selectpage);
                   6291:     formname.page.value = formname["page"+ptr].value;
                   6292:     formname.title.value = formname["title"+ptr].value;
1.68      ng       6293:     formname.submit();
                   6294: }
                   6295: 
                   6296: LISTJAVASCRIPT
1.118     ng       6297:     &commonJSfunctions($request);
1.608     www      6298: 
1.257     albertel 6299:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6300:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6301:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  6302:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       6303: 
1.398     albertel 6304:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 6305: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       6306: 
1.80      ng       6307:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  6308:     my $map_error;
                   6309:     my ($titles,$symbx) = &getSymbMap($map_error);
                   6310:     if ($map_error) {
                   6311:         $request->print(&navmap_errormsg());
                   6312:         return; 
                   6313:     }
1.137     albertel 6314:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   6315: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   6316: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   6317: 
                   6318:     # Collection of hidden fields
1.70      ng       6319:     my $ctr=0;
1.68      ng       6320:     foreach (@$titles) {
1.700     bisitz   6321:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   6322:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   6323:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   6324:         $ctr++;
1.68      ng       6325:     }
1.700     bisitz   6326:     $result.='<input type="hidden" name="page" />'."\n".
                   6327:         '<input type="hidden" name="title" />'."\n";
                   6328: 
                   6329:     $result.=&build_section_inputs();
                   6330:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   6331:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   6332: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   6333: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 6334: 
1.700     bisitz   6335:     # Show grading options
                   6336:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   6337:     my $select = '<select name="selectpage">'."\n";
1.70      ng       6338:     $ctr=0;
                   6339:     foreach (@$titles) {
                   6340: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   6341: 	$select.='<option value="'.$ctr.'"'.
                   6342: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   6343: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       6344: 	$ctr++;
                   6345:     }
1.700     bisitz   6346:     $select.= '</select>';
1.68      ng       6347: 
1.700     bisitz   6348:     $result.=
                   6349:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   6350:        .$select
                   6351:        .&Apache::lonhtmlcommon::row_closure();
                   6352: 
                   6353:     $result.=
                   6354:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   6355:        .'<label><input type="radio" name="vProb" value="no"'
                   6356:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   6357:        .'<label><input type="radio" name="vProb" value="yes" />'
                   6358:            .&mt('yes').'</label>'."\n"
                   6359:        .&Apache::lonhtmlcommon::row_closure();
                   6360: 
                   6361:     $result.=
                   6362:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   6363:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   6364:            .&mt('none').' </label>'."\n"
                   6365:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   6366:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   6367:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   6368:            .&mt('all submissions with details').' </label>'
                   6369:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 6370:     
1.700     bisitz   6371:     $result.=
                   6372:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   6373:        .'<input type="text" name="CODE" value="" />'
                   6374:        .&Apache::lonhtmlcommon::row_closure(1)
                   6375:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 6376: 
1.700     bisitz   6377:     # Show list of students to select for grading
                   6378:     $result.='<br /><input type="button" '.
1.589     bisitz   6379:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       6380: 
1.68      ng       6381:     $request->print($result);
                   6382: 
1.485     albertel 6383:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 6384: 	&Apache::loncommon::start_data_table().
                   6385: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6386: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6387: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 6388: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6389: 	'<th>'.&nameUserString('header').'</th>'.
                   6390: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       6391:  
1.761     raeburn  6392:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       6393:     my $ptr = 1;
1.294     albertel 6394:     foreach my $student (sort 
                   6395: 			 {
                   6396: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   6397: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   6398: 			     }
                   6399: 			     return $a cmp $b;
                   6400: 			 } (keys(%$fullname))) {
1.68      ng       6401: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 6402: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   6403:                                   : '</td>');
1.126     ng       6404: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 6405: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   6406: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 6407: 	$studentTable.=
                   6408: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   6409:                          : '');
1.68      ng       6410: 	$ptr++;
                   6411:     }
1.484     albertel 6412:     if ($ptr%2 == 0) {
                   6413: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   6414: 	    &Apache::loncommon::end_data_table_row();
                   6415:     }
                   6416:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       6417:     $studentTable.='<input type="button" '.
1.589     bisitz   6418:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       6419: 
                   6420:     $request->print($studentTable);
                   6421: 
                   6422:     return '';
                   6423: }
                   6424: 
                   6425: sub getSymbMap {
1.582     raeburn  6426:     my ($map_error) = @_;
1.132     bowersj2 6427:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6428:     unless (ref($navmap)) {
                   6429:         if (ref($map_error)) {
                   6430:             $$map_error = 'navmap';
                   6431:         }
                   6432:         return;
                   6433:     }
1.68      ng       6434:     my %symbx = ();
                   6435:     my @titles = ();
1.117     bowersj2 6436:     my $minder = 0;
                   6437: 
                   6438:     # Gather every sequence that has problems.
1.240     albertel 6439:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   6440: 					       1,0,1);
1.117     bowersj2 6441:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  6442: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 6443: 	    my $title = $minder.'.'.
                   6444: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   6445: 	    push(@titles, $title); # minder in case two titles are identical
                   6446: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 6447: 	    $minder++;
1.241     albertel 6448: 	}
1.68      ng       6449:     }
                   6450:     return \@titles,\%symbx;
                   6451: }
                   6452: 
1.72      ng       6453: #
                   6454: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       6455: sub displayPage {
1.608     www      6456:     my ($request,$symb) = @_;
1.257     albertel 6457:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6458:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6459:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6460:     my $pageTitle = $env{'form.page'};
1.103     albertel 6461:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6462:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6463:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 6464: 
                   6465:     #need to make sure we have the correct data for later EXT calls, 
                   6466:     #thus invalidate the cache
                   6467:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 6468:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   6469:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 6470:     &Apache::lonnet::clear_EXT_cache_status();
                   6471: 
1.103     albertel 6472:     if (!&canview($usec)) {
1.712     bisitz   6473:         $request->print(
                   6474:             '<span class="LC_warning">'.
                   6475:             &mt('Unable to view requested student. ([_1])',
                   6476:                     $env{'form.student'}).
                   6477:             '</span>');
                   6478:         return;
1.103     albertel 6479:     }
1.398     albertel 6480:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 6481:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       6482: 	'</h3>'."\n";
1.500     albertel 6483:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     6484:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 6485: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 6486:     } else {
                   6487: 	delete($env{'form.CODE'});
                   6488:     }
1.71      ng       6489:     &sub_page_js($request);
                   6490:     $request->print($result);
                   6491: 
1.132     bowersj2 6492:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6493:     unless (ref($navmap)) {
                   6494:         $request->print(&navmap_errormsg());
                   6495:         return;
                   6496:     }
1.257     albertel 6497:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       6498:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6499:     if (!$map) {
1.485     albertel 6500: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 6501: 	return; 
                   6502:     }
1.68      ng       6503:     my $iterator = $navmap->getIterator($map->map_start(),
                   6504: 					$map->map_finish());
                   6505: 
1.71      ng       6506:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       6507: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 6508: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   6509: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       6510: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 6511: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 6512: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      6513: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       6514: 
1.382     albertel 6515:     if (defined($env{'form.CODE'})) {
                   6516: 	$studentTable.=
                   6517: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   6518:     }
1.381     albertel 6519:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 6520: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       6521: 
1.594     bisitz   6522:     $studentTable.='&nbsp;<span class="LC_info">'.
                   6523:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   6524:         '</span>'."\n".
1.484     albertel 6525: 	&Apache::loncommon::start_data_table().
                   6526: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   6527: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 6528: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 6529: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6530: 
1.329     albertel 6531:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 6532:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       6533:     $iterator->next(); # skip the first BEGIN_MAP
                   6534:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 6535:     while ($depth > 0) {
1.68      ng       6536:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6537:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       6538: 
1.745     raeburn  6539:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 6540: 	    my $parts = $curRes->parts();
1.68      ng       6541:             my $title = $curRes->compTitle();
1.71      ng       6542: 	    my $symbx = $curRes->symb();
1.746     raeburn  6543:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 6544: 	    $studentTable.=
                   6545: 		&Apache::loncommon::start_data_table_row().
                   6546: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6547: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  6548: 		                        : '<br />('.&mt('[_1]parts',
                   6549: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 6550: 		 ).
                   6551: 		 '</td>';
1.71      ng       6552: 	    $studentTable.='<td valign="top">';
1.382     albertel 6553: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  6554:             if ($is_tool) {
                   6555:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   6556:             } else {
1.745     raeburn  6557: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   6558: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   6559: 					         undef,'both',\%form);
                   6560: 	        } else {
                   6561: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   6562: 		    $companswer =~ s|<form(.*?)>||g;
                   6563: 		    $companswer =~ s|</form>||g;
                   6564: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   6565: #		        $companswer =~ s/$1/ /ms;
                   6566: #		        $request->print('match='.$1."<br />\n");
                   6567: #		    }
                   6568: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   6569: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   6570: 		}
1.71      ng       6571: 	    }
                   6572: 
1.257     albertel 6573: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       6574: 
1.257     albertel 6575: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       6576: 		if ($record{'version'} eq '') {
1.745     raeburn  6577:                     my $msg = &mt('No recorded submission for this problem.');
                   6578:                     if ($is_tool) {
                   6579:                         $msg = &mt('No recorded transactions for this external tool');
                   6580:                     }
                   6581: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       6582: 		} else {
1.116     ng       6583: 		    my %responseType = ();
                   6584: 		    foreach my $partid (@{$parts}) {
1.147     albertel 6585: 			my @responseIds =$curRes->responseIds($partid);
                   6586: 			my @responseType =$curRes->responseType($partid);
                   6587: 			my %responseIds;
                   6588: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   6589: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   6590: 			}
                   6591: 			$responseType{$partid} = \%responseIds;
1.116     ng       6592: 		    }
1.148     albertel 6593: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       6594: 		}
1.257     albertel 6595: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   6596: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  6597:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       6598: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 6599: 									$env{'request.course.id'},
1.726     raeburn  6600: 									'','.submission',undef,
                   6601:                                                                         $usec,$identifier);
1.71      ng       6602:  
                   6603: 	    }
1.103     albertel 6604: 	    if (&canmodify($usec)) {
1.585     bisitz   6605:             $studentTable.=&gradeBox_start();
1.103     albertel 6606: 		foreach my $partid (@{$parts}) {
                   6607: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   6608: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   6609: 		    $question++;
                   6610: 		}
1.585     bisitz   6611:             $studentTable.=&gradeBox_end();
1.196     albertel 6612: 		$prob++;
1.71      ng       6613: 	    }
                   6614: 	    $studentTable.='</td></tr>';
1.68      ng       6615: 
1.103     albertel 6616: 	}
1.68      ng       6617:         $curRes = $iterator->next();
                   6618:     }
1.780     raeburn  6619:     my $disabled;
                   6620:     unless (&canmodify($usec)) {
                   6621:         $disabled = ' disabled="disabled"';
                   6622:     }
1.68      ng       6623: 
1.589     bisitz   6624:     $studentTable.=
                   6625:         '</table>'."\n".
1.780     raeburn  6626:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   6627:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   6628:         '</form>'."\n";
1.71      ng       6629:     $request->print($studentTable);
                   6630: 
                   6631:     return '';
1.119     ng       6632: }
                   6633: 
                   6634: sub displaySubByDates {
1.148     albertel 6635:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 6636:     my $isCODE=0;
1.335     albertel 6637:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  6638:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 6639:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 6640:     my $studentTable=&Apache::loncommon::start_data_table().
                   6641: 	&Apache::loncommon::start_data_table_header_row().
                   6642: 	'<th>'.&mt('Date/Time').'</th>'.
                   6643: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  6644:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  6645: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 6646: 	'<th>'.&mt('Status').'</th>'.
                   6647: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       6648:     my ($version);
                   6649:     my %mark;
1.148     albertel 6650:     my %orders;
1.119     ng       6651:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 6652:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  6653:         if ($is_tool) {
                   6654:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   6655:         } else {
                   6656:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   6657:         }
1.147     albertel 6658:     }
1.335     albertel 6659: 
                   6660:     my $interaction;
1.525     raeburn  6661:     my $no_increment = 1;
1.735     raeburn  6662:     my (%lastrndseed,%lasttype);
1.119     ng       6663:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 6664: 	my $timestamp = 
                   6665: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 6666: 	if (exists($$record{$version.':resource.0.version'})) {
                   6667: 	    $interaction = $$record{$version.':resource.0.version'};
                   6668: 	}
1.671     raeburn  6669:         if ($isTask && $env{'form.previousversion'}) {
                   6670:             next unless ($interaction == $env{'form.previousversion'});
                   6671:         }
1.335     albertel 6672: 	my $where = ($isTask ? "$version:resource.$interaction"
                   6673: 		             : "$version:resource");
1.467     albertel 6674: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   6675: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 6676: 	if ($isCODE) {
                   6677: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   6678: 	}
1.671     raeburn  6679:         if ($isTask) {
                   6680:             $studentTable.='<td>'.$interaction.'</td>';
                   6681:         }
1.119     ng       6682: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   6683: 	my @displaySub = ();
                   6684: 	foreach my $partid (@{$parts}) {
1.640     raeburn  6685:             my ($hidden,$type);
                   6686:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   6687:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  6688:                 $hidden = 1;
                   6689:             }
1.749     raeburn  6690:             my @matchKey;
                   6691:             if ($isTask) {
1.769     raeburn  6692:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  6693:             } elsif ($is_tool) {
1.769     raeburn  6694:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  6695:             } else {
1.769     raeburn  6696:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  6697:             }
1.122     ng       6698: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 6699: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 6700: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 6701: 		if (exists($$record{$version.':'.$matchKey}) &&
                   6702: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  6703:                     if ($is_tool) {
                   6704:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  6705:                     } else {
1.749     raeburn  6706: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   6707: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   6708:                         $displaySub[0].='<span class="LC_nobreak">';
                   6709:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   6710:                                        .' <span class="LC_internal_info">'
                   6711:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   6712:                                        .'</span>'
                   6713:                                        .' <b>';
                   6714:                         if ($hidden) {
                   6715:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   6716:                         } else {
                   6717:                             my ($trial,$rndseed,$newvariation);
                   6718:                             if ($type eq 'randomizetry') {
                   6719:                                 $trial = $$record{"$where.$partid.tries"};
                   6720:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   6721:                             }
                   6722: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   6723: 			        $displaySub[0].=&mt('Trial not counted');
                   6724: 		            } else {
                   6725: 			        $displaySub[0].=&mt('Trial: [_1]',
                   6726: 					        $$record{"$where.$partid.tries"});
                   6727:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   6728:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   6729:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   6730:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   6731:                                     }
1.640     raeburn  6732:                                 }
1.749     raeburn  6733:                                 $lastrndseed{$partid} = $rndseed;
                   6734:                                 $lasttype{$partid} = $type;
                   6735: 		            }
                   6736: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 6737:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  6738: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   6739: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   6740: 			        $orders{$partid}->{$responseId}=
                   6741: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   6742:                                                $no_increment,$type,$trial,$rndseed);
                   6743: 		            }
                   6744: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   6745: 		            $displaySub[0].='&nbsp; '.
                   6746: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   6747:                         }
1.596     raeburn  6748:                     }
1.147     albertel 6749: 		}
                   6750: 	    }
1.335     albertel 6751: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 6752: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   6753: 				    $$record{"$where.$partid.checkedin"},
                   6754: 				    $$record{"$where.$partid.checkedin.slot"}).
                   6755: 					'<br />';
1.335     albertel 6756: 	    }
                   6757: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 6758: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 6759: 		    lc($$record{"$where.$partid.award"}).' '.
                   6760: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 6761: 		    '<br />';
1.749     raeburn  6762: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   6763: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   6764: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   6765: 		}
1.147     albertel 6766: 	    }
1.335     albertel 6767: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  6768: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   6769: 		unless ($is_tool) {
                   6770: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6771: 		}
1.335     albertel 6772: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   6773: 		$displaySub[2].=
1.749     raeburn  6774: 		    $$record{"$version:resource.$partid.regrader"};
                   6775:                 unless ($is_tool) {
                   6776: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6777:                 }
1.147     albertel 6778: 	    }
                   6779: 	}
                   6780: 	# needed because old essay regrader has not parts info
                   6781: 	if (exists $$record{"$version:resource.regrader"}) {
                   6782: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   6783: 	}
                   6784: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   6785: 	if ($displaySub[2]) {
1.467     albertel 6786: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 6787: 	}
1.467     albertel 6788: 	$studentTable.='&nbsp;</td>'.
                   6789: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       6790:     }
1.467     albertel 6791:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       6792:     return $studentTable;
1.71      ng       6793: }
                   6794: 
                   6795: sub updateGradeByPage {
1.608     www      6796:     my ($request,$symb) = @_;
1.71      ng       6797: 
1.257     albertel 6798:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6799:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6800:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6801:     my $pageTitle = $env{'form.page'};
1.103     albertel 6802:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6803:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6804:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 6805:     if (!&canmodify($usec)) {
1.526     raeburn  6806: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 6807: 	return;
                   6808:     }
1.398     albertel 6809:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  6810:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       6811: 	'</h3>'."\n";
1.70      ng       6812: 
1.68      ng       6813:     $request->print($result);
                   6814: 
1.582     raeburn  6815: 
1.132     bowersj2 6816:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6817:     unless (ref($navmap)) {
                   6818:         $request->print(&navmap_errormsg());
                   6819:         return;
                   6820:     }
1.257     albertel 6821:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       6822:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6823:     if (!$map) {
1.527     raeburn  6824: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 6825: 	return; 
                   6826:     }
1.71      ng       6827:     my $iterator = $navmap->getIterator($map->map_start(),
                   6828: 					$map->map_finish());
1.70      ng       6829: 
1.484     albertel 6830:     my $studentTable=
                   6831: 	&Apache::loncommon::start_data_table().
                   6832: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6833: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   6834: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   6835: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   6836: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 6837: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6838: 
                   6839:     $iterator->next(); # skip the first BEGIN_MAP
                   6840:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  6841:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.798     raeburn  6842:     my (@updates,%weights,%excuseds,%awardeds,@symbs_in_map);
1.101     albertel 6843:     while ($depth > 0) {
1.71      ng       6844:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6845:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       6846: 
1.385     albertel 6847:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 6848: 	    my $parts = $curRes->parts();
1.71      ng       6849:             my $title = $curRes->compTitle();
                   6850: 	    my $symbx = $curRes->symb();
1.798     raeburn  6851:             push(@symbs_in_map,$symbx);
1.484     albertel 6852: 	    $studentTable.=
                   6853: 		&Apache::loncommon::start_data_table_row().
                   6854: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6855: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  6856:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  6857: 		.')').'</td>';
1.71      ng       6858: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   6859: 
                   6860: 	    my %newrecord=();
                   6861: 	    my @displayPts=();
1.269     raeburn  6862:             my %aggregate = ();
                   6863:             my $aggregateflag = 0;
1.787     raeburn  6864:             my %queueable;
1.726     raeburn  6865:             if ($env{'form.HIDE'.$prob}) {
                   6866:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  6867:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  6868:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.798     raeburn  6869:                 if ($numchgs) {
                   6870:                     push(@updates,$symbx);
                   6871:                 }
1.726     raeburn  6872:                 $hideflag += $numchgs;
                   6873:             }
1.71      ng       6874: 	    foreach my $partid (@{$parts}) {
1.257     albertel 6875: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   6876: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.787     raeburn  6877:                 my @types = $curRes->responseType($partid);
1.786     raeburn  6878:                 if (grep(/^essay$/,@types)) {
                   6879:                     $queueable{$partid} = 1;
                   6880:                 } else {
1.787     raeburn  6881:                     my @ids = $curRes->responseIds($partid);
1.786     raeburn  6882:                     for (my $i=0; $i < scalar(@ids); $i++) {
1.787     raeburn  6883:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
1.786     raeburn  6884:                                                           '.handgrade',$symb);
                   6885:                         if (lc($hndgrd) eq 'yes') {
                   6886:                             $queueable{$partid} = 1;
                   6887:                             last;
                   6888:                         }
                   6889:                     }
                   6890:                 }
1.257     albertel 6891: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   6892: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.798     raeburn  6893:                 $weights{$symbx}{$partid} = $wgt;
                   6894:                 $excuseds{$symbx}{$partid} = '';
1.71      ng       6895: 		my $partial = $newpts/$wgt;
                   6896: 		my $score;
                   6897: 		if ($partial > 0) {
                   6898: 		    $score = 'correct_by_override';
1.125     ng       6899: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       6900: 		    $score = 'incorrect_by_override';
                   6901: 		}
1.257     albertel 6902: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       6903: 		if ($dropMenu eq 'excused') {
1.71      ng       6904: 		    $partial = '';
                   6905: 		    $score = 'excused';
1.798     raeburn  6906:                     $excuseds{$symbx}{$partid} = 1;
1.125     ng       6907: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 6908: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       6909: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   6910: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   6911: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   6912: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 6913: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       6914: 		    $changeflag++;
                   6915: 		    $newpts = '';
1.269     raeburn  6916:                     
                   6917:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   6918:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   6919:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   6920:                     if ($aggtries > 0) {
                   6921:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   6922:                         $aggregateflag = 1;
                   6923:                     }
1.71      ng       6924: 		}
1.324     albertel 6925: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 6926: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  6927: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       6928: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 6929: 		    '&nbsp;<br />';
1.526     raeburn  6930: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       6931: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 6932: 		    '&nbsp;<br />';
1.71      ng       6933: 		$question++;
1.798     raeburn  6934:                 if (($newpts eq '') || ($partial eq '')) {
                   6935:                     $awardeds{$symbx}{$partid} = 0;
                   6936:                 } else {
                   6937:                     $awardeds{$symbx}{$partid} = $partial;
                   6938:                 }
1.380     albertel 6939: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       6940: 
1.71      ng       6941: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       6942: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 6943: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       6944: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       6945: 
                   6946: 		$changeflag++;
                   6947: 	    }
                   6948: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 6949: 		my %record = 
                   6950: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   6951: 					     $udom,$uname);
                   6952: 
                   6953: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   6954: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   6955: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   6956: 		    $newrecord{'resource.CODE'} = '';
                   6957: 		}
1.257     albertel 6958: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       6959: 					$udom,$uname);
1.382     albertel 6960: 		%record = &Apache::lonnet::restore($symbx,
                   6961: 						   $env{'request.course.id'},
                   6962: 						   $udom,$uname);
1.380     albertel 6963: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.786     raeburn  6964: 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       6965: 	    }
1.380     albertel 6966: 	    
1.269     raeburn  6967:             if ($aggregateflag) {
                   6968:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   6969:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   6970:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   6971:             }
1.125     ng       6972: 
1.71      ng       6973: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   6974: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 6975: 		&Apache::loncommon::end_data_table_row();
1.68      ng       6976: 
1.196     albertel 6977: 	    $prob++;
1.798     raeburn  6978:             if ($changeflag) {
                   6979:                 push(@updates,$symbx);
                   6980:             }
1.68      ng       6981: 	}
1.71      ng       6982:         $curRes = $iterator->next();
1.68      ng       6983:     }
1.98      albertel 6984: 
1.484     albertel 6985:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  6986:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   6987: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  6988: 		  $changeflag).'<br />');
                   6989:     my $hidemsg=($hideflag == 0 ? '' :
                   6990:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   6991:                      $hideflag).'<br />');
                   6992:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       6993: 
1.798     raeburn  6994:     if (@updates) {
                   6995:         my (@allsymbs,$mapsymb,@recurseup,%parentmapsymbs,%possmappb,%possrespb);
                   6996:         @allsymbs = @updates;
                   6997:         if (ref($map)) {
                   6998:             $mapsymb = $map->symb();
                   6999:             push(@allsymbs,$mapsymb);
                   7000:             @recurseup = $navmap->recurseup_maps($map->src,1);
                   7001:         }
                   7002:         if (@recurseup) {
                   7003:             push(@allsymbs,@recurseup);
                   7004:             map { $parentmapsymbs{$_} = 1; } @recurseup;
                   7005:         }
                   7006:         my %passback = &Apache::lonnet::get('nohist_linkprot_passback',\@allsymbs,$cdom,$cnum);
                   7007:         my (%uniqsymbs,$use_symbs_in_map);
                   7008:         if (keys(%passback)) {
                   7009:             foreach my $possible (keys(%passback)) {
                   7010:                 if (ref($passback{$possible}) eq 'HASH') {
                   7011:                     if ($possible eq $mapsymb) {
                   7012:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7013:                             $possmappb{$launcher} = 1;
                   7014:                         }
                   7015:                         $use_symbs_in_map = 1;
                   7016:                     } elsif (exists($parentmapsymbs{$possible})) {
                   7017:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7018:                             my ($linkuri,$linkprotector,$scope) = split(/\0/,$launcher);
                   7019:                             if ($scope eq 'rec') {
                   7020:                                 $possmappb{$launcher} = 1;
                   7021:                                 $use_symbs_in_map = 1;
                   7022:                             }
                   7023:                         }
                   7024:                     } elsif (grep(/^\Q$possible$\E$/,@updates)) {
                   7025:                         foreach my $launcher (keys(%{$passback{$possible}})) {
                   7026:                             $possrespb{$launcher} = 1;
                   7027:                         }
                   7028:                         $uniqsymbs{$possible} = 1;
                   7029:                     }
                   7030:                 }
                   7031:             }
                   7032:         }
                   7033:         if ($use_symbs_in_map) {
                   7034:             map { $uniqsymbs{$_} = 1; } @symbs_in_map;
                   7035:         }
                   7036:         my @posslaunchers;
                   7037:         if (keys(%possmappb)) {
                   7038:             push(@posslaunchers,keys(%possmappb));
                   7039:         }
                   7040:         if (keys(%possrespb)) {
                   7041:             push(@posslaunchers,keys(%possrespb));
                   7042:         }
                   7043:         if (@posslaunchers) {
                   7044:             my (%pbsave,%skip_passback,%needpb);
                   7045:             my %pbids = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@posslaunchers,$udom,$uname);
                   7046:             foreach my $key (keys(%pbids)) {
                   7047:                 if (ref($pbids{$key}) eq 'ARRAY') {
                   7048:                     $needpb{$key} = 1;
                   7049:                 }
                   7050:             }
                   7051:             my @symbs = keys(%uniqsymbs);
1.802     raeburn  7052:             &process_passbacks('updatebypage',\@symbs,$cdom,$cnum,$udom,$uname,$usec,\%weights,
1.798     raeburn  7053:                                \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave,\%pbids);
1.801     raeburn  7054:             if (@Apache::grades::ltipassback) {
1.798     raeburn  7055:                 unless ($registered_cleanup) {
                   7056:                     my $handlers = $request->get_handlers('PerlCleanupHandler');
                   7057:                     $request->set_handlers('PerlCleanupHandler' =>
1.801     raeburn  7058:                                            [\&Apache::grades::make_passback,@{$handlers}]);
                   7059:                     $registered_cleanup=1;
1.798     raeburn  7060:                 }
                   7061:             }
                   7062:         }
                   7063:     }
1.70      ng       7064:     return '';
                   7065: }
                   7066: 
1.801     raeburn  7067: sub make_passback {
                   7068:     if (@Apache::grades::ltipassback) {
                   7069:         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7070:         my $ip = &Apache::lonnet::get_host_ip($lonhost);
                   7071:         foreach my $item (@Apache::grades::ltipassback) {
                   7072:             &Apache::lonhomework::run_passback($item,$lonhost,$ip);
                   7073:         }
                   7074:         undef(@Apache::grades::ltipassback);
                   7075:     }
                   7076: }
                   7077: 
1.72      ng       7078: #-------- end of section for handling grading by page/sequence ---------
                   7079: #
                   7080: #-------------------------------------------------------------------
                   7081: 
1.581     www      7082: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 7083: #
                   7084: #------ start of section for handling grading by page/sequence ---------
                   7085: 
1.423     albertel 7086: =pod
                   7087: 
                   7088: =head1 Bubble sheet grading routines
                   7089: 
1.424     albertel 7090:   For this documentation:
                   7091: 
                   7092:    'scanline' refers to the full line of characters
                   7093:    from the file that we are parsing that represents one entire sheet
                   7094: 
                   7095:    'bubble line' refers to the data
1.659     raeburn  7096:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 7097: 
                   7098: 
1.659     raeburn  7099: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 7100: into a course. When a user wants to grade, they select a
1.659     raeburn  7101: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 7102: one of the predefined configurations for what each scanline looks
                   7103: like.
                   7104: 
                   7105: Next each scanline is checked for any errors of either 'missing
1.435     foxr     7106: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 7107: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   7108: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  7109: invalid student/employee ID
1.424     albertel 7110: 
                   7111: If the CODE option is used that determines the randomization of the
1.556     weissno  7112: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 7113: username:domain.
                   7114: 
                   7115: During the validation phase the instructor can choose to skip scanlines. 
                   7116: 
1.659     raeburn  7117: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 7118: 
                   7119:   scantron_original_filename (unmodified original file)
                   7120:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   7121:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   7122: 
                   7123: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  7124: correction information that isn't representable in the bubblesheet
1.424     albertel 7125: file (see &scantron_getfile() for more information)
                   7126: 
                   7127: After all scanlines are either valid, marked as valid or skipped, then
                   7128: foreach line foreach problem in the picked sequence, an ssi request is
                   7129: made that simulates a user submitting their selected letter(s) against
                   7130: the homework problem.
1.423     albertel 7131: 
                   7132: =over 4
                   7133: 
                   7134: 
                   7135: 
                   7136: =item defaultFormData
                   7137: 
                   7138:   Returns html hidden inputs used to hold context/default values.
                   7139: 
                   7140:  Arguments:
                   7141:   $symb - $symb of the current resource 
                   7142: 
                   7143: =cut
1.422     foxr     7144: 
1.81      albertel 7145: sub defaultFormData {
1.324     albertel 7146:     my ($symb)=@_;
1.766     raeburn  7147:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 7148: }
                   7149: 
1.447     foxr     7150: 
1.423     albertel 7151: =pod 
                   7152: 
                   7153: =item getSequenceDropDown
                   7154: 
                   7155:    Return html dropdown of possible sequences to grade
                   7156:  
                   7157:  Arguments:
1.582     raeburn  7158:    $symb - $symb of the current resource
                   7159:    $map_error - ref to scalar which will container error if
                   7160:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 7161: 
                   7162: =cut
1.422     foxr     7163: 
1.75      albertel 7164: sub getSequenceDropDown {
1.582     raeburn  7165:     my ($symb,$map_error)=@_;
1.75      albertel 7166:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  7167:     my ($titles,$symbx) = &getSymbMap($map_error);
                   7168:     if (ref($map_error)) {
                   7169:         return if ($$map_error);
                   7170:     }
1.137     albertel 7171:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 7172:     my $ctr=0;
                   7173:     foreach (@$titles) {
                   7174: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   7175: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 7176: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 7177: 	    '>'.$showtitle.'</option>'."\n";
                   7178: 	$ctr++;
                   7179:     }
                   7180:     $result.= '</select>';
                   7181:     return $result;
                   7182: }
                   7183: 
1.495     albertel 7184: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  7185:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 7186: 
                   7187: my %first_bubble_line;             # First bubble line no. for each bubble.
                   7188: 
1.509     raeburn  7189: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   7190:                                    # matchresponse or rankresponse, where 
                   7191:                                    # an individual response can have multiple 
                   7192:                                    # lines
1.503     raeburn  7193: 
                   7194: my %responsetype_per_response;     # responsetype for each response
                   7195: 
1.691     raeburn  7196: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   7197:                                    # numbered response. Needed when randomorder
                   7198:                                    # or randompick are in use. Key is ID, value 
                   7199:                                    # is response number.
                   7200: 
1.495     albertel 7201: # Save and restore the bubble lines array to the form env.
                   7202: 
                   7203: 
                   7204: sub save_bubble_lines {
                   7205:     foreach my $line (keys(%bubble_lines_per_response)) {
                   7206: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   7207: 	$env{"form.scantron.first_bubble_line.$line"} =
                   7208: 	    $first_bubble_line{$line};
1.503     raeburn  7209:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   7210:             $subdivided_bubble_lines{$line};
                   7211:         $env{"form.scantron.responsetype.$line"} =
                   7212:             $responsetype_per_response{$line};
1.495     albertel 7213:     }
1.691     raeburn  7214:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   7215:         my $line = $masterseq_id_responsenum{$resid};
                   7216:         $env{"form.scantron.residpart.$line"} = $resid;
                   7217:     }
1.495     albertel 7218: }
                   7219: 
                   7220: 
                   7221: sub restore_bubble_lines {
                   7222:     my $line = 0;
                   7223:     %bubble_lines_per_response = ();
1.691     raeburn  7224:     %masterseq_id_responsenum = ();
1.495     albertel 7225:     while ($env{"form.scantron.bubblelines.$line"}) {
                   7226: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   7227: 	$bubble_lines_per_response{$line} = $value;
                   7228: 	$first_bubble_line{$line}  =
                   7229: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  7230:         $subdivided_bubble_lines{$line} =
                   7231:             $env{"form.scantron.sub_bubblelines.$line"};
                   7232:         $responsetype_per_response{$line} =
                   7233:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  7234:         my $id = $env{"form.scantron.residpart.$line"};
                   7235:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 7236: 	$line++;
                   7237:     }
                   7238: }
                   7239: 
1.423     albertel 7240: =pod 
                   7241: 
                   7242: =item scantron_filenames
                   7243: 
                   7244:    Returns a list of the scantron files in the current course 
                   7245: 
                   7246: =cut
1.422     foxr     7247: 
1.202     albertel 7248: sub scantron_filenames {
1.257     albertel 7249:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7250:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  7251:     my $getpropath = 1;
1.662     raeburn  7252:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   7253:                                                         $cname,$getpropath);
1.202     albertel 7254:     my @possiblenames;
1.662     raeburn  7255:     if (ref($dirlist) eq 'ARRAY') {
                   7256:         foreach my $filename (sort(@{$dirlist})) {
                   7257: 	    ($filename)=split(/&/,$filename);
                   7258: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   7259: 	    $filename=~s/^scantron_orig_//;
                   7260: 	    push(@possiblenames,$filename);
                   7261:         }
1.202     albertel 7262:     }
                   7263:     return @possiblenames;
                   7264: }
                   7265: 
1.423     albertel 7266: =pod 
                   7267: 
                   7268: =item scantron_uploads
                   7269: 
                   7270:    Returns  html drop-down list of scantron files in current course.
                   7271: 
                   7272:  Arguments:
                   7273:    $file2grade - filename to set as selected in the dropdown
                   7274: 
                   7275: =cut
1.422     foxr     7276: 
1.202     albertel 7277: sub scantron_uploads {
1.209     ng       7278:     my ($file2grade) = @_;
1.202     albertel 7279:     my $result=	'<select name="scantron_selectfile">';
                   7280:     $result.="<option></option>";
                   7281:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 7282: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 7283:     }
                   7284:     $result.="</select>";
                   7285:     return $result;
                   7286: }
                   7287: 
1.423     albertel 7288: =pod 
                   7289: 
                   7290: =item scantron_scantab
                   7291: 
                   7292:   Returns html drop down of the scantron formats in the scantronformat.tab
                   7293:   file.
                   7294: 
                   7295: =cut
1.422     foxr     7296: 
1.82      albertel 7297: sub scantron_scantab {
                   7298:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 7299:     $result.='<option></option>'."\n";
1.754     raeburn  7300:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  7301:     if (@lines > 0) {
                   7302:         foreach my $line (@lines) {
                   7303:             next if (($line =~ /^\#/) || ($line eq ''));
                   7304: 	    my ($name,$descrip)=split(/:/,$line);
                   7305: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   7306:         }
1.82      albertel 7307:     }
                   7308:     $result.='</select>'."\n";
1.518     raeburn  7309:     return $result;
                   7310: }
                   7311: 
1.423     albertel 7312: =pod 
                   7313: 
                   7314: =item scantron_CODElist
                   7315: 
                   7316:   Returns html drop down of the saved CODE lists from current course,
                   7317:   generated from earlier printings.
                   7318: 
                   7319: =cut
1.422     foxr     7320: 
1.186     albertel 7321: sub scantron_CODElist {
1.257     albertel 7322:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7323:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 7324:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   7325:     my $namechoice='<option></option>';
1.225     albertel 7326:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 7327: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 7328: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 7329: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   7330:     }
                   7331:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   7332:     return $namechoice;
                   7333: }
                   7334: 
1.423     albertel 7335: =pod 
                   7336: 
                   7337: =item scantron_CODEunique
                   7338: 
                   7339:   Returns the html for "Each CODE to be used once" radio.
                   7340: 
                   7341: =cut
1.422     foxr     7342: 
1.186     albertel 7343: sub scantron_CODEunique {
1.532     bisitz   7344:     my $result='<span class="LC_nobreak">
1.272     albertel 7345:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7346:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 7347:                 </span>
1.532     bisitz   7348:                 <span class="LC_nobreak">
1.272     albertel 7349:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7350:                         value="no" />'.&mt('No').' </label>
1.381     albertel 7351:                 </span>';
1.186     albertel 7352:     return $result;
                   7353: }
1.423     albertel 7354: 
                   7355: =pod 
                   7356: 
                   7357: =item scantron_selectphase
                   7358: 
1.659     raeburn  7359:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 7360:   Allows for - starting a grading run.
1.424     albertel 7361:              - downloading existing scan data (original, corrected
1.423     albertel 7362:                                                 or skipped info)
                   7363: 
                   7364:              - uploading new scan data
                   7365: 
                   7366:  Arguments:
                   7367:   $r          - The Apache request object
                   7368:   $file2grade - name of the file that contain the scanned data to score
                   7369: 
                   7370: =cut
1.186     albertel 7371: 
1.75      albertel 7372: sub scantron_selectphase {
1.608     www      7373:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 7374:     if (!$symb) {return '';}
1.582     raeburn  7375:     my $map_error;
                   7376:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   7377:     if ($map_error) {
                   7378:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   7379:         return;
                   7380:     }
1.324     albertel 7381:     my $default_form_data=&defaultFormData($symb);
1.209     ng       7382:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 7383:     my $format_selector=&scantron_scantab();
1.186     albertel 7384:     my $CODE_selector=&scantron_CODElist();
                   7385:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 7386:     my $result;
1.422     foxr     7387: 
1.513     foxr     7388:     $ssi_error = 0;
                   7389: 
1.770     raeburn  7390:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 7391: 
                   7392: 	# Chunk of form to prompt for a scantron file upload.
                   7393: 
                   7394:         $r->print('
1.754     raeburn  7395:     <br />');
1.606     wenzelju 7396:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7397:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  7398:     my $csec= $env{'request.course.sec'};
1.736     damieng  7399:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   7400:     &js_escape(\$alertmsg);
1.754     raeburn  7401:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 7402:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   7403:     function checkUpload(formname) {
                   7404: 	if (formname.upfile.value == "") {
1.736     damieng  7405: 	    alert("'.$alertmsg.'");
1.606     wenzelju 7406: 	    return false;
                   7407: 	}
                   7408: 	formname.submit();
1.756     raeburn  7409:     }'."\n".$formatjs));
1.606     wenzelju 7410:     $r->print('
                   7411:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7412:                 '.$default_form_data.'
                   7413:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  7414:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 7415:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   7416:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  7417:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7418:               '.&Apache::loncommon::start_data_table_header_row().'
                   7419:                 <th>
                   7420:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   7421:                 </th>
                   7422:               '.&Apache::loncommon::end_data_table_header_row().'
                   7423:               '.&Apache::loncommon::start_data_table_row().'
                   7424:             <td>
                   7425:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   7426:     if ($formatoptions) {
                   7427:         $r->print('</td>
                   7428:                  '.&Apache::loncommon::end_data_table_row().'
                   7429:                  '.&Apache::loncommon::start_data_table_row().'
                   7430:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   7431:                  </td>
                   7432:                  '.&Apache::loncommon::end_data_table_row().'
                   7433:                  '.&Apache::loncommon::start_data_table_row().'
                   7434:                  <td>'
                   7435:         );
                   7436:     } else {
                   7437:         $r->print(' <br />');
                   7438:     }
                   7439:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   7440:               </td>
                   7441:              '.&Apache::loncommon::end_data_table_row().'
                   7442:              '.&Apache::loncommon::end_data_table().'
                   7443:              </form>'
                   7444:     );
1.606     wenzelju 7445: 
                   7446:     }
                   7447: 
1.422     foxr     7448:     # Chunk of form to prompt for a file to grade and how:
                   7449: 
1.489     albertel 7450:     $result.= '
                   7451:     <br />
                   7452:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   7453:     <input type="hidden" name="command" value="scantron_warning" />
                   7454:     '.$default_form_data.'
                   7455:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7456:        '.&Apache::loncommon::start_data_table_header_row().'
                   7457:             <th colspan="2">
1.492     albertel 7458:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 7459:             </th>
                   7460:        '.&Apache::loncommon::end_data_table_header_row().'
                   7461:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7462:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 7463:        '.&Apache::loncommon::end_data_table_row().'
                   7464:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      7465:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_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('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 7469:        '.&Apache::loncommon::end_data_table_row().'
                   7470:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7471:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_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('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 7475:        '.&Apache::loncommon::end_data_table_row().'
                   7476:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7477: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 7478:             <td>
1.492     albertel 7479: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   7480:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   7481:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 7482: 	    </td>
1.489     albertel 7483:        '.&Apache::loncommon::end_data_table_row().'
                   7484:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 7485:             <td colspan="2">
1.572     www      7486:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 7487:             </td>
1.489     albertel 7488:        '.&Apache::loncommon::end_data_table_row().'
                   7489:     '.&Apache::loncommon::end_data_table().'
                   7490:     </form>
                   7491: ';
1.162     albertel 7492:    
                   7493:     $r->print($result);
                   7494: 
1.422     foxr     7495:     # Chunk of the form that prompts to view a scoring office file,
                   7496:     # corrected file, skipped records in a file.
                   7497: 
1.489     albertel 7498:     $r->print('
                   7499:    <br />
                   7500:    <form action="/adm/grades" name="scantron_download">
                   7501:      '.$default_form_data.'
                   7502:      <input type="hidden" name="command" value="scantron_download" />
                   7503:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7504:        '.&Apache::loncommon::start_data_table_header_row().'
                   7505:               <th>
1.492     albertel 7506:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 7507:               </th>
                   7508:        '.&Apache::loncommon::end_data_table_header_row().'
                   7509:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7510:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 7511:                 <br />
1.492     albertel 7512:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 7513:        '.&Apache::loncommon::end_data_table_row().'
                   7514:      '.&Apache::loncommon::end_data_table().'
                   7515:    </form>
                   7516:    <br />
                   7517: ');
1.162     albertel 7518: 
1.457     banghart 7519:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  7520: 
1.694     bisitz   7521:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  7522:              $default_form_data."\n".
                   7523:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   7524:              &Apache::loncommon::start_data_table_header_row()."\n".
                   7525:              '<th colspan="2">
1.572     www      7526:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  7527:              '</th>'."\n".
                   7528:               &Apache::loncommon::end_data_table_header_row()."\n".
                   7529:               &Apache::loncommon::start_data_table_row()."\n".
                   7530:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   7531:               '<td> '.$sequence_selector.' </td>'.
                   7532:               &Apache::loncommon::end_data_table_row()."\n".
                   7533:               &Apache::loncommon::start_data_table_row()."\n".
                   7534:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   7535:               '<td> '.$file_selector.' </td>'."\n".
                   7536:               &Apache::loncommon::end_data_table_row()."\n".
                   7537:               &Apache::loncommon::start_data_table_row()."\n".
                   7538:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   7539:               '<td> '.$format_selector.' </td>'."\n".
                   7540:               &Apache::loncommon::end_data_table_row()."\n".
                   7541:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  7542:               '<td> '.&mt('Options').' </td>'."\n".
                   7543:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   7544:               &Apache::loncommon::end_data_table_row()."\n".
                   7545:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  7546:               '<td colspan="2">'."\n".
                   7547:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      7548:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  7549:               '</td>'."\n".
                   7550:               &Apache::loncommon::end_data_table_row()."\n".
                   7551:               &Apache::loncommon::end_data_table()."\n".
                   7552:               '</form><br />');
                   7553:     return;
1.75      albertel 7554: }
                   7555: 
1.423     albertel 7556: =pod 
                   7557: 
                   7558: =item username_to_idmap
                   7559: 
1.556     weissno  7560:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  7561:     student username:domain. If a single ID occurs for more than one student,
                   7562:     the status of the student is checked, and if Active, the value in the hash
                   7563:     will be set to the Active student.
1.423     albertel 7564: 
                   7565:   Arguments:
                   7566: 
                   7567:     $classlist - reference to the class list hash. This is a hash
                   7568:                  keyed by student name:domain  whose elements are references
1.424     albertel 7569:                  to arrays containing various chunks of information
1.423     albertel 7570:                  about the student. (See loncoursedata for more info).
                   7571: 
                   7572:   Returns
                   7573:     %idmap - the constructed hash
                   7574: 
                   7575: =cut
                   7576: 
1.82      albertel 7577: sub username_to_idmap {
                   7578:     my ($classlist)= @_;
                   7579:     my %idmap;
                   7580:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  7581:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   7582:         unless ($id eq '') {
                   7583:             if (!exists($idmap{$id})) {
                   7584:                 $idmap{$id} = $student;
                   7585:             } else {
                   7586:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   7587:                 if ($status eq 'Active') {
                   7588:                     $idmap{$id} = $student;
                   7589:                 }
                   7590:             }
                   7591:         }
1.82      albertel 7592:     }
                   7593:     return %idmap;
                   7594: }
1.423     albertel 7595: 
                   7596: =pod
                   7597: 
1.424     albertel 7598: =item scantron_fixup_scanline
1.423     albertel 7599: 
                   7600:    Process a requested correction to a scanline.
                   7601: 
                   7602:   Arguments:
1.754     raeburn  7603:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 7604:     $scan_data         - hash of correction information 
                   7605:                           (see &scantron_getfile())
                   7606:     $line              - existing scanline
                   7607:     $whichline         - line number of the passed in scanline
                   7608:     $field             - type of change to process 
                   7609:                          (either 
1.573     bisitz   7610:                           'ID'     -> correct the student/employee ID
1.423     albertel 7611:                           'CODE'   -> correct the CODE
                   7612:                           'answer' -> fixup the submitted answers)
                   7613:     
                   7614:    $args               - hash of additional info,
                   7615:                           - 'ID' 
                   7616:                                'newid' -> studentID to use in replacement
1.424     albertel 7617:                                           of existing one
1.423     albertel 7618:                           - 'CODE' 
                   7619:                                'CODE_ignore_dup' - set to true if duplicates
                   7620:                                                    should be ignored.
                   7621: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 7622:                                         if the existing unfound code should
1.423     albertel 7623:                                         be used as is
                   7624:                           - 'answer'
                   7625:                                'response' - new answer or 'none' if blank
                   7626:                                'question' - the bubble line to change
1.503     raeburn  7627:                                'questionnum' - the question identifier,
                   7628:                                                may include subquestion. 
1.423     albertel 7629: 
                   7630:   Returns:
                   7631:     $line - the modified scanline
                   7632: 
                   7633:   Side effects: 
                   7634:     $scan_data - may be updated
                   7635: 
                   7636: =cut
                   7637: 
1.82      albertel 7638: 
1.157     albertel 7639: sub scantron_fixup_scanline {
                   7640:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   7641:     if ($field eq 'ID') {
                   7642: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 7643: 	    return ($line,1,'New value too large');
1.157     albertel 7644: 	}
                   7645: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   7646: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   7647: 				     $args->{'newid'});
                   7648: 	}
                   7649: 	substr($line,$$scantron_config{'IDstart'}-1,
                   7650: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   7651: 	if ($args->{'newid'}=~/^\s*$/) {
                   7652: 	    &scan_data($scan_data,"$whichline.user",
                   7653: 		       $args->{'username'}.':'.$args->{'domain'});
                   7654: 	}
1.186     albertel 7655:     } elsif ($field eq 'CODE') {
1.192     albertel 7656: 	if ($args->{'CODE_ignore_dup'}) {
                   7657: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   7658: 	}
                   7659: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   7660: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 7661: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   7662: 		return ($line,1,'New CODE value too large');
                   7663: 	    }
                   7664: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   7665: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   7666: 	    }
                   7667: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   7668: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 7669: 	}
1.157     albertel 7670:     } elsif ($field eq 'answer') {
1.497     foxr     7671: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 7672: 	my $off=$scantron_config->{'Qoff'};
                   7673: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     7674: 	my $answer=${off}x$length;
                   7675: 	if ($args->{'response'} eq 'none') {
                   7676: 	    &scan_data($scan_data,
1.503     raeburn  7677: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     7678: 	} else {
                   7679: 	    if ($on eq 'letter') {
                   7680: 		my @alphabet=('A'..'Z');
                   7681: 		$answer=$alphabet[$args->{'response'}];
                   7682: 	    } elsif ($on eq 'number') {
                   7683: 		$answer=$args->{'response'}+1;
                   7684: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 7685: 	    } else {
1.497     foxr     7686: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 7687: 	    }
1.497     foxr     7688: 	    &scan_data($scan_data,
1.503     raeburn  7689: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 7690: 	}
1.497     foxr     7691: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   7692: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 7693:     }
                   7694:     return $line;
                   7695: }
1.423     albertel 7696: 
                   7697: =pod
                   7698: 
                   7699: =item scan_data
                   7700: 
                   7701:     Edit or look up  an item in the scan_data hash.
                   7702: 
                   7703:   Arguments:
                   7704:     $scan_data  - The hash (see scantron_getfile)
                   7705:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 7706:                   scantronfilename_key).
1.423     albertel 7707:     $data        - New value of the hash entry.
                   7708:     $delete      - If true, the entry is removed from the hash.
                   7709: 
                   7710:   Returns:
                   7711:     The new value of the hash table field (undefined if deleted).
                   7712: 
                   7713: =cut
                   7714: 
                   7715: 
1.157     albertel 7716: sub scan_data {
                   7717:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 7718:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 7719:     if (defined($value)) {
                   7720: 	$scan_data->{$filename.'_'.$key} = $value;
                   7721:     }
                   7722:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   7723:     return $scan_data->{$filename.'_'.$key};
                   7724: }
1.423     albertel 7725: 
1.495     albertel 7726: # ----- These first few routines are general use routines.----
                   7727: 
                   7728: # Return the number of occurences of a pattern in a string.
                   7729: 
                   7730: sub occurence_count {
                   7731:     my ($string, $pattern) = @_;
                   7732: 
                   7733:     my @matches = ($string =~ /$pattern/g);
                   7734: 
                   7735:     return scalar(@matches);
                   7736: }
                   7737: 
                   7738: 
                   7739: # Take a string known to have digits and convert all the
                   7740: # digits into letters in the range J,A..I.
                   7741: 
                   7742: sub digits_to_letters {
                   7743:     my ($input) = @_;
                   7744: 
                   7745:     my @alphabet = ('J', 'A'..'I');
                   7746: 
                   7747:     my @input    = split(//, $input);
                   7748:     my $output ='';
                   7749:     for (my $i = 0; $i < scalar(@input); $i++) {
                   7750: 	if ($input[$i] =~ /\d/) {
                   7751: 	    $output .= $alphabet[$input[$i]];
                   7752: 	} else {
                   7753: 	    $output .= $input[$i];
                   7754: 	}
                   7755:     }
                   7756:     return $output;
                   7757: }
                   7758: 
1.423     albertel 7759: =pod 
                   7760: 
                   7761: =item scantron_parse_scanline
                   7762: 
1.711     bisitz   7763:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 7764: 
                   7765:  Arguments:
1.711     bisitz   7766:     line             - The text of the bubblesheet file line to process
1.423     albertel 7767:     whichline        - Line number
1.711     bisitz   7768:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 7769:     scan_data        - Hash of extra information about the scanline
                   7770:                        (see scantron_getfile for more information)
                   7771:     just_header      - True if should not process question answers but only
                   7772:                        the stuff to the left of the answers.
1.691     raeburn  7773:     randomorder      - True if randomorder in use
                   7774:     randompick       - True if randompick in use
                   7775:     sequence         - Exam folder URL
                   7776:     master_seq       - Ref to array containing symbs in exam folder
                   7777:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   7778:                        (corresponding values are resource objects)
                   7779:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   7780:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   7781:                        are refs to an array of resource objects, ordered
                   7782:                        according to order used for CODE, when randomorder
                   7783:                        and or randompick are in use.
                   7784:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   7785:                        for current line to question number used for same question
                   7786:                         in "Master Sequence" (as seen by Course Coordinator).
                   7787:     startline        - Ref to hash where key is question number (0 is first)
                   7788:                        and value is number of first bubble line for current 
                   7789:                        student or code-based randompick and/or randomorder.
                   7790:     totalref         - Ref of scalar used to score total number of bubble
                   7791:                        lines needed for responses in a scan line (used when
                   7792:                        randompick in use. 
                   7793:     
1.423     albertel 7794:  Returns:
                   7795:    Hash containing the result of parsing the scanline
                   7796: 
                   7797:    Keys are all proceeded by the string 'scantron.'
                   7798: 
                   7799:        CODE    - the CODE in use for this scanline
                   7800:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   7801:                  by the operator
                   7802:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   7803:                             CODEs were selected, but the usage has been
                   7804:                             forced by the operator
1.556     weissno  7805:        ID  - student/employee ID
1.423     albertel 7806:        PaperID - if used, the ID number printed on the sheet when the 
                   7807:                  paper was scanned
                   7808:        FirstName - first name from the sheet
                   7809:        LastName  - last name from the sheet
                   7810: 
                   7811:      if just_header was not true these key may also exist
                   7812: 
1.447     foxr     7813:        missingerror - a list of bubble ranges that are considered to be answers
                   7814:                       to a single question that don't have any bubbles filled in.
                   7815:                       Of the form questionnumber:firstbubblenumber:count.
                   7816:        doubleerror  - a list of bubble ranges that are considered to be answers
                   7817:                       to a single question that have more than one bubble filled in.
                   7818:                       Of the form questionnumber::firstbubblenumber:count
                   7819:    
                   7820:                 In the above, count is the number of bubble responses in the
                   7821:                 input line needed to represent the possible answers to the question.
                   7822:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   7823:                 per line would have count = 2.
                   7824: 
1.423     albertel 7825:        maxquest     - the number of the last bubble line that was parsed
                   7826: 
                   7827:        (<number> starts at 1)
                   7828:        <number>.answer - zero or more letters representing the selected
                   7829:                          letters from the scanline for the bubble line 
                   7830:                          <number>.
                   7831:                          if blank there was either no bubble or there where
                   7832:                          multiple bubbles, (consult the keys missingerror and
                   7833:                          doubleerror if this is an error condition)
                   7834: 
                   7835: =cut
                   7836: 
1.82      albertel 7837: sub scantron_parse_scanline {
1.691     raeburn  7838:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   7839:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   7840:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     7841: 
1.82      albertel 7842:     my %record;
1.691     raeburn  7843:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 7844:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   7845: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   7846: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   7847: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   7848: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 7849: 	    $record{'scantron.CODE'}=substr($data,
                   7850: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 7851: 					    $$scantron_config{'CODElength'});
1.191     albertel 7852: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   7853: 		$record{'scantron.useCODE'}=1;
                   7854: 	    }
1.192     albertel 7855: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   7856: 		$record{'scantron.CODE_ignore_dup'}=1;
                   7857: 	    }
1.82      albertel 7858: 	} else {
                   7859: 	    #FIXME interpret first N questions
                   7860: 	}
                   7861:     }
1.83      albertel 7862:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   7863: 				  $$scantron_config{'IDlength'});
1.157     albertel 7864:     $record{'scantron.PaperID'}=
                   7865: 	substr($data,$$scantron_config{'PaperID'}-1,
                   7866: 	       $$scantron_config{'PaperIDlength'});
                   7867:     $record{'scantron.FirstName'}=
                   7868: 	substr($data,$$scantron_config{'FirstName'}-1,
                   7869: 	       $$scantron_config{'FirstNamelength'});
                   7870:     $record{'scantron.LastName'}=
                   7871: 	substr($data,$$scantron_config{'LastName'}-1,
                   7872: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 7873:     if ($just_header) { return \%record; }
1.194     albertel 7874: 
1.82      albertel 7875:     my @alphabet=('A'..'Z');
                   7876:     my $questnum=0;
1.447     foxr     7877:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   7878: 
1.691     raeburn  7879:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   7880:     if ($randompick || $randomorder) {
                   7881:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   7882:                                          $master_seq,$symb_to_resource,
                   7883:                                          $partids_by_symb,$orderedforcode,
                   7884:                                          $respnumlookup,$startline);
                   7885:         if ($total) {
                   7886:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   7887:         }
                   7888:         if (ref($totalref)) {
                   7889:             $$totalref = $total;
                   7890:         }
                   7891:     }
                   7892:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     7893:     chomp($questions);		# Get rid of any trailing \n.
                   7894:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   7895:     while (length($questions)) {
1.691     raeburn  7896:         my $answers_needed;
                   7897:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7898:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   7899:         } else {
                   7900: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   7901:         }
1.503     raeburn  7902:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   7903:                              || 1;
                   7904:         $questnum++;
                   7905:         my $quest_id = $questnum;
                   7906:         my $currentquest = substr($questions,0,$answer_length);
                   7907:         $questions       = substr($questions,$answer_length);
                   7908:         if (length($currentquest) < $answer_length) { next; }
                   7909: 
1.691     raeburn  7910:         my $subdivided;
                   7911:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7912:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   7913:         } else {
                   7914:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   7915:         }
                   7916:         if ($subdivided =~ /,/) {
1.503     raeburn  7917:             my $subquestnum = 1;
                   7918:             my $subquestions = $currentquest;
1.691     raeburn  7919:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  7920:             foreach my $subans (@subanswers_needed) {
                   7921:                 my $subans_length =
                   7922:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   7923:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   7924:                 $subquestions   = substr($subquestions,$subans_length);
                   7925:                 $quest_id = "$questnum.$subquestnum";
                   7926:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   7927:                     ($$scantron_config{'Qon'} eq 'number')) {
                   7928:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   7929:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  7930:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7931:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7932:                 } else {
                   7933:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  7934:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   7935:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7936:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7937:                 }
                   7938:                 $subquestnum ++;
                   7939:             }
                   7940:         } else {
                   7941:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   7942:                 ($$scantron_config{'Qon'} eq 'number')) {
                   7943:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   7944:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7945:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7946:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7947:             } else {
                   7948:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   7949:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7950:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7951:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7952:             }
                   7953:         }
                   7954:     }
                   7955:     $record{'scantron.maxquest'}=$questnum;
                   7956:     return \%record;
                   7957: }
1.447     foxr     7958: 
1.691     raeburn  7959: sub get_master_seq {
1.788     raeburn  7960:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
1.691     raeburn  7961:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   7962:                    (ref($symb_to_resource) eq 'HASH'));
1.788     raeburn  7963:     if ($need_symb_in_map) {
                   7964:         return unless (ref($symb_for_examcode) eq 'HASH');
                   7965:     }
1.691     raeburn  7966:     my $resource_error;
                   7967:     foreach my $resource (@{$resources}) {
                   7968:         my $ressymb;
                   7969:         if (ref($resource)) {
                   7970:             $ressymb = $resource->symb();
                   7971:             push(@{$master_seq},$ressymb);
                   7972:             $symb_to_resource->{$ressymb} = $resource;
1.788     raeburn  7973:             if ($need_symb_in_map) {
                   7974:                 unless ($resource->is_map()) {
                   7975:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   7976:                     unless (exists($symb_for_examcode->{$map})) {
                   7977:                         $symb_for_examcode->{$map} = $ressymb;
                   7978:                     }
                   7979:                 }
                   7980:             }
1.691     raeburn  7981:         } else {
                   7982:             $resource_error = 1;
                   7983:             last;
                   7984:         }
                   7985:     }
                   7986:     return $resource_error;
                   7987: }
                   7988: 
                   7989: sub get_respnum_lookups {
                   7990:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   7991:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   7992:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   7993:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   7994:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   7995:                    (ref($startline) eq 'HASH'));
                   7996:     my ($user,$scancode);
                   7997:     if ((exists($record->{'scantron.CODE'})) &&
                   7998:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   7999:         $scancode = $record->{'scantron.CODE'};
                   8000:     } else {
                   8001:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   8002:     }
                   8003:     my @mapresources =
                   8004:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   8005:                      $orderedforcode);
                   8006:     my $total = 0;
                   8007:     my $count = 0;
                   8008:     foreach my $resource (@mapresources) {
                   8009:         my $id = $resource->id();
                   8010:         my $symb = $resource->symb();
                   8011:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   8012:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   8013:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   8014:                 if ($respnum ne '') {
                   8015:                     $respnumlookup->{$count} = $respnum;
                   8016:                     $startline->{$count} = $total;
                   8017:                     $total += $bubble_lines_per_response{$respnum};
                   8018:                     $count ++;
                   8019:                 }
                   8020:             }
                   8021:         }
                   8022:     }
                   8023:     return $total;
                   8024: }
                   8025: 
1.503     raeburn  8026: sub scantron_validator_lettnum {
                   8027:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  8028:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   8029:         $randompick,$respnumlookup) = @_;
1.503     raeburn  8030: 
                   8031:     # Qon 'letter' implies for each slot in currquest we have:
                   8032:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   8033:     #    about anything else (esp. a value of Qoff) for missing
                   8034:     #    bubbles.
                   8035:     #
                   8036:     # Qon 'number' implies each slot gives a digit that indexes the
                   8037:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   8038:     #    and * or ? for double bubbles on a single line.
                   8039:     #
1.447     foxr     8040: 
1.503     raeburn  8041:     my $matchon;
                   8042:     if ($$scantron_config{'Qon'} eq 'letter') {
                   8043:         $matchon = '[A-Z]';
                   8044:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   8045:         $matchon = '\d';
                   8046:     }
                   8047:     my $occurrences = 0;
1.691     raeburn  8048:     my $responsenum = $questnum-1;
                   8049:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   8050:        $responsenum = $respnumlookup->{$questnum-1} 
                   8051:     }
                   8052:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8053:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8054:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8055:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8056:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8057:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8058:         my @singlelines = split('',$currquest);
                   8059:         foreach my $entry (@singlelines) {
                   8060:             $occurrences = &occurence_count($entry,$matchon);
                   8061:             if ($occurrences > 1) {
                   8062:                 last;
                   8063:             }
1.691     raeburn  8064:         }
1.503     raeburn  8065:     } else {
                   8066:         $occurrences = &occurence_count($currquest,$matchon); 
                   8067:     }
                   8068:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   8069:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8070:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8071:             my $bubble = substr($currquest,$ans,1);
                   8072:             if ($bubble =~ /$matchon/ ) {
                   8073:                 if ($$scantron_config{'Qon'} eq 'number') {
                   8074:                     if ($bubble == 0) {
                   8075:                         $bubble = 10; 
                   8076:                     }
                   8077:                     $record->{"scantron.$ansnum.answer"} = 
                   8078:                         $alphabet->[$bubble-1];
                   8079:                 } else {
                   8080:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   8081:                 }
                   8082:             } else {
                   8083:                 $record->{"scantron.$ansnum.answer"}='';
                   8084:             }
                   8085:             $ansnum++;
                   8086:         }
                   8087:     } elsif (!defined($currquest)
                   8088:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   8089:             || (&occurence_count($currquest,$matchon) == 0)) {
                   8090:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8091:             $record->{"scantron.$ansnum.answer"}='';
                   8092:             $ansnum++;
                   8093:         }
                   8094:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8095:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   8096:         }
                   8097:     } else {
                   8098:         if ($$scantron_config{'Qon'} eq 'number') {
                   8099:             $currquest = &digits_to_letters($currquest);            
                   8100:         }
                   8101:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8102:             my $bubble = substr($currquest,$ans,1);
                   8103:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   8104:             $ansnum++;
                   8105:         }
                   8106:     }
                   8107:     return $ansnum;
                   8108: }
1.447     foxr     8109: 
1.503     raeburn  8110: sub scantron_validator_positional {
                   8111:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  8112:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   8113:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     8114: 
1.503     raeburn  8115:     # Otherwise there's a positional notation;
                   8116:     # each bubble line requires Qlength items, and there are filled in
                   8117:     # bubbles for each case where there 'Qon' characters.
                   8118:     #
1.447     foxr     8119: 
1.503     raeburn  8120:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     8121: 
1.503     raeburn  8122:     # If the split only gives us one element.. the full length of the
                   8123:     # answer string, no bubbles are filled in:
1.447     foxr     8124: 
1.507     raeburn  8125:     if ($answers_needed eq '') {
                   8126:         return;
                   8127:     }
                   8128: 
1.503     raeburn  8129:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   8130:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8131:             $record->{"scantron.$ansnum.answer"}='';
                   8132:             $ansnum++;
                   8133:         }
                   8134:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8135:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   8136:         }
                   8137:     } elsif (scalar(@array) == 2) {
                   8138:         my $location = length($array[0]);
                   8139:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   8140:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   8141:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8142:             if ($ans eq $line_num) {
                   8143:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   8144:             } else {
                   8145:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   8146:             }
                   8147:             $ansnum++;
                   8148:          }
                   8149:     } else {
                   8150:         #  If there's more than one instance of a bubble character
                   8151:         #  That's a double bubble; with positional notation we can
                   8152:         #  record all the bubbles filled in as well as the
                   8153:         #  fact this response consists of multiple bubbles.
                   8154:         #
1.691     raeburn  8155:         my $responsenum = $questnum-1;
                   8156:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   8157:             $responsenum = $respnumlookup->{$questnum-1}
                   8158:         }
                   8159:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8160:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8161:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8162:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8163:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8164:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8165:             my $doubleerror = 0;
                   8166:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   8167:                    (!$doubleerror)) {
                   8168:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   8169:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   8170:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   8171:                if (length(@currarray) > 2) {
                   8172:                    $doubleerror = 1;
                   8173:                } 
                   8174:             }
                   8175:             if ($doubleerror) {
                   8176:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8177:             }
                   8178:         } else {
                   8179:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8180:         }
                   8181:         my $item = $ansnum;
                   8182:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8183:             $record->{"scantron.$item.answer"} = '';
                   8184:             $item ++;
                   8185:         }
1.447     foxr     8186: 
1.503     raeburn  8187:         my @ans=@array;
                   8188:         my $i=0;
                   8189:         my $increment = 0;
                   8190:         while ($#ans) {
                   8191:             $i+=length($ans[0]) + $increment;
                   8192:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   8193:             my $bubble = $i%$$scantron_config{'Qlength'};
                   8194:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   8195:             shift(@ans);
                   8196:             $increment = 1;
                   8197:         }
                   8198:         $ansnum += $answers_needed;
1.82      albertel 8199:     }
1.503     raeburn  8200:     return $ansnum;
1.82      albertel 8201: }
                   8202: 
1.423     albertel 8203: =pod
                   8204: 
                   8205: =item scantron_add_delay
                   8206: 
                   8207:    Adds an error message that occurred during the grading phase to a
                   8208:    queue of messages to be shown after grading pass is complete
                   8209: 
                   8210:  Arguments:
1.424     albertel 8211:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 8212:    $scanline    - the scanline that caused the error
                   8213:    $errormesage - the error message
                   8214:    $errorcode   - a numeric code for the error
                   8215: 
                   8216:  Side Effects:
1.424     albertel 8217:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 8218: 
                   8219: =cut
                   8220: 
1.82      albertel 8221: sub scantron_add_delay {
1.140     albertel 8222:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   8223:     push(@$delayqueue,
                   8224: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   8225: 	  'ecode' => $errorcode }
                   8226: 	 );
1.82      albertel 8227: }
                   8228: 
1.423     albertel 8229: =pod
                   8230: 
                   8231: =item scantron_find_student
                   8232: 
1.424     albertel 8233:    Finds the username for the current scanline
                   8234: 
                   8235:   Arguments:
                   8236:    $scantron_record - hash result from scantron_parse_scanline
                   8237:    $scan_data       - hash of correction information 
                   8238:                       (see &scantron_getfile() form more information)
                   8239:    $idmap           - hash from &username_to_idmap()
                   8240:    $line            - number of current scanline
                   8241:  
                   8242:   Returns:
                   8243:    Either 'username:domain' or undef if unknown
                   8244: 
1.423     albertel 8245: =cut
                   8246: 
1.82      albertel 8247: sub scantron_find_student {
1.157     albertel 8248:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 8249:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 8250:     if ($scanID =~ /^\s*$/) {
                   8251:  	return &scan_data($scan_data,"$line.user");
                   8252:     }
1.83      albertel 8253:     foreach my $id (keys(%$idmap)) {
1.157     albertel 8254:  	if (lc($id) eq lc($scanID)) {
                   8255:  	    return $$idmap{$id};
                   8256:  	}
1.83      albertel 8257:     }
                   8258:     return undef;
                   8259: }
                   8260: 
1.423     albertel 8261: =pod
                   8262: 
                   8263: =item scantron_filter
                   8264: 
1.424     albertel 8265:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   8266:    hidden resources was selected
                   8267: 
1.423     albertel 8268: =cut
                   8269: 
1.83      albertel 8270: sub scantron_filter {
                   8271:     my ($curres)=@_;
1.331     albertel 8272: 
                   8273:     if (ref($curres) && $curres->is_problem()) {
                   8274: 	# if the user has asked to not have either hidden
                   8275: 	# or 'randomout' controlled resources to be graded
                   8276: 	# don't include them
                   8277: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   8278: 	    && $curres->randomout) {
                   8279: 	    return 0;
                   8280: 	}
1.83      albertel 8281: 	return 1;
                   8282:     }
                   8283:     return 0;
1.82      albertel 8284: }
                   8285: 
1.423     albertel 8286: =pod
                   8287: 
                   8288: =item scantron_process_corrections
                   8289: 
1.424     albertel 8290:    Gets correction information out of submitted form data and corrects
                   8291:    the scanline
                   8292: 
1.423     albertel 8293: =cut
                   8294: 
1.157     albertel 8295: sub scantron_process_corrections {
                   8296:     my ($r) = @_;
1.754     raeburn  8297:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8298:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8299:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 8300:     my $which=$env{'form.scantron_line'};
1.200     albertel 8301:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 8302:     my ($skip,$err,$errmsg);
1.257     albertel 8303:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 8304: 	$skip=1;
1.257     albertel 8305:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   8306: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   8307: 	    $env{'form.scantron_domain'};
1.157     albertel 8308: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   8309: 	($line,$err,$errmsg)=
                   8310: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   8311: 				     'ID',{'newid'=>$newid,
1.257     albertel 8312: 				    'username'=>$env{'form.scantron_username'},
                   8313: 				    'domain'=>$env{'form.scantron_domain'}});
                   8314:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   8315: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 8316: 	my $newCODE;
1.192     albertel 8317: 	my %args;
1.190     albertel 8318: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 8319: 	    $newCODE='use_unfound';
1.190     albertel 8320: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 8321: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 8322: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 8323: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 8324: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 8325: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 8326: 	}
1.257     albertel 8327: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 8328: 	    $args{'CODE_ignore_dup'}=1;
                   8329: 	}
                   8330: 	$args{'CODE'}=$newCODE;
1.186     albertel 8331: 	($line,$err,$errmsg)=
                   8332: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 8333: 				     'CODE',\%args);
1.257     albertel 8334:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   8335: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 8336: 	    ($line,$err,$errmsg)=
                   8337: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   8338: 					 $which,'answer',
                   8339: 					 { 'question'=>$question,
1.503     raeburn  8340: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   8341:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 8342: 	    if ($err) { last; }
                   8343: 	}
                   8344:     }
                   8345:     if ($err) {
1.703     bisitz   8346:         $r->print(
                   8347:             '<p class="LC_error">'
                   8348:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   8349:                 $errmsg)
1.704     raeburn  8350:            .'</p>');
1.157     albertel 8351:     } else {
1.200     albertel 8352: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 8353: 	&scantron_putfile($scanlines,$scan_data);
                   8354:     }
                   8355: }
                   8356: 
1.423     albertel 8357: =pod
                   8358: 
                   8359: =item reset_skipping_status
                   8360: 
1.424     albertel 8361:    Forgets the current set of remember skipped scanlines (and thus
                   8362:    reverts back to considering all lines in the
                   8363:    scantron_skipped_<filename> file)
                   8364: 
1.423     albertel 8365: =cut
                   8366: 
1.200     albertel 8367: sub reset_skipping_status {
                   8368:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8369:     &scan_data($scan_data,'remember_skipping',undef,1);
                   8370:     &scantron_putfile(undef,$scan_data);
                   8371: }
                   8372: 
1.423     albertel 8373: =pod
                   8374: 
                   8375: =item start_skipping
                   8376: 
1.424     albertel 8377:    Marks a scanline to be skipped. 
                   8378: 
1.423     albertel 8379: =cut
                   8380: 
1.376     albertel 8381: sub start_skipping {
1.200     albertel 8382:     my ($scan_data,$i)=@_;
                   8383:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8384:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   8385: 	$remembered{$i}=2;
                   8386:     } else {
                   8387: 	$remembered{$i}=1;
                   8388:     }
1.200     albertel 8389:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   8390: }
                   8391: 
1.423     albertel 8392: =pod
                   8393: 
                   8394: =item should_be_skipped
                   8395: 
1.424     albertel 8396:    Checks whether a scanline should be skipped.
                   8397: 
1.423     albertel 8398: =cut
                   8399: 
1.200     albertel 8400: sub should_be_skipped {
1.376     albertel 8401:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 8402:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 8403: 	# not redoing old skips
1.376     albertel 8404: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 8405: 	return 0;
                   8406:     }
                   8407:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8408: 
                   8409:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   8410: 	return 0;
                   8411:     }
1.200     albertel 8412:     return 1;
                   8413: }
                   8414: 
1.423     albertel 8415: =pod
                   8416: 
                   8417: =item remember_current_skipped
                   8418: 
1.424     albertel 8419:    Discovers what scanlines are in the scantron_skipped_<filename>
                   8420:    file and remembers them into scan_data for later use.
                   8421: 
1.423     albertel 8422: =cut
                   8423: 
1.200     albertel 8424: sub remember_current_skipped {
                   8425:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8426:     my %to_remember;
                   8427:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8428: 	if ($scanlines->{'skipped'}[$i]) {
                   8429: 	    $to_remember{$i}=1;
                   8430: 	}
                   8431:     }
1.376     albertel 8432: 
1.200     albertel 8433:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   8434:     &scantron_putfile(undef,$scan_data);
                   8435: }
                   8436: 
1.423     albertel 8437: =pod
                   8438: 
                   8439: =item check_for_error
                   8440: 
1.424     albertel 8441:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  8442:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 8443:     something went wrong.
                   8444: 
1.423     albertel 8445: =cut
                   8446: 
1.200     albertel 8447: sub check_for_error {
                   8448:     my ($r,$result)=@_;
                   8449:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 8450: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 8451:     }
                   8452: }
1.157     albertel 8453: 
1.423     albertel 8454: =pod
                   8455: 
                   8456: =item scantron_warning_screen
                   8457: 
1.424     albertel 8458:    Interstitial screen to make sure the operator has selected the
                   8459:    correct options before we start the validation phase.
                   8460: 
1.423     albertel 8461: =cut
                   8462: 
1.203     albertel 8463: sub scantron_warning_screen {
1.650     raeburn  8464:     my ($button_text,$symb)=@_;
1.257     albertel 8465:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  8466:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 8467:     my $CODElist;
1.284     albertel 8468:     if ($scantron_config{'CODElocation'} &&
                   8469: 	$scantron_config{'CODEstart'} &&
                   8470: 	$scantron_config{'CODElength'}) {
                   8471: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   8472: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 8473: 	$CODElist=
1.492     albertel 8474: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 8475: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 8476:     }
1.663     raeburn  8477:     my $lastbubblepoints;
                   8478:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8479:         $lastbubblepoints =
                   8480:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   8481:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   8482:     }
1.770     raeburn  8483:     return '
1.203     albertel 8484: <p>
1.492     albertel 8485: <span class="LC_warning">
1.705     raeburn  8486: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 8487: </p>
                   8488: <table>
1.492     albertel 8489: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   8490: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  8491: '.$CODElist.$lastbubblepoints.'
1.203     albertel 8492: </table>
1.680     raeburn  8493: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  8494: '.&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  8495: ';
1.203     albertel 8496: }
                   8497: 
1.423     albertel 8498: =pod
                   8499: 
                   8500: =item scantron_do_warning
                   8501: 
1.424     albertel 8502:    Check if the operator has picked something for all required
                   8503:    fields. Error out if something is missing.
                   8504: 
1.423     albertel 8505: =cut
                   8506: 
1.203     albertel 8507: sub scantron_do_warning {
1.608     www      8508:     my ($r,$symb)=@_;
1.203     albertel 8509:     if (!$symb) {return '';}
1.324     albertel 8510:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 8511:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 8512:     if ( $env{'form.selectpage'} eq '' ||
                   8513: 	 $env{'form.scantron_selectfile'} eq '' ||
                   8514: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  8515: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 8516: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 8517: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 8518: 	} 
1.257     albertel 8519: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  8520: 	    $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  8521: 	}
1.257     albertel 8522: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  8523: 	    $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  8524: 	}
1.237     albertel 8525:     } else {
1.650     raeburn  8526: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  8527:         my ($checksec,@possibles) = &gradable_sections();
                   8528:         my $gradesections;
                   8529:         if ($checksec) {
                   8530:             my $file=$env{'form.scantron_selectfile'};
                   8531:             if (&valid_file($file)) {
                   8532:                 my %bysec = &scantron_get_sections();
                   8533:                 my $table;
                   8534:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   8535:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   8536:                     $table = &Apache::loncommon::start_data_table()."\n".
                   8537:                              &Apache::loncommon::start_data_table_header_row().
                   8538:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   8539:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   8540:                     if ($bysec{'none'}) {
                   8541:                         $table .= &Apache::loncommon::start_data_table_row().
                   8542:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   8543:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8544:                     }
                   8545:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   8546:                         next if ($sec eq 'none');
                   8547:                         $table .= &Apache::loncommon::start_data_table_row().
                   8548:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   8549:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8550:                     }
                   8551:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   8552:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   8553:                                       '<p>'.$table.'</p>';
                   8554:                     if (@possibles) {
                   8555:                         $gradesections .= '<p>'.
                   8556:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   8557:                                               scalar(@possibles)).'<br />'.
                   8558:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   8559:                                               '<i>'.$checksec.'</i>').' ';
                   8560:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   8561:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   8562:                         }
                   8563:                         $gradesections .= '</p>';
                   8564:                     }
                   8565:                 }
                   8566:             } else {
                   8567:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   8568:             }
                   8569:         }
1.663     raeburn  8570:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 8571: 	$r->print('
1.770     raeburn  8572: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 8573: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 8574: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 8575: ');
1.237     albertel 8576:     }
1.614     www      8577:     $r->print("</form><br />");
1.203     albertel 8578:     return '';
                   8579: }
                   8580: 
1.423     albertel 8581: =pod
                   8582: 
                   8583: =item scantron_form_start
                   8584: 
1.424     albertel 8585:     html hidden input for remembering all selected grading options
                   8586: 
1.423     albertel 8587: =cut
                   8588: 
1.203     albertel 8589: sub scantron_form_start {
                   8590:     my ($max_bubble)=@_;
                   8591:     my $result= <<SCANTRONFORM;
                   8592: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 8593:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   8594:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   8595:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 8596:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 8597:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   8598:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   8599:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   8600:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 8601:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 8602: SCANTRONFORM
1.447     foxr     8603: 
                   8604:   my $line = 0;
                   8605:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   8606:        my $chunk =
                   8607: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     8608:        $chunk .=
                   8609: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  8610:        $chunk .= 
                   8611:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  8612:        $chunk .=
                   8613:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  8614:        $chunk .=
                   8615:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     8616:        $result .= $chunk;
                   8617:        $line++;
1.691     raeburn  8618:     }
1.203     albertel 8619:     return $result;
                   8620: }
                   8621: 
1.423     albertel 8622: =pod
                   8623: 
                   8624: =item scantron_validate_file
                   8625: 
1.659     raeburn  8626:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 8627: 
                   8628:     Also processes any necessary information resets that need to
                   8629:     occur before validation begins (ignore previous corrections,
                   8630:     restarting the skipped records processing)
                   8631: 
1.423     albertel 8632: =cut
                   8633: 
1.157     albertel 8634: sub scantron_validate_file {
1.608     www      8635:     my ($r,$symb) = @_;
1.157     albertel 8636:     if (!$symb) {return '';}
1.324     albertel 8637:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 8638:     
1.703     bisitz   8639:     # do the detection of only doing skipped records first before we delete
1.424     albertel 8640:     # them when doing the corrections reset
1.257     albertel 8641:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 8642: 	&reset_skipping_status();
                   8643:     }
1.257     albertel 8644:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 8645: 	&remember_current_skipped();
1.257     albertel 8646: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 8647:     }
                   8648: 
1.257     albertel 8649:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 8650: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   8651: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   8652: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 8653: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 8654:     }
1.200     albertel 8655: 
1.257     albertel 8656:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 8657: 	&scantron_process_corrections($r);
                   8658:     }
1.770     raeburn  8659: 
                   8660:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   8661:     my ($checksec,@gradable);
                   8662:     if ($env{'request.course.sec'}) {
                   8663:         ($checksec,my @possibles) = &gradable_sections();
                   8664:         if ($checksec) {
                   8665:             if (@possibles) {
                   8666:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   8667:                 if (@chosensecs) {
                   8668:                     foreach my $sec (@chosensecs) {
                   8669:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   8670:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   8671:                                 push(@gradable,$sec);
                   8672:                             }
                   8673:                         }
                   8674:                     }
                   8675:                 }
                   8676:             }
                   8677:             $r->print('<p><table>');
                   8678:             if (@gradable) {
                   8679:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   8680:                 $r->print(
                   8681:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   8682:             } else {
                   8683:                 $r->print(
                   8684:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   8685:             }
                   8686:             $r->print('</table></p>');
                   8687:         }
                   8688:     }
                   8689:     $r->rflush();
                   8690: 
1.157     albertel 8691:     #get the student pick code ready
                   8692:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  8693:     my $nav_error;
1.754     raeburn  8694:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8695:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8696:     if ($nav_error) {
                   8697:         $r->print(&navmap_errormsg());
                   8698:         return '';
                   8699:     }
1.203     albertel 8700:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  8701:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8702:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   8703:     }
1.157     albertel 8704:     $r->print($result);
                   8705:     
1.334     albertel 8706:     my @validate_phases=( 'sequence',
                   8707: 			  'ID',
1.157     albertel 8708: 			  'CODE',
                   8709: 			  'doublebubble',
                   8710: 			  'missingbubbles');
1.257     albertel 8711:     if (!$env{'form.validatepass'}) {
                   8712: 	$env{'form.validatepass'} = 0;
1.157     albertel 8713:     }
1.257     albertel 8714:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  8715:     my %skipbysec=();
1.448     foxr     8716: 
1.157     albertel 8717:     my $stop=0;
                   8718:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  8719: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 8720: 	$r->rflush();
1.691     raeburn  8721:      
1.157     albertel 8722: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   8723: 	{
                   8724: 	    no strict 'refs';
1.770     raeburn  8725:             my @extras=();
                   8726:             if ($validate_phases[$currentphase] eq 'ID') {
                   8727:                 @extras = (\%skipbysec,$checksec,@gradable);
                   8728:             }
                   8729: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 8730: 	}
                   8731:     }
                   8732:     if (!$stop) {
1.650     raeburn  8733: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  8734:         my $secinfo;
                   8735:         if (keys(%skipbysec) > 0) {
                   8736:             my $seclist = '<ul>';
                   8737:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   8738:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   8739:             }
                   8740:             $seclist .= '</ul>';
                   8741:             $secinfo = '<p class="LC_info">'.
                   8742:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   8743:                            $seclist).
                   8744:                        '</p>';
                   8745:         }
1.542     raeburn  8746: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  8747:                   $secinfo.$warning.
1.542     raeburn  8748:                   &mt('Perform verification for each student after storage of submissions?').
                   8749:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   8750:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   8751:                   ('&nbsp;'x3).'<label>'.
                   8752:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   8753:                   '</label></span><br />'.
                   8754:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  8755:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  8756:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   8757:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 8758:     } else {
                   8759: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   8760: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   8761:     }
                   8762:     if ($stop) {
1.334     albertel 8763: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  8764: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 8765: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 8766: 
1.650     raeburn  8767: 	    $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 8768: 	} else {
1.503     raeburn  8769:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  8770: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  8771:             } else {
1.539     riegler  8772:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  8773:             }
1.492     albertel 8774: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   8775: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   8776: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 8777: 	}
1.157     albertel 8778:     }
1.614     www      8779:     $r->print(" </form><br />");
1.157     albertel 8780:     return '';
                   8781: }
                   8782: 
1.423     albertel 8783: 
                   8784: =pod
                   8785: 
                   8786: =item scantron_remove_file
                   8787: 
1.659     raeburn  8788:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 8789:    scantron_original_<filename> is never removed
                   8790: 
                   8791: 
1.423     albertel 8792: =cut
                   8793: 
1.200     albertel 8794: sub scantron_remove_file {
1.192     albertel 8795:     my ($which)=@_;
1.257     albertel 8796:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8797:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8798:     my $file='scantron_';
1.200     albertel 8799:     if ($which eq 'corrected' || $which eq 'skipped') {
                   8800: 	$file.=$which.'_';
1.192     albertel 8801:     } else {
                   8802: 	return 'refused';
                   8803:     }
1.257     albertel 8804:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 8805:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   8806: }
                   8807: 
1.423     albertel 8808: 
                   8809: =pod
                   8810: 
                   8811: =item scantron_remove_scan_data
                   8812: 
1.659     raeburn  8813:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 8814:    data file.  (In the case that both the are doing skipped records we need
                   8815:    to remember the old skipped lines for the time being so that element
                   8816:    persists for a while.)
                   8817: 
1.423     albertel 8818: =cut
                   8819: 
1.200     albertel 8820: sub scantron_remove_scan_data {
1.257     albertel 8821:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8822:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8823:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   8824:     my @todelete;
1.257     albertel 8825:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 8826:     foreach my $key (@keys) {
                   8827: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 8828: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 8829: 		$key=~/remember_skipping/) {
                   8830: 		next;
                   8831: 	    }
1.192     albertel 8832: 	    push(@todelete,$key);
                   8833: 	}
                   8834:     }
1.200     albertel 8835:     my $result;
1.192     albertel 8836:     if (@todelete) {
1.491     albertel 8837: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   8838: 				       \@todelete,$cdom,$cname);
                   8839:     } else {
                   8840: 	$result = 'ok';
1.192     albertel 8841:     }
                   8842:     return $result;
                   8843: }
                   8844: 
1.423     albertel 8845: 
                   8846: =pod
                   8847: 
                   8848: =item scantron_getfile
                   8849: 
1.659     raeburn  8850:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 8851:     the scan_data hash
                   8852:   
                   8853:   Arguments:
                   8854:     None
                   8855: 
                   8856:   Returns:
                   8857:     2 hash references
                   8858: 
                   8859:      - first one has 
                   8860:          orig      -
                   8861:          corrected -
                   8862:          skipped   -  each of which points to an array ref of the specified
                   8863:                       file broken up into individual lines
                   8864:          count     - number of scanlines
                   8865:  
                   8866:      - second is the scan_data hash possible keys are
1.425     albertel 8867:        ($number refers to scanline numbered $number and thus the key affects
                   8868:         only that scanline
                   8869:         $bubline refers to the specific bubble line element and the aspects
                   8870:         refers to that specific bubble line element)
                   8871: 
                   8872:        $number.user - username:domain to use
                   8873:        $number.CODE_ignore_dup 
                   8874:                     - ignore the duplicate CODE error 
                   8875:        $number.useCODE
                   8876:                     - use the CODE in the scanline as is
                   8877:        $number.no_bubble.$bubline
                   8878:                     - it is valid that there is no bubbled in bubble
                   8879:                       at $number $bubline
                   8880:        remember_skipping
                   8881:                     - a frozen hash containing keys of $number and values
                   8882:                       of either 
                   8883:                         1 - we are on a 'do skipped records pass' and plan
                   8884:                             on processing this line
                   8885:                         2 - we are on a 'do skipped records pass' and this
                   8886:                             scanline has been marked to skip yet again
1.424     albertel 8887: 
1.423     albertel 8888: =cut
                   8889: 
1.157     albertel 8890: sub scantron_getfile {
1.200     albertel 8891:     #FIXME really would prefer a scantron directory
1.257     albertel 8892:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8893:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 8894:     my $lines;
                   8895:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8896: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 8897:     my %scanlines;
                   8898:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   8899:     my $temp=$scanlines{'orig'};
                   8900:     $scanlines{'count'}=$#$temp;
                   8901: 
                   8902:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8903: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 8904:     if ($lines eq '-1') {
                   8905: 	$scanlines{'corrected'}=[];
                   8906:     } else {
                   8907: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   8908:     }
                   8909:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8910: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 8911:     if ($lines eq '-1') {
                   8912: 	$scanlines{'skipped'}=[];
                   8913:     } else {
                   8914: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   8915:     }
1.175     albertel 8916:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 8917:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   8918:     my %scan_data = @tmp;
                   8919:     return (\%scanlines,\%scan_data);
                   8920: }
                   8921: 
1.423     albertel 8922: =pod
                   8923: 
                   8924: =item lonnet_putfile
                   8925: 
1.424     albertel 8926:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   8927: 
                   8928:  Arguments:
                   8929:    $contents - data to store
                   8930:    $filename - filename to store $contents into
                   8931: 
                   8932:  Returns:
                   8933:    result value from &Apache::lonnet::finishuserfileupload
                   8934: 
1.423     albertel 8935: =cut
                   8936: 
1.157     albertel 8937: sub lonnet_putfile {
                   8938:     my ($contents,$filename)=@_;
1.257     albertel 8939:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8940:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8941:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 8942:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 8943: 
                   8944: }
                   8945: 
1.423     albertel 8946: =pod
                   8947: 
                   8948: =item scantron_putfile
                   8949: 
1.659     raeburn  8950:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 8951:     scan_data hash. (Does not modify the original version only the
                   8952:     corrected and skipped versions.
                   8953: 
                   8954:  Arguments:
                   8955:     $scanlines - hash ref that looks like the first return value from
                   8956:                  &scantron_getfile()
                   8957:     $scan_data - hash ref that looks like the second return value from
                   8958:                  &scantron_getfile()
                   8959: 
1.423     albertel 8960: =cut
                   8961: 
1.157     albertel 8962: sub scantron_putfile {
                   8963:     my ($scanlines,$scan_data) = @_;
1.200     albertel 8964:     #FIXME really would prefer a scantron directory
1.257     albertel 8965:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8966:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 8967:     if ($scanlines) {
                   8968: 	my $prefix='scantron_';
1.157     albertel 8969: # no need to update orig, shouldn't change
                   8970: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 8971: #		    $env{'form.scantron_selectfile'});
1.200     albertel 8972: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   8973: 			$prefix.'corrected_'.
1.257     albertel 8974: 			$env{'form.scantron_selectfile'});
1.200     albertel 8975: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   8976: 			$prefix.'skipped_'.
1.257     albertel 8977: 			$env{'form.scantron_selectfile'});
1.200     albertel 8978:     }
1.175     albertel 8979:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 8980: }
                   8981: 
1.423     albertel 8982: =pod
                   8983: 
                   8984: =item scantron_get_line
                   8985: 
1.424     albertel 8986:    Returns the correct version of the scanline
                   8987: 
                   8988:  Arguments:
                   8989:     $scanlines - hash ref that looks like the first return value from
                   8990:                  &scantron_getfile()
                   8991:     $scan_data - hash ref that looks like the second return value from
                   8992:                  &scantron_getfile()
                   8993:     $i         - number of the requested line (starts at 0)
                   8994: 
                   8995:  Returns:
                   8996:    A scanline, (either the original or the corrected one if it
                   8997:    exists), or undef if the requested scanline should be
                   8998:    skipped. (Either because it's an skipped scanline, or it's an
                   8999:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   9000:    pass.
                   9001: 
1.423     albertel 9002: =cut
                   9003: 
1.157     albertel 9004: sub scantron_get_line {
1.200     albertel 9005:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 9006:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   9007:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 9008:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   9009:     return $scanlines->{'orig'}[$i]; 
                   9010: }
                   9011: 
1.423     albertel 9012: =pod
                   9013: 
                   9014: =item scantron_todo_count
                   9015: 
1.424     albertel 9016:     Counts the number of scanlines that need processing.
                   9017: 
                   9018:  Arguments:
                   9019:     $scanlines - hash ref that looks like the first return value from
                   9020:                  &scantron_getfile()
                   9021:     $scan_data - hash ref that looks like the second return value from
                   9022:                  &scantron_getfile()
                   9023: 
                   9024:  Returns:
                   9025:     $count - number of scanlines to process
                   9026: 
1.423     albertel 9027: =cut
                   9028: 
1.200     albertel 9029: sub get_todo_count {
                   9030:     my ($scanlines,$scan_data)=@_;
                   9031:     my $count=0;
                   9032:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   9033: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   9034: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9035: 	$count++;
                   9036:     }
                   9037:     return $count;
                   9038: }
                   9039: 
1.423     albertel 9040: =pod
                   9041: 
                   9042: =item scantron_put_line
                   9043: 
1.659     raeburn  9044:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 9045:     data file.
                   9046: 
                   9047:  Arguments:
                   9048:     $scanlines - hash ref that looks like the first return value from
                   9049:                  &scantron_getfile()
                   9050:     $scan_data - hash ref that looks like the second return value from
                   9051:                  &scantron_getfile()
                   9052:     $i         - line number to update
                   9053:     $newline   - contents of the updated scanline
                   9054:     $skip      - if true make the line for skipping and update the
                   9055:                  'skipped' file
                   9056: 
1.423     albertel 9057: =cut
                   9058: 
1.157     albertel 9059: sub scantron_put_line {
1.200     albertel 9060:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 9061:     if ($skip) {
                   9062: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 9063: 	&start_skipping($scan_data,$i);
1.157     albertel 9064: 	return;
                   9065:     }
                   9066:     $scanlines->{'corrected'}[$i]=$newline;
                   9067: }
                   9068: 
1.423     albertel 9069: =pod
                   9070: 
                   9071: =item scantron_clear_skip
                   9072: 
1.424     albertel 9073:    Remove a line from the 'skipped' file
                   9074: 
                   9075:  Arguments:
                   9076:     $scanlines - hash ref that looks like the first return value from
                   9077:                  &scantron_getfile()
                   9078:     $scan_data - hash ref that looks like the second return value from
                   9079:                  &scantron_getfile()
                   9080:     $i         - line number to update
                   9081: 
1.423     albertel 9082: =cut
                   9083: 
1.376     albertel 9084: sub scantron_clear_skip {
                   9085:     my ($scanlines,$scan_data,$i)=@_;
                   9086:     if (exists($scanlines->{'skipped'}[$i])) {
                   9087: 	undef($scanlines->{'skipped'}[$i]);
                   9088: 	return 1;
                   9089:     }
                   9090:     return 0;
                   9091: }
                   9092: 
1.423     albertel 9093: =pod
                   9094: 
                   9095: =item scantron_filter_not_exam
                   9096: 
1.424     albertel 9097:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   9098:    filter out resources that are not marked as 'exam' mode
                   9099: 
1.423     albertel 9100: =cut
                   9101: 
1.334     albertel 9102: sub scantron_filter_not_exam {
                   9103:     my ($curres)=@_;
                   9104:     
                   9105:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   9106: 	# if the user has asked to not have either hidden
                   9107: 	# or 'randomout' controlled resources to be graded
                   9108: 	# don't include them
                   9109: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   9110: 	    && $curres->randomout) {
                   9111: 	    return 0;
                   9112: 	}
                   9113: 	return 1;
                   9114:     }
                   9115:     return 0;
                   9116: }
                   9117: 
1.423     albertel 9118: =pod
                   9119: 
                   9120: =item scantron_validate_sequence
                   9121: 
1.424     albertel 9122:     Validates the selected sequence, checking for resource that are
                   9123:     not set to exam mode.
                   9124: 
1.423     albertel 9125: =cut
                   9126: 
1.334     albertel 9127: sub scantron_validate_sequence {
                   9128:     my ($r,$currentphase) = @_;
                   9129: 
                   9130:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9131:     unless (ref($navmap)) {
                   9132:         $r->print(&navmap_errormsg());
                   9133:         return (1,$currentphase);
                   9134:     }
1.334     albertel 9135:     my (undef,undef,$sequence)=
                   9136: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9137: 
                   9138:     my $map=$navmap->getResourceByUrl($sequence);
                   9139: 
                   9140:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   9141:                                     value="ignore" />');
                   9142:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   9143: 	my @resources=
                   9144: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   9145: 	if (@resources) {
1.675     bisitz   9146: 	    $r->print(
                   9147:                 '<p class="LC_warning">'
                   9148:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   9149:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   9150:                    .' work correctly.')
                   9151:                .'</p>'
                   9152:             );
1.334     albertel 9153: 	    return (1,$currentphase);
                   9154: 	}
                   9155:     }
                   9156: 
                   9157:     return (0,$currentphase+1);
                   9158: }
                   9159: 
1.423     albertel 9160: 
                   9161: 
1.157     albertel 9162: sub scantron_validate_ID {
1.770     raeburn  9163:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 9164:     
                   9165:     #get student info
                   9166:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9167:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  9168:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 9169: 
                   9170:     #get scantron line setup
1.754     raeburn  9171:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9172:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  9173: 
                   9174:     my $nav_error;
1.649     raeburn  9175:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  9176:     if ($nav_error) {
                   9177:         $r->print(&navmap_errormsg());
                   9178:         return(1,$currentphase);
                   9179:     }
1.157     albertel 9180: 
                   9181:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  9182:     my $unsavedskips = 0;
1.157     albertel 9183:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9184: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9185: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9186: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9187: 						 $scan_data);
                   9188: 	my $id=$$scan_record{'scantron.ID'};
                   9189: 	my $found;
                   9190: 	foreach my $checkid (keys(%idmap)) {
                   9191: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   9192: 	}
                   9193: 	if ($found) {
                   9194: 	    my $username=$idmap{$found};
1.770     raeburn  9195:             if ($checksec) {
                   9196:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   9197:                     my $stusec = $classlist->{$username}->[$secidx];
                   9198:                     if ($stusec ne $checksec) {
                   9199:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9200:                             my $skip=1;
                   9201:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9202:                             if (ref($skipbysec) eq 'HASH') {
                   9203:                                 if ($stusec eq '') {
                   9204:                                     $skipbysec->{'none'} ++;
                   9205:                                 } else {
                   9206:                                     $skipbysec->{$stusec} ++;
                   9207:                                 }
                   9208:                             }
                   9209:                             $unsavedskips ++;
                   9210:                             next;
                   9211:                         }
                   9212:                     }
                   9213:                 }
                   9214:             }
1.157     albertel 9215: 	    if ($found{'ids'}{$found}) {
                   9216: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9217: 					 $line,'duplicateID',$found);
1.770     raeburn  9218:                 if ($unsavedskips) {
                   9219:                     &scantron_putfile($scanlines,$scan_data);
                   9220:                     $unsavedskips = 0;
                   9221:                 }
1.194     albertel 9222: 		return(1,$currentphase);
1.157     albertel 9223: 	    } elsif ($found{'usernames'}{$username}) {
                   9224: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9225: 					 $line,'duplicateID',$username);
1.770     raeburn  9226:                 if ($unsavedskips) {
                   9227:                     &scantron_putfile($scanlines,$scan_data);
                   9228:                     $unsavedskips = 0;
                   9229:                 }
1.194     albertel 9230: 		return(1,$currentphase);
1.157     albertel 9231: 	    }
1.186     albertel 9232: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 9233: 	    $found{'ids'}{$found}++;
                   9234: 	    $found{'usernames'}{$username}++;
                   9235: 	} else {
                   9236: 	    if ($id =~ /^\s*$/) {
1.158     albertel 9237: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  9238:                 if (($checksec && $username ne '')) {
                   9239:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   9240:                         my $stusec = $classlist->{$username}->[$secidx];
                   9241:                         if ($stusec ne $checksec) {
                   9242:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9243:                                 my $skip=1;
                   9244:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9245:                                 if (ref($skipbysec) eq 'HASH') {
                   9246:                                     if ($stusec eq '') {
                   9247:                                         $skipbysec->{'none'} ++;
                   9248:                                     } else {
                   9249:                                         $skipbysec->{$stusec} ++;
                   9250:                                     }
                   9251:                                 }
                   9252:                                 $unsavedskips ++;
                   9253:                                 next;
                   9254:                             }
                   9255:                         }
                   9256:                     }
                   9257: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 9258: 		    &scantron_get_correction($r,$i,$scan_record,
                   9259: 					     \%scantron_config,
                   9260: 					     $line,'duplicateID',$username);
1.770     raeburn  9261:                     if ($unsavedskips) {
                   9262:                         &scantron_putfile($scanlines,$scan_data);
                   9263:                         $unsavedskips = 0;
                   9264:                     }
1.194     albertel 9265: 		    return(1,$currentphase);
1.157     albertel 9266: 		} elsif (!defined($username)) {
                   9267: 		    &scantron_get_correction($r,$i,$scan_record,
                   9268: 					     \%scantron_config,
                   9269: 					     $line,'incorrectID');
1.770     raeburn  9270:                     if ($unsavedskips) {
                   9271:                         &scantron_putfile($scanlines,$scan_data);
                   9272:                         $unsavedskips = 0;
                   9273:                     }
1.194     albertel 9274: 		    return(1,$currentphase);
1.157     albertel 9275: 		}
                   9276: 		$found{'usernames'}{$username}++;
                   9277: 	    } else {
                   9278: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9279: 					 $line,'incorrectID');
1.770     raeburn  9280:                 if ($unsavedskips) {
                   9281:                     &scantron_putfile($scanlines,$scan_data);
                   9282:                     $unsavedskips = 0;
                   9283:                 }
1.194     albertel 9284: 		return(1,$currentphase);
1.157     albertel 9285: 	    }
                   9286: 	}
                   9287:     }
1.770     raeburn  9288:     if ($unsavedskips) {
                   9289:         &scantron_putfile($scanlines,$scan_data);
                   9290:         $unsavedskips = 0;
                   9291:     }
1.157     albertel 9292:     return (0,$currentphase+1);
                   9293: }
                   9294: 
1.770     raeburn  9295: sub scantron_get_sections {
                   9296:     my %bysec;
                   9297:     if ($env{'form.scantron_format'} ne '') {
                   9298:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   9299:         my ($scanlines,$scan_data)=&scantron_getfile();
                   9300:         my $classlist=&Apache::loncoursedata::get_classlist();
                   9301:         my %idmap=&username_to_idmap($classlist);
                   9302:         foreach my $key (keys(%idmap)) {
                   9303:             my $lckey = lc($key);
                   9304:             $idmap{$lckey} = $idmap{$key};
                   9305:         }
                   9306:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   9307:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   9308:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   9309:             if ($line=~/^[\s\cz]*$/) { next; }
                   9310:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9311:                                                      $scan_data);
                   9312:             my $id=lc($$scan_record{'scantron.ID'});
                   9313:             if (exists($idmap{$id})) {
                   9314:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9315:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9316:                     if ($stusec eq '') {
                   9317:                         $bysec{'none'} ++;
                   9318:                     } else {
                   9319:                         $bysec{$stusec} ++;
                   9320:                     }
                   9321:                 }
                   9322:             }
                   9323:         }
                   9324:     }
                   9325:     return %bysec;
                   9326: }
1.423     albertel 9327: 
1.157     albertel 9328: sub scantron_get_correction {
1.691     raeburn  9329:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   9330:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 9331: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 9332: #to show both the current line and the previous one and allow skipping
                   9333: #the previous one or the current one
                   9334: 
1.333     albertel 9335:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   9336:         $r->print(
                   9337:             '<p class="LC_warning">'
                   9338:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   9339:                 "<b>$error</b>",
                   9340:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   9341:            ."</p> \n");
1.157     albertel 9342:     } else {
1.658     bisitz   9343:         $r->print(
                   9344:             '<p class="LC_warning">'
                   9345:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   9346:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   9347:            ."</p> \n");
                   9348:     }
                   9349:     my $message =
                   9350:         '<p>'
                   9351:        .&mt('The ID on the form is [_1]',
                   9352:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   9353:        .'<br />'
1.665     raeburn  9354:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   9355:             $$scan_record{'scantron.LastName'},
                   9356:             $$scan_record{'scantron.FirstName'})
                   9357:        .'</p>';
1.242     albertel 9358: 
1.157     albertel 9359:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   9360:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  9361:                            # Array populated for doublebubble or
                   9362:     my @lines_to_correct;  # missingbubble errors to build javascript
                   9363:                            # to validate radio button checking   
                   9364: 
1.157     albertel 9365:     if ($error =~ /ID$/) {
1.186     albertel 9366: 	if ($error eq 'incorrectID') {
1.658     bisitz   9367:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 9368: 		      "</p>\n");
1.157     albertel 9369: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   9370:             $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 9371: 	}
1.242     albertel 9372: 	$r->print($message);
1.492     albertel 9373: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 9374: 	$r->print("\n<ul><li> ");
                   9375: 	#FIXME it would be nice if this sent back the user ID and
                   9376: 	#could do partial userID matches
                   9377: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   9378: 				       'scantron_username','scantron_domain'));
                   9379: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   9380: 	$r->print("\n:\n".
1.257     albertel 9381: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 9382: 
                   9383: 	$r->print('</li>');
1.186     albertel 9384:     } elsif ($error =~ /CODE$/) {
                   9385: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   9386: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 9387: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   9388: 	    $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 9389: 	}
1.658     bisitz   9390: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   9391: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   9392:                  ."</p>\n");
1.242     albertel 9393: 	$r->print($message);
1.658     bisitz   9394: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 9395: 	$r->print("\n<br /> ");
1.194     albertel 9396: 	my $i=0;
1.273     albertel 9397: 	if ($error eq 'incorrectCODE' 
                   9398: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 9399: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 9400: 	    if ($closest > 0) {
                   9401: 		foreach my $testcode (@{$closest}) {
                   9402: 		    my $checked='';
1.569     bisitz   9403: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9404: 		    $r->print("
                   9405:    <label>
1.569     bisitz   9406:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 9407:        ".&mt("Use the similar CODE [_1] instead.",
                   9408: 	    "<b><tt>".$testcode."</tt></b>")."
                   9409:     </label>
                   9410:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 9411: 		    $r->print("\n<br />");
                   9412: 		    $i++;
                   9413: 		}
1.194     albertel 9414: 	    }
                   9415: 	}
1.273     albertel 9416: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   9417: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9418: 	    $r->print("
                   9419:     <label>
1.569     bisitz   9420:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  9421:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 9422: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   9423:     </label>");
1.273     albertel 9424: 	    $r->print("\n<br />");
                   9425: 	}
1.194     albertel 9426: 
1.597     wenzelju 9427: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 9428: function change_radio(field) {
1.190     albertel 9429:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 9430:     var i;
                   9431:     for (i=0;i<slct.length;i++) {
                   9432:         if (slct[i].value==field) { slct[i].checked=true; }
                   9433:     }
                   9434: }
                   9435: ENDSCRIPT
1.187     albertel 9436: 	my $href="/adm/pickcode?".
1.359     www      9437: 	   "form=".&escape("scantronupload").
                   9438: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   9439: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   9440: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   9441: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 9442: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 9443: 	    $r->print("
                   9444:     <label>
                   9445:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   9446:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   9447: 	     "<a target='_blank' href='$href'>","</a>")."
                   9448:     </label> 
1.558     bisitz   9449:     ".&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 9450: 	    $r->print("\n<br />");
                   9451: 	}
1.492     albertel 9452: 	$r->print("
                   9453:     <label>
                   9454:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   9455:        ".&mt("Use [_1] as the CODE.",
                   9456: 	     "</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 9457: 	$r->print("\n<br /><br />");
1.157     albertel 9458:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   9459: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     9460: 
                   9461: 	# The form field scantron_questions is acutally a list of line numbers.
                   9462: 	# represented by this form so:
                   9463: 
1.691     raeburn  9464: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9465:                                                 $respnumlookup,$startline);
1.497     foxr     9466: 
1.157     albertel 9467: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9468: 		  $line_list.'" />');
1.242     albertel 9469: 	$r->print($message);
1.492     albertel 9470: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 9471: 	foreach my $question (@{$arg}) {
1.503     raeburn  9472: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9473:                                                    $scan_record, $error,
                   9474:                                                    $randomorder,$randompick,
                   9475:                                                    $respnumlookup,$startline);
1.524     raeburn  9476:             push(@lines_to_correct,@linenums);
1.157     albertel 9477: 	}
1.503     raeburn  9478:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9479:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   9480: 	$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 9481: 	$r->print($message);
1.492     albertel 9482: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  9483: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     9484: 
1.503     raeburn  9485: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     9486: 	# a list of question numbers. Therefore:
                   9487: 	#
1.691     raeburn  9488: 
                   9489: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9490:                                                 $respnumlookup,$startline);
1.497     foxr     9491: 
1.157     albertel 9492: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9493: 		  $line_list.'" />');
1.157     albertel 9494: 	foreach my $question (@{$arg}) {
1.503     raeburn  9495: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9496:                                                    $scan_record, $error,
                   9497:                                                    $randomorder,$randompick,
                   9498:                                                    $respnumlookup,$startline);
1.524     raeburn  9499:             push(@lines_to_correct,@linenums);
1.157     albertel 9500: 	}
1.503     raeburn  9501:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9502:     } else {
                   9503: 	$r->print("\n<ul>");
                   9504:     }
                   9505:     $r->print("\n</li></ul>");
1.497     foxr     9506: }
                   9507: 
1.503     raeburn  9508: sub verify_bubbles_checked {
                   9509:     my (@ansnums) = @_;
                   9510:     my $ansnumstr = join('","',@ansnums);
                   9511:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  9512:     &js_escape(\$warning);
1.767     raeburn  9513:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  9514: function verify_bubble_radio(form) {
                   9515:     var ansnumArray = new Array ("$ansnumstr");
                   9516:     var need_bubble_count = 0;
                   9517:     for (var i=0; i<ansnumArray.length; i++) {
                   9518:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   9519:             var bubble_picked = 0; 
                   9520:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   9521:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   9522:                     bubble_picked = 1;
                   9523:                 }
                   9524:             }
                   9525:             if (bubble_picked == 0) {
                   9526:                 need_bubble_count ++;
                   9527:             }
                   9528:         }
                   9529:     }
                   9530:     if (need_bubble_count) {
                   9531:         alert("$warning");
                   9532:         return;
                   9533:     }
                   9534:     form.submit(); 
                   9535: }
                   9536: ENDSCRIPT
                   9537:     return $output;
                   9538: }
                   9539: 
1.497     foxr     9540: =pod
                   9541: 
                   9542: =item  questions_to_line_list
1.157     albertel 9543: 
1.497     foxr     9544: Converts a list of questions into a string of comma separated
                   9545: line numbers in the answer sheet used by the questions.  This is
                   9546: used to fill in the scantron_questions form field.
                   9547: 
                   9548:   Arguments:
                   9549:      questions    - Reference to an array of questions.
1.691     raeburn  9550:      randomorder  - True if randomorder in use.
                   9551:      randompick   - True if randompick in use.
                   9552:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9553:                      for current line to question number used for same question
                   9554:                      in "Master Seqence" (as seen by Course Coordinator).
                   9555:      startline    - Reference to hash where key is question number (0 is first)
                   9556:                     and key is number of first bubble line for current student
                   9557:                     or code-based randompick and/or randomorder.
1.693     raeburn  9558: 
1.497     foxr     9559: =cut
                   9560: 
                   9561: 
                   9562: sub questions_to_line_list {
1.691     raeburn  9563:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     9564:     my @lines;
                   9565: 
1.503     raeburn  9566:     foreach my $item (@{$questions}) {
                   9567:         my $question = $item;
                   9568:         my ($first,$count,$last);
                   9569:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   9570:             $question = $1;
                   9571:             my $subquestion = $2;
1.691     raeburn  9572:             my $responsenum = $question-1;
                   9573:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9574:                 $responsenum = $respnumlookup->{$question-1};
                   9575:                 if (ref($startline) eq 'HASH') {
                   9576:                     $first = $startline->{$question-1} + 1;
                   9577:                 }
                   9578:             } else {
                   9579:                 $first = $first_bubble_line{$responsenum} + 1;
                   9580:             }
                   9581:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9582:             my $subcount = 1;
                   9583:             while ($subcount<$subquestion) {
                   9584:                 $first += $subans[$subcount-1];
                   9585:                 $subcount ++;
                   9586:             }
                   9587:             $count = $subans[$subquestion-1];
                   9588:         } else {
1.691     raeburn  9589:             my $responsenum = $question-1;
                   9590:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9591:                 $responsenum = $respnumlookup->{$question-1};
                   9592:                 if (ref($startline) eq 'HASH') {
                   9593:                     $first = $startline->{$question-1} + 1;
                   9594:                 }
                   9595:             } else {
                   9596:                 $first = $first_bubble_line{$responsenum} + 1;
                   9597:             }
                   9598: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9599:         }
1.506     raeburn  9600:         $last = $first+$count-1;
1.503     raeburn  9601:         push(@lines, ($first..$last));
1.497     foxr     9602:     }
                   9603:     return join(',', @lines);
                   9604: }
                   9605: 
                   9606: =pod 
                   9607: 
                   9608: =item prompt_for_corrections
                   9609: 
                   9610: Prompts for a potentially multiline correction to the
                   9611: user's bubbling (factors out common code from scantron_get_correction
                   9612: for multi and missing bubble cases).
                   9613: 
                   9614:  Arguments:
                   9615:    $r           - Apache request object.
                   9616:    $question    - The question number to prompt for.
                   9617:    $scan_config - The scantron file configuration hash.
                   9618:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  9619:    $error       - Type of error
1.691     raeburn  9620:    $randomorder - True if randomorder in use.
                   9621:    $randompick  - True if randompick in use.
                   9622:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9623:                     for current line to question number used for same question
                   9624:                     in "Master Seqence" (as seen by Course Coordinator).
                   9625:    $startline   - Reference to hash where key is question number (0 is first)
                   9626:                   and value is number of first bubble line for current student
                   9627:                   or code-based randompick and/or randomorder.
                   9628: 
1.497     foxr     9629: 
                   9630:  Implicit inputs:
                   9631:    %bubble_lines_per_response   - Starting line numbers for each question.
                   9632:                                   Numbered from 0 (but question numbers are from
                   9633:                                   1.
                   9634:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  9635:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   9636:                                   type problems render as separate sub-questions, 
1.503     raeburn  9637:                                   in exam mode. This hash contains a 
                   9638:                                   comma-separated list of the lines per 
                   9639:                                   sub-question.
1.510     raeburn  9640:    %responsetype_per_response   - essayresponse, formularesponse,
                   9641:                                   stringresponse, imageresponse, reactionresponse,
                   9642:                                   and organicresponse type problem parts can have
1.503     raeburn  9643:                                   multiple lines per response if the weight
                   9644:                                   assigned exceeds 10.  In this case, only
                   9645:                                   one bubble per line is permitted, but more 
                   9646:                                   than one line might contain bubbles, e.g.
                   9647:                                   bubbling of: line 1 - J, line 2 - J, 
                   9648:                                   line 3 - B would assign 22 points.  
1.497     foxr     9649: 
                   9650: =cut
                   9651: 
                   9652: sub prompt_for_corrections {
1.691     raeburn  9653:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   9654:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  9655:     my ($current_line,$lines);
                   9656:     my @linenums;
                   9657:     my $questionnum = $question;
1.691     raeburn  9658:     my ($first,$responsenum);
1.503     raeburn  9659:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   9660:         $question = $1;
                   9661:         my $subquestion = $2;
1.691     raeburn  9662:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9663:             $responsenum = $respnumlookup->{$question-1};
                   9664:             if (ref($startline) eq 'HASH') {
                   9665:                 $first = $startline->{$question-1};
                   9666:             }
                   9667:         } else {
                   9668:             $responsenum = $question-1;
1.714     raeburn  9669:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  9670:         }
                   9671:         $current_line = $first + 1 ;
                   9672:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9673:         my $subcount = 1;
                   9674:         while ($subcount<$subquestion) {
                   9675:             $current_line += $subans[$subcount-1];
                   9676:             $subcount ++;
                   9677:         }
                   9678:         $lines = $subans[$subquestion-1];
                   9679:     } else {
1.691     raeburn  9680:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9681:             $responsenum = $respnumlookup->{$question-1};
                   9682:             if (ref($startline) eq 'HASH') { 
                   9683:                 $first = $startline->{$question-1};
                   9684:             }
                   9685:         } else {
                   9686:             $responsenum = $question-1;
                   9687:             $first = $first_bubble_line{$responsenum};
                   9688:         }
                   9689:         $current_line = $first + 1;
                   9690:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9691:     }
1.497     foxr     9692:     if ($lines > 1) {
1.503     raeburn  9693:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  9694:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   9695:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   9696:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   9697:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   9698:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   9699:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   9700:             $r->print(
                   9701:                 &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)
                   9702:                .'<br /><br />'
                   9703:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   9704:                .'<br />'
                   9705:                .&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.')
                   9706:                .'<br />'
                   9707:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   9708:                .'<br /><br />'
                   9709:             );
1.503     raeburn  9710:         } else {
                   9711:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   9712:         }
1.497     foxr     9713:     }
                   9714:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  9715:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  9716: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  9717: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  9718:         push(@linenums,$current_line);
1.497     foxr     9719: 	$current_line++;
                   9720:     }
                   9721:     if ($lines > 1) {
                   9722: 	$r->print("<hr /><br />");
                   9723:     }
1.503     raeburn  9724:     return @linenums;
1.157     albertel 9725: }
1.423     albertel 9726: 
                   9727: =pod
                   9728: 
                   9729: =item scantron_bubble_selector
                   9730:   
                   9731:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 9732:    possibly showing the existing the selected bubbles if known
1.423     albertel 9733: 
                   9734:  Arguments:
                   9735:     $r           - Apache request object
1.754     raeburn  9736:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     9737:     $line        - Number of the line being displayed.
1.503     raeburn  9738:     $questionnum - Question number (may include subquestion)
                   9739:     $error       - Type of error.
1.497     foxr     9740:     @selected    - Array of bubbles picked on this line.
1.423     albertel 9741: 
                   9742: =cut
                   9743: 
1.157     albertel 9744: sub scantron_bubble_selector {
1.503     raeburn  9745:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 9746:     my $max=$$scan_config{'Qlength'};
1.274     albertel 9747: 
                   9748:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  9749:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   9750:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   9751:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   9752:             $max=$$scan_config{'BubblesPerRow'};
                   9753:             if (($scmode eq 'number') && ($max > 10)) {
                   9754:                 $max = 10;
                   9755:             } elsif (($scmode eq 'letter') && $max > 26) {
                   9756:                 $max = 26;
                   9757:             }
                   9758:         } else {
                   9759:             $max = 10;
                   9760:         }
                   9761:     }
1.274     albertel 9762: 
1.157     albertel 9763:     my @alphabet=('A'..'Z');
1.503     raeburn  9764:     $r->print(&Apache::loncommon::start_data_table().
                   9765:               &Apache::loncommon::start_data_table_row());
                   9766:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     9767:     for (my $i=0;$i<$max+1;$i++) {
                   9768: 	$r->print("\n".'<td align="center">');
                   9769: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   9770: 	else { $r->print('&nbsp;'); }
                   9771: 	$r->print('</td>');
                   9772:     }
1.503     raeburn  9773:     $r->print(&Apache::loncommon::end_data_table_row().
                   9774:               &Apache::loncommon::start_data_table_row());
1.497     foxr     9775:     for (my $i=0;$i<$max;$i++) {
                   9776: 	$r->print("\n".
                   9777: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   9778: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   9779:     }
1.503     raeburn  9780:     my $nobub_checked = ' ';
                   9781:     if ($error eq 'missingbubble') {
                   9782:         $nobub_checked = ' checked = "checked" ';
                   9783:     }
                   9784:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   9785: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   9786:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   9787:               $line.'" value="'.$questionnum.'" /></td>');
                   9788:     $r->print(&Apache::loncommon::end_data_table_row().
                   9789:               &Apache::loncommon::end_data_table());
1.157     albertel 9790: }
                   9791: 
1.423     albertel 9792: =pod
                   9793: 
                   9794: =item num_matches
                   9795: 
1.424     albertel 9796:    Counts the number of characters that are the same between the two arguments.
                   9797: 
                   9798:  Arguments:
                   9799:    $orig - CODE from the scanline
                   9800:    $code - CODE to match against
                   9801: 
                   9802:  Returns:
                   9803:    $count - integer count of the number of same characters between the
                   9804:             two arguments
                   9805: 
1.423     albertel 9806: =cut
                   9807: 
1.194     albertel 9808: sub num_matches {
                   9809:     my ($orig,$code) = @_;
                   9810:     my @code=split(//,$code);
                   9811:     my @orig=split(//,$orig);
                   9812:     my $same=0;
                   9813:     for (my $i=0;$i<scalar(@code);$i++) {
                   9814: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   9815:     }
                   9816:     return $same;
                   9817: }
                   9818: 
1.423     albertel 9819: =pod
                   9820: 
                   9821: =item scantron_get_closely_matching_CODEs
                   9822: 
1.424     albertel 9823:    Cycles through all CODEs and finds the set that has the greatest
                   9824:    number of same characters as the provided CODE
                   9825: 
                   9826:  Arguments:
                   9827:    $allcodes - hash ref returned by &get_codes()
                   9828:    $CODE     - CODE from the current scanline
                   9829: 
                   9830:  Returns:
                   9831:    2 element list
                   9832:     - first elements is number of how closely matching the best fit is 
                   9833:       (5 means best set has 5 matching characters)
                   9834:     - second element is an arrary ref containing the set of valid CODEs
                   9835:       that best fit the passed in CODE
                   9836: 
1.423     albertel 9837: =cut
                   9838: 
1.194     albertel 9839: sub scantron_get_closely_matching_CODEs {
                   9840:     my ($allcodes,$CODE)=@_;
                   9841:     my @CODEs;
                   9842:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   9843: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   9844:     }
                   9845: 
                   9846:     return ($#CODEs,$CODEs[-1]);
                   9847: }
                   9848: 
1.423     albertel 9849: =pod
                   9850: 
                   9851: =item get_codes
                   9852: 
1.424     albertel 9853:    Builds a hash which has keys of all of the valid CODEs from the selected
                   9854:    set of remembered CODEs.
                   9855: 
                   9856:  Arguments:
                   9857:   $old_name - name of the set of remembered CODEs
                   9858:   $cdom     - domain of the course
                   9859:   $cnum     - internal course name
                   9860: 
                   9861:  Returns:
                   9862:   %allcodes - keys are the valid CODEs, values are all 1
                   9863: 
1.423     albertel 9864: =cut
                   9865: 
1.194     albertel 9866: sub get_codes {
1.280     foxr     9867:     my ($old_name, $cdom, $cnum) = @_;
                   9868:     if (!$old_name) {
                   9869: 	$old_name=$env{'form.scantron_CODElist'};
                   9870:     }
                   9871:     if (!$cdom) {
                   9872: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9873:     }
                   9874:     if (!$cnum) {
                   9875: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   9876:     }
1.278     albertel 9877:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   9878: 				    $cdom,$cnum);
                   9879:     my %allcodes;
                   9880:     if ($result{"type\0$old_name"} eq 'number') {
                   9881: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   9882:     } else {
                   9883: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   9884:     }
1.194     albertel 9885:     return %allcodes;
                   9886: }
                   9887: 
1.423     albertel 9888: =pod
                   9889: 
                   9890: =item scantron_validate_CODE
                   9891: 
1.424     albertel 9892:    Validates all scanlines in the selected file to not have any
                   9893:    invalid or underspecified CODEs and that none of the codes are
                   9894:    duplicated if this was requested.
                   9895: 
1.423     albertel 9896: =cut
                   9897: 
1.157     albertel 9898: sub scantron_validate_CODE {
                   9899:     my ($r,$currentphase) = @_;
1.754     raeburn  9900:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 9901:     if ($scantron_config{'CODElocation'} &&
                   9902: 	$scantron_config{'CODEstart'} &&
                   9903: 	$scantron_config{'CODElength'}) {
1.257     albertel 9904: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 9905: 	    &FIXME_blow_up()
                   9906: 	}
                   9907:     } else {
                   9908: 	return (0,$currentphase+1);
                   9909:     }
                   9910:     
                   9911:     my %usedCODEs;
                   9912: 
1.194     albertel 9913:     my %allcodes=&get_codes();
1.186     albertel 9914: 
1.582     raeburn  9915:     my $nav_error;
1.649     raeburn  9916:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  9917:     if ($nav_error) {
                   9918:         $r->print(&navmap_errormsg());
                   9919:         return(1,$currentphase);
                   9920:     }
1.447     foxr     9921: 
1.186     albertel 9922:     my ($scanlines,$scan_data)=&scantron_getfile();
                   9923:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9924: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 9925: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9926: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9927: 						 $scan_data);
                   9928: 	my $CODE=$$scan_record{'scantron.CODE'};
                   9929: 	my $error=0;
1.224     albertel 9930: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   9931: 	    &scantron_get_correction($r,$i,$scan_record,
                   9932: 				     \%scantron_config,
                   9933: 				     $line,'incorrectCODE',\%allcodes);
                   9934: 	    return(1,$currentphase);
                   9935: 	}
1.221     albertel 9936: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   9937: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 9938: 	    &scantron_get_correction($r,$i,$scan_record,
                   9939: 				     \%scantron_config,
1.194     albertel 9940: 				     $line,'incorrectCODE',\%allcodes);
                   9941: 	    return(1,$currentphase);
1.186     albertel 9942: 	}
1.214     albertel 9943: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 9944: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 9945: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 9946: 	    &scantron_get_correction($r,$i,$scan_record,
                   9947: 				     \%scantron_config,
1.194     albertel 9948: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   9949: 	    return(1,$currentphase);
1.186     albertel 9950: 	}
1.524     raeburn  9951: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 9952:     }
1.157     albertel 9953:     return (0,$currentphase+1);
                   9954: }
                   9955: 
1.423     albertel 9956: =pod
                   9957: 
                   9958: =item scantron_validate_doublebubble
                   9959: 
1.424     albertel 9960:    Validates all scanlines in the selected file to not have any
                   9961:    bubble lines with multiple bubbles marked.
                   9962: 
1.423     albertel 9963: =cut
                   9964: 
1.157     albertel 9965: sub scantron_validate_doublebubble {
                   9966:     my ($r,$currentphase) = @_;
                   9967:     #get student info
                   9968:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9969:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  9970:     my (undef,undef,$sequence)=
                   9971:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 9972: 
                   9973:     #get scantron line setup
1.754     raeburn  9974:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9975:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  9976: 
                   9977:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9978:     unless (ref($navmap)) {
                   9979:         $r->print(&navmap_errormsg());
                   9980:         return(1,$currentphase);
                   9981:     }
                   9982:     my $map=$navmap->getResourceByUrl($sequence);
                   9983:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9984:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9985:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   9986:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9987: 
1.583     raeburn  9988:     my $nav_error;
1.691     raeburn  9989:     if (ref($map)) {
                   9990:         $randomorder = $map->randomorder();
                   9991:         $randompick = $map->randompick();
1.788     raeburn  9992:         unless ($randomorder || $randompick) {
                   9993:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9994:                 if ($res->randomorder()) {
                   9995:                     $randomorder = 1;
                   9996:                 }
                   9997:                 if ($res->randompick()) {
                   9998:                     $randompick = 1;
                   9999:                 }
                   10000:                 last if ($randomorder || $randompick);
                   10001:             }
                   10002:         }
1.691     raeburn  10003:         if ($randomorder || $randompick) {
                   10004:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10005:             if ($nav_error) {
                   10006:                 $r->print(&navmap_errormsg());
                   10007:                 return(1,$currentphase);
                   10008:             }
                   10009:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10010:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   10011:         }
                   10012:     } else {
                   10013:         $r->print(&navmap_errormsg());
                   10014:         return(1,$currentphase);
                   10015:     }
                   10016: 
1.649     raeburn  10017:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  10018:     if ($nav_error) {
                   10019:         $r->print(&navmap_errormsg());
                   10020:         return(1,$currentphase);
                   10021:     }
1.447     foxr     10022: 
1.157     albertel 10023:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 10024: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10025: 	if ($line=~/^[\s\cz]*$/) { next; }
                   10026: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  10027: 						 $scan_data,undef,\%idmap,$randomorder,
                   10028:                                                  $randompick,$sequence,\@master_seq,
                   10029:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   10030:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 10031: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   10032: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   10033: 				 'doublebubble',
1.691     raeburn  10034: 				 $$scan_record{'scantron.doubleerror'},
                   10035:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 10036:     	return (1,$currentphase);
                   10037:     }
                   10038:     return (0,$currentphase+1);
                   10039: }
                   10040: 
1.423     albertel 10041: 
1.503     raeburn  10042: sub scantron_get_maxbubble {
1.649     raeburn  10043:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 10044:     if (defined($env{'form.scantron_maxbubble'}) &&
                   10045: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     10046: 	&restore_bubble_lines();
1.257     albertel 10047: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 10048:     }
1.330     albertel 10049: 
1.447     foxr     10050:     my (undef, undef, $sequence) =
1.257     albertel 10051: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 10052: 
1.447     foxr     10053:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10054:     unless (ref($navmap)) {
                   10055:         if (ref($nav_error)) {
                   10056:             $$nav_error = 1;
                   10057:         }
1.591     raeburn  10058:         return;
1.582     raeburn  10059:     }
1.191     albertel 10060:     my $map=$navmap->getResourceByUrl($sequence);
                   10061:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  10062:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 10063: 
                   10064:     &Apache::lonxml::clear_problem_counter();
                   10065: 
1.557     raeburn  10066:     my $uname       = $env{'user.name'};
                   10067:     my $udom        = $env{'user.domain'};
1.435     foxr     10068:     my $cid         = $env{'request.course.id'};
                   10069:     my $total_lines = 0;
                   10070:     %bubble_lines_per_response = ();
1.447     foxr     10071:     %first_bubble_line         = ();
1.503     raeburn  10072:     %subdivided_bubble_lines   = ();
                   10073:     %responsetype_per_response = ();
1.691     raeburn  10074:     %masterseq_id_responsenum  = ();
1.554     raeburn  10075: 
1.447     foxr     10076:     my $response_number = 0;
                   10077:     my $bubble_line     = 0;
1.191     albertel 10078:     foreach my $resource (@resources) {
1.691     raeburn  10079:         my $resid = $resource->id(); 
1.672     raeburn  10080:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   10081:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  10082:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   10083: 	    foreach my $part_id (@{$parts}) {
                   10084:                 my $lines;
                   10085: 
                   10086: 	        # TODO - make this a persistent hash not an array.
                   10087: 
                   10088:                 # optionresponse, matchresponse and rankresponse type items 
                   10089:                 # render as separate sub-questions in exam mode.
                   10090:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   10091:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   10092:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   10093:                     my ($numbub,$numshown);
                   10094:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   10095:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   10096:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   10097:                         }
                   10098:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   10099:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   10100:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   10101:                         }
                   10102:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   10103:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   10104:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   10105:                         }
                   10106:                     }
                   10107:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   10108:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   10109:                     }
1.649     raeburn  10110:                     my $bubbles_per_row =
                   10111:                         &bubblesheet_bubbles_per_row($scantron_config);
                   10112:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   10113:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  10114:                         $inner_bubble_lines++;
                   10115:                     }
                   10116:                     for (my $i=0; $i<$numshown; $i++) {
                   10117:                         $subdivided_bubble_lines{$response_number} .= 
                   10118:                             $inner_bubble_lines.',';
                   10119:                     }
                   10120:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   10121:                     $lines = $numshown * $inner_bubble_lines;
                   10122:                 } else {
                   10123:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  10124:                 }
1.542     raeburn  10125: 
                   10126:                 $first_bubble_line{$response_number} = $bubble_line;
                   10127: 	        $bubble_lines_per_response{$response_number} = $lines;
                   10128:                 $responsetype_per_response{$response_number} = 
                   10129:                     $analysis->{$part_id.'.type'};
1.691     raeburn  10130:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  10131: 	        $response_number++;
                   10132: 
                   10133: 	        $bubble_line +=  $lines;
                   10134: 	        $total_lines +=  $lines;
                   10135: 	    }
                   10136:         }
                   10137:     }
1.552     raeburn  10138:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  10139: 
                   10140:     &save_bubble_lines();
                   10141:     $env{'form.scantron_maxbubble'} =
                   10142: 	$total_lines;
                   10143:     return $env{'form.scantron_maxbubble'};
                   10144: }
1.523     raeburn  10145: 
1.649     raeburn  10146: sub bubblesheet_bubbles_per_row {
                   10147:     my ($scantron_config) = @_;
                   10148:     my $bubbles_per_row;
                   10149:     if (ref($scantron_config) eq 'HASH') {
                   10150:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   10151:     }
                   10152:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   10153:         $bubbles_per_row = 10;
                   10154:     }
                   10155:     return $bubbles_per_row;
                   10156: }
                   10157: 
1.157     albertel 10158: sub scantron_validate_missingbubbles {
                   10159:     my ($r,$currentphase) = @_;
                   10160:     #get student info
                   10161:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10162:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  10163:     my (undef,undef,$sequence)=
                   10164:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 10165: 
                   10166:     #get scantron line setup
1.754     raeburn  10167:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 10168:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  10169: 
                   10170:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10171:     unless (ref($navmap)) {
                   10172:         $r->print(&navmap_errormsg());
                   10173:         return(1,$currentphase);
                   10174:     }
                   10175: 
                   10176:     my $map=$navmap->getResourceByUrl($sequence);
                   10177:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10178:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10179:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   10180:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10181: 
1.582     raeburn  10182:     my $nav_error;
1.691     raeburn  10183:     if (ref($map)) {
                   10184:         $randomorder = $map->randomorder();
                   10185:         $randompick = $map->randompick();
1.788     raeburn  10186:         unless ($randomorder || $randompick) {
                   10187:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10188:                 if ($res->randomorder()) {
                   10189:                     $randomorder = 1;
                   10190:                 }
                   10191:                 if ($res->randompick()) {
                   10192:                     $randompick = 1;
                   10193:                 }
                   10194:                 last if ($randomorder || $randompick);
                   10195:             }
                   10196:         }
1.691     raeburn  10197:         if ($randomorder || $randompick) {
                   10198:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10199:             if ($nav_error) {
                   10200:                 $r->print(&navmap_errormsg());
                   10201:                 return(1,$currentphase);
                   10202:             }
                   10203:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10204:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   10205:         }
                   10206:     } else {
                   10207:         $r->print(&navmap_errormsg());
                   10208:         return(1,$currentphase);
                   10209:     }
                   10210: 
                   10211: 
1.649     raeburn  10212:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  10213:     if ($nav_error) {
1.691     raeburn  10214:         $r->print(&navmap_errormsg());
1.693     raeburn  10215:         return(1,$currentphase);
1.582     raeburn  10216:     }
1.691     raeburn  10217: 
1.157     albertel 10218:     if (!$max_bubble) { $max_bubble=2**31; }
                   10219:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 10220: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10221: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  10222: 	my $scan_record =
                   10223:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   10224: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   10225:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   10226:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 10227: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   10228: 	my @to_correct;
1.470     foxr     10229: 	
                   10230: 	# Probably here's where the error is...
                   10231: 
1.157     albertel 10232: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  10233:             my $lastbubble;
                   10234:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   10235:                my $question = $1;
                   10236:                my $subquestion = $2;
1.691     raeburn  10237:                my ($first,$responsenum);
                   10238:                if ($randomorder || $randompick) {
                   10239:                    $responsenum = $respnumlookup{$question-1};
                   10240:                    $first = $startline{$question-1};
                   10241:                } else {
                   10242:                    $responsenum = $question-1; 
                   10243:                    $first = $first_bubble_line{$responsenum};
                   10244:                }
                   10245:                if (!defined($first)) { next; }
                   10246:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  10247:                my $subcount = 1;
                   10248:                while ($subcount<$subquestion) {
                   10249:                    $first += $subans[$subcount-1];
                   10250:                    $subcount ++;
                   10251:                }
                   10252:                my $count = $subans[$subquestion-1];
                   10253:                $lastbubble = $first + $count;
                   10254:             } else {
1.691     raeburn  10255:                my ($first,$responsenum);
                   10256:                if ($randomorder || $randompick) {
                   10257:                    $responsenum = $respnumlookup{$missing-1};
                   10258:                    $first = $startline{$missing-1};
                   10259:                } else {
                   10260:                    $responsenum = $missing-1;
                   10261:                    $first = $first_bubble_line{$responsenum};
                   10262:                }
                   10263:                if (!defined($first)) { next; }
                   10264:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  10265:             }
                   10266:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 10267: 	    push(@to_correct,$missing);
                   10268: 	}
                   10269: 	if (@to_correct) {
                   10270: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  10271: 				     $line,'missingbubble',\@to_correct,
                   10272:                                      $randomorder,$randompick,\%respnumlookup,
                   10273:                                      \%startline);
1.157     albertel 10274: 	    return (1,$currentphase);
                   10275: 	}
                   10276: 
                   10277:     }
                   10278:     return (0,$currentphase+1);
                   10279: }
                   10280: 
1.663     raeburn  10281: sub hand_bubble_option {
                   10282:     my (undef, undef, $sequence) =
                   10283:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10284:     return if ($sequence eq '');
                   10285:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10286:     unless (ref($navmap)) {
                   10287:         return;
                   10288:     }
                   10289:     my $needs_hand_bubbles;
                   10290:     my $map=$navmap->getResourceByUrl($sequence);
                   10291:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10292:     foreach my $res (@resources) {
                   10293:         if (ref($res)) {
                   10294:             if ($res->is_problem()) {
                   10295:                 my $partlist = $res->parts();
                   10296:                 foreach my $part (@{ $partlist }) {
                   10297:                     my @types = $res->responseType($part);
                   10298:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   10299:                         $needs_hand_bubbles = 1;
                   10300:                         last;
                   10301:                     }
                   10302:                 }
                   10303:             }
                   10304:         }
                   10305:     }
                   10306:     if ($needs_hand_bubbles) {
1.754     raeburn  10307:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  10308:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10309:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   10310:                &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 />').
                   10311:                '<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  10312:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  10313:     }
                   10314:     return;
                   10315: }
1.423     albertel 10316: 
1.82      albertel 10317: sub scantron_process_students {
1.608     www      10318:     my ($r,$symb) = @_;
1.513     foxr     10319: 
1.257     albertel 10320:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     10321:     if (!$symb) {
                   10322: 	return '';
                   10323:     }
1.324     albertel 10324:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 10325: 
1.754     raeburn  10326:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  10327:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 10328:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 10329:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10330:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 10331:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10332:     unless (ref($navmap)) {
                   10333:         $r->print(&navmap_errormsg());
                   10334:         return '';
1.691     raeburn  10335:     }
1.83      albertel 10336:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10337:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.788     raeburn  10338:         %grader_randomlists_by_symb,%symb_for_examcode);
1.677     raeburn  10339:     if (ref($map)) {
                   10340:         $randomorder = $map->randomorder();
1.689     raeburn  10341:         $randompick = $map->randompick();
1.788     raeburn  10342:         unless ($randomorder || $randompick) {
                   10343:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10344:                 if ($res->randomorder()) {
                   10345:                     $randomorder = 1;
                   10346:                 }
                   10347:                 if ($res->randompick()) {
                   10348:                     $randompick = 1;
                   10349:                 }
                   10350:                 last if ($randomorder || $randompick);
                   10351:             }
                   10352:         }
1.691     raeburn  10353:     } else {
                   10354:         $r->print(&navmap_errormsg());
                   10355:         return '';
1.677     raeburn  10356:     }
1.691     raeburn  10357:     my $nav_error;
1.83      albertel 10358:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10359:     if ($randomorder || $randompick) {
1.788     raeburn  10360:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
1.691     raeburn  10361:         if ($nav_error) {
                   10362:             $r->print(&navmap_errormsg());
                   10363:             return '';
                   10364:         }
                   10365:     }
1.557     raeburn  10366:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  10367:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  10368: 
1.554     raeburn  10369:     my ($uname,$udom);
1.82      albertel 10370:     my $result= <<SCANTRONFORM;
1.81      albertel 10371: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   10372:   <input type="hidden" name="command" value="scantron_configphase" />
                   10373:   $default_form_data
                   10374: SCANTRONFORM
1.82      albertel 10375:     $r->print($result);
                   10376: 
1.770     raeburn  10377:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 10378:     my @delayqueue;
1.542     raeburn  10379:     my (%completedstudents,%scandata);
1.770     raeburn  10380: 
1.520     www      10381:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 10382:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10383:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   10384:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  10385:     $r->print('<br />');
1.140     albertel 10386:     my $start=&Time::HiRes::time();
1.158     albertel 10387:     my $i=-1;
1.542     raeburn  10388:     my $started;
1.447     foxr     10389: 
1.649     raeburn  10390:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10391:     if ($nav_error) {
                   10392:         $r->print(&navmap_errormsg());
                   10393:         return '';
                   10394:     }
                   10395: 
1.513     foxr     10396:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   10397:     # the user and return.
                   10398: 
                   10399:     if ($ssi_error) {
                   10400: 	$r->print("</form>");
                   10401: 	&ssi_print_error($r);
1.520     www      10402:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     10403: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   10404:     }
1.447     foxr     10405: 
1.755     raeburn  10406:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  10407:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  10408:     my %orderedforcode;
1.542     raeburn  10409: 
1.157     albertel 10410:     while ($i<$scanlines->{'count'}) {
                   10411:  	($uname,$udom)=('','');
                   10412:  	$i++;
1.200     albertel 10413:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10414:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 10415: 	if ($started) {
1.667     www      10416: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 10417: 	}
                   10418: 	$started=1;
1.691     raeburn  10419:         my %respnumlookup = ();
                   10420:         my %startline = ();
                   10421:         my $total;
1.157     albertel 10422:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  10423:                                                  $scan_data,undef,\%idmap,$randomorder,
                   10424:                                                  $randompick,$sequence,\@master_seq,
                   10425:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   10426:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   10427:                                                  \$total);
1.157     albertel 10428:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10429:  					      \%idmap,$i)) {
                   10430:   	    &scantron_add_delay(\@delayqueue,$line,
                   10431:  				'Unable to find a student that matches',1);
                   10432:  	    next;
                   10433:   	}
                   10434:  	if (exists $completedstudents{$uname}) {
                   10435:  	    &scantron_add_delay(\@delayqueue,$line,
                   10436:  				'Student '.$uname.' has multiple sheets',2);
                   10437:  	    next;
                   10438:  	}
1.677     raeburn  10439:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  10440:         if (($checksec ne '') && ($checksec ne $usec)) {
                   10441:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   10442:                 &scantron_add_delay(\@delayqueue,$line,
                   10443:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   10444:                 next;
                   10445:             }
                   10446:         }
1.677     raeburn  10447:         my $user = $uname.':'.$usec;
1.157     albertel 10448:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 10449: 
1.677     raeburn  10450:         my $scancode;
                   10451:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10452:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10453:             $scancode = $scan_record->{'scantron.CODE'};
                   10454:         } else {
                   10455:             $scancode = '';
                   10456:         }
                   10457: 
                   10458:         my @mapresources = @resources;
1.689     raeburn  10459:         if ($randomorder || $randompick) {
1.678     raeburn  10460:             @mapresources = 
1.691     raeburn  10461:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10462:                              \%orderedforcode);
1.677     raeburn  10463:         }
1.586     raeburn  10464:         my (%partids_by_symb,$res_error);
1.677     raeburn  10465:         foreach my $resource (@mapresources) {
1.586     raeburn  10466:             my $ressymb;
                   10467:             if (ref($resource)) {
                   10468:                 $ressymb = $resource->symb();
                   10469:             } else {
                   10470:                 $res_error = 1;
                   10471:                 last;
                   10472:             }
1.557     raeburn  10473:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10474:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10475:                 my $currcode;
                   10476:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10477:                     $currcode = $scancode;
                   10478:                 }
1.557     raeburn  10479:                 my ($analysis,$parts) =
1.672     raeburn  10480:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  10481:                                               $uname,$udom,undef,$bubbles_per_row,
                   10482:                                               $currcode);
1.557     raeburn  10483:                 $partids_by_symb{$ressymb} = $parts;
                   10484:             } else {
                   10485:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   10486:             }
1.554     raeburn  10487:         }
                   10488: 
1.586     raeburn  10489:         if ($res_error) {
                   10490:             &scantron_add_delay(\@delayqueue,$line,
                   10491:                                 'An error occurred while grading student '.$uname,2);
                   10492:             next;
                   10493:         }
                   10494: 
1.330     albertel 10495: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  10496:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 10497: 
                   10498: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   10499: 	    &scantron_putfile($scanlines,$scan_data);
                   10500: 	}
1.161     albertel 10501: 	
1.542     raeburn  10502:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10503:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  10504:                                    $bubbles_per_row,$randomorder,$randompick,
                   10505:                                    \%respnumlookup,\%startline) 
                   10506:             eq 'ssi_error') {
1.542     raeburn  10507:             $ssi_error = 0; # So end of handler error message does not trigger.
                   10508:             $r->print("</form>");
                   10509:             &ssi_print_error($r);
                   10510:             &Apache::lonnet::remove_lock($lock);
                   10511:             return '';      # Why return ''?  Beats me.
                   10512:         }
1.513     foxr     10513: 
1.692     raeburn  10514:         if (($scancode) && ($randomorder || $randompick)) {
1.788     raeburn  10515:             foreach my $key (keys(%symb_for_examcode)) {
                   10516:                 my $symb_in_map = $symb_for_examcode{$key};
                   10517:                 if ($symb_in_map ne '') {
                   10518:                     my $parmresult =
                   10519:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   10520:                                                                '0_examcode',2,$scancode,
                   10521:                                                                'string_examcode',$uname,
                   10522:                                                                $udom);
                   10523:                 }
                   10524:             }
1.692     raeburn  10525:         }
1.140     albertel 10526: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  10527:         if ($env{'form.verifyrecord'}) {
                   10528:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  10529:             if ($randompick) {
                   10530:                 if ($total) {
                   10531:                     $lastpos = $total*$scantron_config{'Qlength'};
                   10532:                 }
                   10533:             }
                   10534: 
1.542     raeburn  10535:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10536:             chomp($studentdata);
                   10537:             $studentdata =~ s/\r$//;
                   10538:             my $studentrecord = '';
                   10539:             my $counter = -1;
1.677     raeburn  10540:             foreach my $resource (@mapresources) {
1.554     raeburn  10541:                 my $ressymb = $resource->symb();
1.542     raeburn  10542:                 ($counter,my $recording) =
                   10543:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10544:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10545:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   10546:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  10547:                 $studentrecord .= $recording;
                   10548:             }
                   10549:             if ($studentrecord ne $studentdata) {
1.554     raeburn  10550:                 &Apache::lonxml::clear_problem_counter();
                   10551:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10552:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  10553:                                            $bubbles_per_row,$randomorder,$randompick,
                   10554:                                            \%respnumlookup,\%startline) 
                   10555:                     eq 'ssi_error') {
1.554     raeburn  10556:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   10557:                     $r->print("</form>");
                   10558:                     &ssi_print_error($r);
                   10559:                     &Apache::lonnet::remove_lock($lock);
                   10560:                     delete($completedstudents{$uname});
                   10561:                     return '';
                   10562:                 }
1.542     raeburn  10563:                 $counter = -1;
                   10564:                 $studentrecord = '';
1.677     raeburn  10565:                 foreach my $resource (@mapresources) {
1.554     raeburn  10566:                     my $ressymb = $resource->symb();
1.542     raeburn  10567:                     ($counter,my $recording) =
                   10568:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10569:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10570:                                                  \%scantron_config,\%lettdig,$numletts,
                   10571:                                                  $randomorder,$randompick,\%respnumlookup,
                   10572:                                                  \%startline);
1.542     raeburn  10573:                     $studentrecord .= $recording;
                   10574:                 }
                   10575:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   10576:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  10577:                     if ($scancode eq '') {
1.658     bisitz   10578:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  10579:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   10580:                     } else {
1.658     bisitz   10581:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  10582:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   10583:                     }
                   10584:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   10585:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   10586:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   10587:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   10588:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10589:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   10590:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  10591:                               &Apache::loncommon::end_data_table_row().
                   10592:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10593:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   10594:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  10595:                               &Apache::loncommon::end_data_table_row().
                   10596:                               &Apache::loncommon::end_data_table().'</p>');
                   10597:                 } else {
                   10598:                     $r->print('<br /><span class="LC_warning">'.
                   10599:                              &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 />'.
                   10600:                              &mt("As a consequence, this user's submission history records two tries.").
                   10601:                                  '</span><br />');
                   10602:                 }
                   10603:             }
                   10604:         }
1.543     raeburn  10605:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 10606:     } continue {
1.330     albertel 10607: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  10608: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 10609:     }
1.140     albertel 10610:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      10611:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 10612: #    my $lasttime = &Time::HiRes::time()-$start;
                   10613: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 10614: 
1.200     albertel 10615:     $r->print("</form>");
1.157     albertel 10616:     return '';
1.75      albertel 10617: }
1.157     albertel 10618: 
1.557     raeburn  10619: sub graders_resources_pass {
1.649     raeburn  10620:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   10621:         $bubbles_per_row) = @_;
1.557     raeburn  10622:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   10623:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   10624:         foreach my $resource (@{$resources}) {
                   10625:             my $ressymb = $resource->symb();
                   10626:             my ($analysis,$parts) =
                   10627:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  10628:                                           $env{'user.name'},$env{'user.domain'},
                   10629:                                           1,$bubbles_per_row);
1.557     raeburn  10630:             $grader_partids_by_symb->{$ressymb} = $parts;
                   10631:             if (ref($analysis) eq 'HASH') {
                   10632:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   10633:                     $grader_randomlists_by_symb->{$ressymb} =
                   10634:                         $analysis->{'parts_withrandomlist'};
                   10635:                 }
                   10636:             }
                   10637:         }
                   10638:     }
                   10639:     return;
                   10640: }
                   10641: 
1.678     raeburn  10642: =pod
                   10643: 
                   10644: =item users_order
                   10645: 
                   10646:   Returns array of resources in current map, ordered based on either CODE,
                   10647:   if this is a CODEd exam, or based on student's identity if this is a 
                   10648:   "NAMEd" exam.
                   10649: 
1.691     raeburn  10650:   Should be used when randomorder and/or randompick applied when the 
                   10651:   corresponding exam was printed, prior to students completing bubblesheets 
                   10652:   for the version of the exam the student received.
1.678     raeburn  10653: 
                   10654: =cut
                   10655: 
                   10656: sub users_order  {
1.691     raeburn  10657:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  10658:     my @mapresources;
1.691     raeburn  10659:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  10660:         return @mapresources;
1.691     raeburn  10661:     }
                   10662:     if ($scancode) {
                   10663:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   10664:             @mapresources = @{$orderedforcode->{$scancode}};
                   10665:         } else {
                   10666:             $env{'form.CODE'} = $scancode;
                   10667:             my $actual_seq =
                   10668:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10669:                                                                $master_seq,
                   10670:                                                                $user,$scancode,1);
                   10671:             if (ref($actual_seq) eq 'ARRAY') {
                   10672:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10673:                 if (ref($orderedforcode) eq 'HASH') {
                   10674:                     if (@mapresources > 0) { 
                   10675:                         $orderedforcode->{$scancode} = \@mapresources;
                   10676:                     }
                   10677:                 }
                   10678:             }
                   10679:             delete($env{'form.CODE'});
1.678     raeburn  10680:         }
                   10681:     } else {
                   10682:         my $actual_seq =
                   10683:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10684:                                                            $master_seq,
1.688     raeburn  10685:                                                            $user,undef,1);
1.678     raeburn  10686:         if (ref($actual_seq) eq 'ARRAY') {
                   10687:             @mapresources = 
                   10688:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10689:         }
1.691     raeburn  10690:     }
                   10691:     return @mapresources;
1.678     raeburn  10692: }
                   10693: 
1.542     raeburn  10694: sub grade_student_bubbles {
1.691     raeburn  10695:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   10696:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   10697:     my $uselookup = 0;
                   10698:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   10699:         (ref($startline) eq 'HASH')) {
                   10700:         $uselookup = 1;
                   10701:     }
                   10702: 
1.554     raeburn  10703:     if (ref($resources) eq 'ARRAY') {
                   10704:         my $count = 0;
                   10705:         foreach my $resource (@{$resources}) {
                   10706:             my $ressymb = $resource->symb();
                   10707:             my %form = ('submitted'      => 'scantron',
                   10708:                         'grade_target'   => 'grade',
                   10709:                         'grade_username' => $uname,
                   10710:                         'grade_domain'   => $udom,
                   10711:                         'grade_courseid' => $env{'request.course.id'},
                   10712:                         'grade_symb'     => $ressymb,
                   10713:                         'CODE'           => $scancode
                   10714:                        );
1.649     raeburn  10715:             if ($bubbles_per_row ne '') {
                   10716:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   10717:             }
1.663     raeburn  10718:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   10719:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   10720:             }
1.554     raeburn  10721:             if (ref($parts) eq 'HASH') {
                   10722:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   10723:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  10724:                         if ($uselookup) {
                   10725:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   10726:                         } else {
                   10727:                             $form{'scantron_questnum_start.'.$part} =
                   10728:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   10729:                         }
1.554     raeburn  10730:                         $count++;
                   10731:                     }
                   10732:                 }
                   10733:             }
                   10734:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   10735:             return 'ssi_error' if ($ssi_error);
                   10736:             last if (&Apache::loncommon::connection_aborted($r));
                   10737:         }
1.542     raeburn  10738:     }
                   10739:     return;
                   10740: }
                   10741: 
1.157     albertel 10742: sub scantron_upload_scantron_data {
1.767     raeburn  10743:     my ($r,$symb) = @_;
1.565     raeburn  10744:     my $dom = $env{'request.role.domain'};
1.754     raeburn  10745:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  10746:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   10747:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 10748:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 10749: 							  'domainid',
1.565     raeburn  10750: 							  'coursename',$dom);
                   10751:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   10752:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      10753:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  10754:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  10755:     &js_escape(\$nofile_alert);
1.579     raeburn  10756:     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  10757:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 10758:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 10759:     function checkUpload(formname) {
                   10760: 	if (formname.upfile.value == "") {
1.579     raeburn  10761: 	    alert("'.$nofile_alert.'");
1.157     albertel 10762: 	    return false;
                   10763: 	}
1.565     raeburn  10764:         if (formname.courseid.value == "") {
1.579     raeburn  10765:             alert("'.$nocourseid_alert.'");
1.565     raeburn  10766:             return false;
                   10767:         }
1.157     albertel 10768: 	formname.submit();
                   10769:     }
1.565     raeburn  10770: 
                   10771:     function ToSyllabus() {
                   10772:         var cdom = '."'$dom'".';
                   10773:         var cnum = document.rules.courseid.value;
                   10774:         if (cdom == "" || cdom == null) {
                   10775:             return;
                   10776:         }
                   10777:         if (cnum == "" || cnum == null) {
                   10778:            return;
                   10779:         }
                   10780:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   10781:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   10782:         return;
                   10783:     }
                   10784: 
1.754     raeburn  10785:     '.$formatjs.'
1.597     wenzelju 10786: '));
                   10787:     $r->print('
1.648     bisitz   10788: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  10789: 
1.492     albertel 10790: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  10791: '.$default_form_data.
                   10792:   &Apache::lonhtmlcommon::start_pick_box().
                   10793:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   10794:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   10795:   &Apache::lonhtmlcommon::row_closure().
                   10796:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   10797:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   10798:   &Apache::lonhtmlcommon::row_closure().
                   10799:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   10800:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  10801:   &Apache::lonhtmlcommon::row_closure());
                   10802:     if ($formatoptions) {
                   10803:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   10804:                   &Apache::lonhtmlcommon::row_closure());
                   10805:     }
                   10806:     $r->print(
1.565     raeburn  10807:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   10808:   '<input type="file" name="upfile" size="50" />'.
                   10809:   &Apache::lonhtmlcommon::row_closure(1).
                   10810:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   10811: 
1.492     albertel 10812: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   10813: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 10814: </form>
1.492     albertel 10815: ');
1.157     albertel 10816:     return '';
                   10817: }
                   10818: 
1.754     raeburn  10819: sub scantron_upload_dataformat {
                   10820:     my ($dom) = @_;
                   10821:     my ($formatoptions,$formattitle,$formatjs);
                   10822:     $formatjs = <<'END';
                   10823: function toggleScantab(form) {
                   10824:    return;
                   10825: }
                   10826: END
                   10827:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   10828:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10829:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10830:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   10831:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   10832:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  10833:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   10834:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   10835:                             my ($onclick,$formatextra,$singleline);
                   10836:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   10837:                             my $count = 0;
                   10838:                             foreach my $line (@lines) {
1.790     raeburn  10839:                                 next if (($line =~ /^\#/) || ($line eq ''));
1.756     raeburn  10840:                                 $singleline = $line;
                   10841:                                 $count ++;
                   10842:                             }
                   10843:                             if ($count > 1) {
                   10844:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  10845:                                                '<span class="LC_nobreak">'.
1.776     raeburn  10846:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  10847:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  10848:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   10849:                                 $formatjs = <<"END";
1.754     raeburn  10850: function toggleScantab(form) {
                   10851:     var divid = 'bubbletype';
                   10852:     if (document.getElementById(divid)) {
                   10853:         var radioname = 'fileformat';
                   10854:         var num = form.elements[radioname].length;
                   10855:         if (num) {
                   10856:             for (var i=0; i<num; i++) {
                   10857:                 if (form.elements[radioname][i].checked) {
                   10858:                     var chosen = form.elements[radioname][i].value;
                   10859:                     if (chosen == 'dat') {
                   10860:                         document.getElementById(divid).style.display = 'none';
                   10861:                     } else if (chosen == 'csv') {
1.757     raeburn  10862:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  10863:                     }
                   10864:                 }
                   10865:             }
                   10866:         }
                   10867:     }
                   10868:     return;
                   10869: }
                   10870: 
                   10871: END
1.756     raeburn  10872:                             } elsif ($count == 1) {
                   10873:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   10874:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   10875:                             }
                   10876:                             $formattitle = &mt('File format');
                   10877:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   10878:                                              &mt('Plain Text (no delimiters)').
                   10879:                                              '</label>'.('&nbsp;'x2).
                   10880:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   10881:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  10882:                         }
                   10883:                     }
                   10884:                 }
                   10885:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  10886:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10887:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  10888:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  10889:                         $formatoptions = &scantron_scantab();
                   10890:                     }
1.754     raeburn  10891:                 }
                   10892:             }
                   10893:         }
                   10894:     }
                   10895:     return ($formatoptions,$formattitle,$formatjs);
                   10896: }
1.423     albertel 10897: 
1.157     albertel 10898: sub scantron_upload_scantron_data_save {
1.767     raeburn  10899:     my ($r,$symb) = @_;
1.182     albertel 10900:     my $doanotherupload=
                   10901: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   10902: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 10903: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 10904: 	'</form>'."\n";
1.257     albertel 10905:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 10906: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  10907: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   10908:         !&Apache::lonnet::allowed('usc',
                   10909:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      10910: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      10911: 	unless ($symb) {
1.182     albertel 10912: 	    $r->print($doanotherupload);
                   10913: 	}
1.162     albertel 10914: 	return '';
                   10915:     }
1.257     albertel 10916:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  10917:     my $uploadedfile;
1.710     bisitz   10918:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 10919:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10920:         $r->print(
                   10921:             &Apache::lonhtmlcommon::confirm_success(
                   10922:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10923:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 10924:     } else {
1.754     raeburn  10925:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   10926:         my $parser;
                   10927:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10928:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10929:                 my $is_csv;
                   10930:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   10931:                 if (@possibles > 1) {
                   10932:                     if ($env{'form.fileformat'} eq 'csv') {
                   10933:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10934:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10935:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10936:                                     $is_csv = 1;
                   10937:                                 }
1.754     raeburn  10938:                             }
                   10939:                         }
                   10940:                     }
                   10941:                 } elsif (@possibles == 1) {
                   10942:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10943:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10944:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10945:                                 $is_csv = 1;
                   10946:                             }
1.754     raeburn  10947:                         }
                   10948:                     }
                   10949:                 }
                   10950:                 if ($is_csv) {
                   10951:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   10952:                 }
                   10953:             }
                   10954:         }
                   10955:         my $result =
                   10956:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  10957:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   10958:         if ($result =~ m{^/uploaded/}) {
                   10959:             $r->print(
                   10960:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   10961:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   10962:                         (length($env{'form.upfile'})-1),
                   10963:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  10964:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  10965:             if ($uploadedfile =~ /^scantron_orig_/) {
                   10966:                 my $logname = $uploadedfile;
                   10967:                 $logname =~ s/^scantron_orig_//;
                   10968:                 if ($logname ne '') {
                   10969:                     my $now = time;
                   10970:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   10971:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   10972:                 }
                   10973:             }
1.567     raeburn  10974:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  10975:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   10976:         } else {
                   10977:             $r->print(
                   10978:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   10979:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   10980:                           $result,
1.568     raeburn  10981: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 10982: 	}
                   10983:     }
1.174     albertel 10984:     if ($symb) {
1.612     www      10985: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 10986:     } else {
1.182     albertel 10987: 	$r->print($doanotherupload);
1.174     albertel 10988:     }
1.157     albertel 10989:     return '';
                   10990: }
                   10991: 
1.567     raeburn  10992: sub validate_uploaded_scantron_file {
1.770     raeburn  10993:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   10994: 
1.567     raeburn  10995:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   10996:     my @lines;
                   10997:     if ($scanlines ne '-1') {
                   10998:         @lines=split("\n",$scanlines,-1);
                   10999:     }
1.770     raeburn  11000:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   11001:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   11002:     if ($context eq 'download') {
                   11003:         $priv = 'mgr';
                   11004:     } else {
                   11005:         $priv = 'usc';
                   11006:     }
                   11007:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   11008:             (($env{'request.course.id'}) &&
                   11009:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   11010:         if ($env{'request.course.sec'} ne '') {
                   11011:             unless (&Apache::lonnet::allowed($priv,
                   11012:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   11013:                 unless ($context eq 'download') {
                   11014:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   11015:                 }
                   11016:                 return $output;
                   11017:             }
                   11018:             ($checksec,@possibles)=&gradable_sections();
                   11019:         }
                   11020:     }
1.567     raeburn  11021:     if (@lines) {
                   11022:         my (%counts,$max_match_format);
1.710     bisitz   11023:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  11024:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   11025:         my %idmap = &username_to_idmap($classlist);
                   11026:         foreach my $key (keys(%idmap)) {
                   11027:             my $lckey = lc($key);
                   11028:             $idmap{$lckey} = $idmap{$key};
                   11029:         }
                   11030:         my %unique_formats;
1.754     raeburn  11031:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  11032:         foreach my $line (@formatlines) {
1.790     raeburn  11033:             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  11034:             my @config = split(/:/,$line);
                   11035:             my $idstart = $config[5];
                   11036:             my $idlength = $config[6];
                   11037:             if (($idstart ne '') && ($idlength > 0)) {
                   11038:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   11039:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   11040:                 } else {
                   11041:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   11042:                 }
                   11043:             }
                   11044:         }
                   11045:         foreach my $key (keys(%unique_formats)) {
                   11046:             my ($idstart,$idlength) = split(':',$key);
                   11047:             %{$counts{$key}} = (
                   11048:                                'found'   => 0,
                   11049:                                'total'   => 0,
1.770     raeburn  11050:                                'totalanysec' => 0,
                   11051:                                'othersec' => 0,
1.567     raeburn  11052:                               );
                   11053:             foreach my $line (@lines) {
                   11054:                 next if ($line =~ /^#/);
                   11055:                 next if ($line =~ /^[\s\cz]*$/);
                   11056:                 my $id = substr($line,$idstart-1,$idlength);
                   11057:                 $id = lc($id);
                   11058:                 if (exists($idmap{$id})) {
1.770     raeburn  11059:                     if ($checksec ne '') {
                   11060:                         $counts{$key}{'totalanysec'} ++;
                   11061:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   11062:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   11063:                             if ($stusec ne $checksec) {
                   11064:                                 if (@possibles) {
                   11065:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   11066:                                         $counts{$key}{'othersec'} ++;
                   11067:                                         next;
                   11068:                                     }
                   11069:                                 } else {
                   11070:                                     $counts{$key}{'othersec'} ++;
                   11071:                                     next;
                   11072:                                 }
                   11073:                             }
                   11074:                         }
                   11075:                     }
1.567     raeburn  11076:                     $counts{$key}{'found'} ++;
                   11077:                 }
                   11078:                 $counts{$key}{'total'} ++;
                   11079:             }
                   11080:             if ($counts{$key}{'total'}) {
                   11081:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   11082:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   11083:                     $max_match_pct = $percent_match;
                   11084:                     $max_match_format = $key;
1.710     bisitz   11085:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  11086:                     $max_match_count = $counts{$key}{'total'};
                   11087:                 }
                   11088:             }
                   11089:         }
1.770     raeburn  11090:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  11091:             my $format_descs;
                   11092:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   11093:             for (my $i=0; $i<$numwithformat; $i++) {
                   11094:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   11095:                 if ($i<$numwithformat-2) {
                   11096:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   11097:                 } elsif ($i==$numwithformat-2) {
                   11098:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   11099:                 } elsif ($i==$numwithformat-1) {
                   11100:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   11101:                 }
                   11102:             }
                   11103:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   11104:             $output .= '<br />';
                   11105:             if ($found_match_count == $max_match_count) {
                   11106:                 # 100% matching entries
                   11107:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   11108:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   11109:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   11110:                 &mt('Comparison of student IDs in the uploaded file with'.
                   11111:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   11112:                     ' in the file (for the format defined for [_3]).',
                   11113:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   11114:             } else {
                   11115:                 # Not all entries matching? -> Show warning and additional info
                   11116:                 $output .=
                   11117:                     &Apache::lonhtmlcommon::confirm_success(
                   11118:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   11119:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   11120:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   11121:                     &mt('Comparison of student IDs in the uploaded file with'.
                   11122:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   11123:                         ' in the file (for the format defined for [_3]).',
                   11124:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   11125:                     '<p class="LC_info">'.
                   11126:                     &mt('A low percentage of matches results from one of the following:').
                   11127:                     '</p><ul>'.
                   11128:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   11129:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   11130:                                '<i>'.$cdom.'</i>').'</li>'.
                   11131:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   11132:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   11133:                     '</ul>';
                   11134:             }
1.770     raeburn  11135:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11136:                 if ($counts{$max_match_format}{'othersec'}) {
                   11137:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   11138:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   11139:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   11140:                     &js_escape(\$confirmdel);
                   11141:                     $output .= '<p class="LC_warning">'.
                   11142:                                &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',
                   11143:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   11144:                                '<br />'.
                   11145:                                &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>').
                   11146:                                '</p><p>'.
                   11147:                                &mt('If you prefer to delete the file now, use: [_1]').
                   11148:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   11149:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   11150:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   11151:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   11152:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   11153:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   11154:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   11155:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   11156:                                '</form></p>';
                   11157:                 }
                   11158:             }
1.567     raeburn  11159:         }
1.770     raeburn  11160:         if (($context eq 'download') && ($checksec ne '')) {
                   11161:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11162:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   11163:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   11164:             }
                   11165:         } 
                   11166:     } elsif ($context ne 'download') {
1.710     bisitz   11167:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  11168:     }
                   11169:     return $output;
                   11170: }
                   11171: 
1.770     raeburn  11172: sub gradable_sections {
                   11173:     my $checksec = $env{'request.course.sec'};
                   11174:     my @oksecs;
                   11175:     if ($checksec) {
                   11176:         my %availablesecs = &sections_grade_privs();
                   11177:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   11178:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   11179:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   11180:                     push(@oksecs,$sec);
                   11181:                 }
                   11182:             }
                   11183:             if (grep(/^all$/,@oksecs)) {
                   11184:                 undef($checksec);
                   11185:             }
                   11186:         }
                   11187:     }
                   11188:     return($checksec,@oksecs);
                   11189: }
                   11190: 
                   11191: sub sections_grade_privs {
                   11192:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11193:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11194:     my %availablesecs = (
                   11195:                           mgr => [],
                   11196:                           vgr => [],
                   11197:                           usc => [],
                   11198:                         );
                   11199:     my $ccrole = 'cc';
                   11200:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   11201:         $ccrole = 'co';
                   11202:     }
                   11203:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   11204:                                                      'userroles',['active'],
                   11205:                                                      [$ccrole,'in','cr'],$cdom,1);
                   11206:     my $crsid = $cnum.':'.$cdom;
                   11207:     foreach my $item (keys(%crsroleshash)) {
                   11208:         next unless ($item =~ /^$crsid\:/);
                   11209:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   11210:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   11211:         if ($sec ne '') {
                   11212:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   11213:         }
                   11214:         if (($role eq $ccrole) || ($role eq 'in')) {
                   11215:             foreach my $priv ('mgr','vgr','usc') { 
                   11216:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11217:                     if ($sec eq '') {
                   11218:                         $availablesecs{$priv} = ['all'];
                   11219:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   11220:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11221:                             push(@{$availablesecs{$priv}},$sec);
                   11222:                         }
                   11223:                     }
                   11224:                 }
                   11225:             }
                   11226:         } elsif ($role =~ m{^cr/}) {
                   11227:             foreach my $priv ('mgr','vgr','usc') {
                   11228:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11229:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   11230:                         if ($sec eq '') {
                   11231:                             $availablesecs{$priv} = ['all'];
                   11232:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   11233:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11234:                                 push(@{$availablesecs{$priv}},$sec);
                   11235:                             }
                   11236:                         }
                   11237:                     }
                   11238:                 }
                   11239:             }
                   11240:         }
                   11241:     }
                   11242:     return %availablesecs;
                   11243: }
                   11244: 
                   11245: sub scantron_upload_delete {
                   11246:     my ($r,$symb) = @_;
                   11247:     my $filename = $env{'form.uploadedfile'};
                   11248:     if ($filename =~ /^scantron_orig_/) {
                   11249:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   11250:             &Apache::lonnet::allowed('usc',
                   11251:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   11252:             &Apache::lonnet::allowed('usc',
                   11253:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   11254:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   11255:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   11256:             if ($retrieval eq '-1') {
                   11257:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11258:                           &mt('File requested for deletion not found.'));
                   11259:             } else {
                   11260:                 $filename =~ s/^scantron_orig_//;
                   11261:                 if ($filename ne '') {
                   11262:                     my ($is_valid,$numleft);
                   11263:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11264:                     if (keys(%info)) {
                   11265:                         if (ref($info{$filename}) eq 'HASH') {
                   11266:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   11267:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11268:                                     $is_valid = 1;
                   11269:                                     delete($info{$filename}{$timestamp}); 
                   11270:                                 }
                   11271:                             }
                   11272:                             $numleft = scalar(keys(%{$info{$filename}}));
                   11273:                         }
                   11274:                     }
                   11275:                     if ($is_valid) {
                   11276:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   11277:                         if ($result eq 'ok') {
                   11278:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   11279:                             if ($numleft) {
                   11280:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   11281:                             } else {
                   11282:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11283:                             }
                   11284:                         } else {
                   11285:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11286:                                       &mt('Result was [_1]',$result));
                   11287:                         }
                   11288:                     } else {
                   11289:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11290:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   11291:                     }
                   11292:                 } else {
                   11293:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11294:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11295:                 }
                   11296:             }
                   11297:         } else {
                   11298:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   11299:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   11300:         }
                   11301:     } else {
                   11302:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11303:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11304:     }
                   11305:     return;
                   11306: }
                   11307: 
1.202     albertel 11308: sub valid_file {
                   11309:     my ($requested_file)=@_;
                   11310:     foreach my $filename (sort(&scantron_filenames())) {
                   11311: 	if ($requested_file eq $filename) { return 1; }
                   11312:     }
                   11313:     return 0;
                   11314: }
                   11315: 
                   11316: sub scantron_download_scantron_data {
1.767     raeburn  11317:     my ($r,$symb) = @_;
1.608     www      11318:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 11319:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   11320:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   11321:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 11322:     if (! &valid_file($file)) {
1.492     albertel 11323: 	$r->print('
1.202     albertel 11324: 	<p>
1.686     bisitz   11325: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 11326:         </p>
1.492     albertel 11327: ');
1.202     albertel 11328: 	return;
                   11329:     }
1.770     raeburn  11330:     my (%uploader,$is_owner,%counts,$percent);
                   11331:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   11332:     if (ref($uploader{$file}) eq 'HASH') {
                   11333:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   11334:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11335:                 $is_owner = 1;
                   11336:                 last;
                   11337:             }
                   11338:         }
                   11339:     }
                   11340:     unless ($is_owner) {
                   11341:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   11342:         if ($counts{'totalanysec'}) {
                   11343:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   11344:             if ($percent_othersec >= 10) {
                   11345:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   11346:                 $r->print('<p class="LC_warning">'.
                   11347:                           &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).
                   11348:                           '</p>');
                   11349:                 return;
                   11350:             }
                   11351:         }
                   11352:     }
1.202     albertel 11353:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   11354:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   11355:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   11356:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   11357:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   11358:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 11359:     $r->print('
1.202     albertel 11360:     <p>
1.723     raeburn  11361: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 11362: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 11363:     </p>
                   11364:     <p>
1.492     albertel 11365: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   11366: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 11367:     </p>
                   11368:     <p>
1.492     albertel 11369: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   11370: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 11371:     </p>
1.492     albertel 11372: ');
1.202     albertel 11373:     return '';
                   11374: }
1.157     albertel 11375: 
1.523     raeburn  11376: sub checkscantron_results {
1.608     www      11377:     my ($r,$symb) = @_;
1.523     raeburn  11378:     if (!$symb) {return '';}
                   11379:     my $cid = $env{'request.course.id'};
1.755     raeburn  11380:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  11381:     my $numletts = scalar(keys(%lettdig));
                   11382:     my $cnum = $env{'course.'.$cid.'.num'};
                   11383:     my $cdom = $env{'course.'.$cid.'.domain'};
                   11384:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   11385:     my %record;
                   11386:     my %scantron_config =
1.754     raeburn  11387:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  11388:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  11389:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  11390:     my $classlist=&Apache::loncoursedata::get_classlist();
                   11391:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   11392:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  11393:     unless (ref($navmap)) {
                   11394:         $r->print(&navmap_errormsg());
                   11395:         return '';
                   11396:     }
1.523     raeburn  11397:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  11398:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   11399:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  11400:     if (ref($map)) { 
                   11401:         $randomorder=$map->randomorder();
1.689     raeburn  11402:         $randompick=$map->randompick();
1.788     raeburn  11403:         unless ($randomorder || $randompick) {
                   11404:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   11405:                 if ($res->randomorder()) {
                   11406:                     $randomorder = 1;
                   11407:                 }
                   11408:                 if ($res->randompick()) {
                   11409:                     $randompick = 1;
                   11410:                 }
                   11411:                 last if ($randomorder || $randompick);
                   11412:             }
                   11413:         }
1.677     raeburn  11414:     }
1.557     raeburn  11415:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  11416:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   11417:     if ($nav_error) {
                   11418:         $r->print(&navmap_errormsg());
                   11419:         return '';
1.678     raeburn  11420:     }
1.673     raeburn  11421:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   11422:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  11423:     my ($uname,$udom);
1.523     raeburn  11424:     my (%scandata,%lastname,%bylast);
                   11425:     $r->print('
                   11426: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   11427: 
                   11428:     my @delayqueue;
                   11429:     my %completedstudents;
                   11430: 
1.691     raeburn  11431:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      11432:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  11433:     my ($username,$domain,$started);
1.649     raeburn  11434:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  11435:     if ($nav_error) {
                   11436:         $r->print(&navmap_errormsg());
                   11437:         return '';
                   11438:     }
1.523     raeburn  11439: 
1.667     www      11440:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  11441:     my $start=&Time::HiRes::time();
                   11442:     my $i=-1;
                   11443: 
                   11444:     while ($i<$scanlines->{'count'}) {
                   11445:         ($username,$domain,$uname)=('','','');
                   11446:         $i++;
                   11447:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   11448:         if ($line=~/^[\s\cz]*$/) { next; }
                   11449:         if ($started) {
1.667     www      11450:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  11451:         }
                   11452:         $started=1;
                   11453:         my $scan_record=
                   11454:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   11455:                                                      $scan_data);
1.693     raeburn  11456:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   11457:                                               \%idmap,$i)) {
1.523     raeburn  11458:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11459:                                 'Unable to find a student that matches',1);
                   11460:             next;
                   11461:         }
                   11462:         if (exists $completedstudents{$uname}) {
                   11463:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11464:                                 'Student '.$uname.' has multiple sheets',2);
                   11465:             next;
                   11466:         }
                   11467:         my $pid = $scan_record->{'scantron.ID'};
                   11468:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   11469:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  11470:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   11471:         my $user = $uname.':'.$usec;
1.523     raeburn  11472:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  11473: 
1.678     raeburn  11474:         my $scancode;
1.677     raeburn  11475:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   11476:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   11477:             $scancode = $scan_record->{'scantron.CODE'};
                   11478:         } else {
                   11479:             $scancode = '';
                   11480:         }
                   11481: 
                   11482:         my @mapresources = @resources;
1.691     raeburn  11483:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   11484:         my %respnumlookup=();
                   11485:         my %startline=();
1.689     raeburn  11486:         if ($randomorder || $randompick) {
1.678     raeburn  11487:             @mapresources =
1.691     raeburn  11488:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   11489:                              \%orderedforcode);
                   11490:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   11491:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   11492:                                              \%grader_partids_by_symb,\%orderedforcode,
                   11493:                                              \%respnumlookup,\%startline);
                   11494:             if ($randompick && $total) {
                   11495:                 $lastpos = $total*$scantron_config{'Qlength'};
                   11496:             }
1.677     raeburn  11497:         }
1.691     raeburn  11498:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   11499:         chomp($scandata{$pid});
                   11500:         $scandata{$pid} =~ s/\r$//;
                   11501: 
1.523     raeburn  11502:         my $counter = -1;
1.677     raeburn  11503:         foreach my $resource (@mapresources) {
1.557     raeburn  11504:             my $parts;
1.554     raeburn  11505:             my $ressymb = $resource->symb();
1.557     raeburn  11506:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   11507:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  11508:                 my $currcode;
                   11509:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   11510:                     $currcode = $scancode;
                   11511:                 }
1.557     raeburn  11512:                 (my $analysis,$parts) =
1.672     raeburn  11513:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   11514:                                               $username,$domain,undef,
1.741     raeburn  11515:                                               $bubbles_per_row,$currcode);
1.557     raeburn  11516:             } else {
                   11517:                 $parts = $grader_partids_by_symb{$ressymb};
                   11518:             }
1.542     raeburn  11519:             ($counter,my $recording) =
                   11520:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  11521:                                          $scandata{$pid},$parts,
1.691     raeburn  11522:                                          \%scantron_config,\%lettdig,$numletts,
                   11523:                                          $randomorder,$randompick,
                   11524:                                          \%respnumlookup,\%startline);
1.542     raeburn  11525:             $record{$pid} .= $recording;
1.523     raeburn  11526:         }
                   11527:     }
                   11528:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   11529:     $r->print('<br />');
                   11530:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   11531:     $passed = 0;
                   11532:     $failed = 0;
                   11533:     $numstudents = 0;
                   11534:     foreach my $last (sort(keys(%bylast))) {
                   11535:         if (ref($bylast{$last}) eq 'ARRAY') {
                   11536:             foreach my $pid (sort(@{$bylast{$last}})) {
                   11537:                 my $showscandata = $scandata{$pid};
                   11538:                 my $showrecord = $record{$pid};
                   11539:                 $showscandata =~ s/\s/&nbsp;/g;
                   11540:                 $showrecord =~ s/\s/&nbsp;/g;
                   11541:                 if ($scandata{$pid} eq $record{$pid}) {
                   11542:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   11543:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      11544: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  11545: '</tr>'."\n".
                   11546: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11547: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  11548:                     $passed ++;
                   11549:                 } else {
                   11550:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      11551:                     $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  11552: '</tr>'."\n".
                   11553: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11554: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  11555: '</tr>'."\n";
                   11556:                     $failed ++;
                   11557:                 }
                   11558:                 $numstudents ++;
                   11559:             }
                   11560:         }
                   11561:     }
1.648     bisitz   11562:     $r->print(
                   11563:         '<p>'
                   11564:        .&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).',
                   11565:             '<b>',
                   11566:             $numstudents,
                   11567:             '</b>',
                   11568:             $env{'form.scantron_maxbubble'})
                   11569:        .'</p>'
                   11570:     );
1.682     raeburn  11571:     $r->print('<p>'
1.683     raeburn  11572:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  11573:              .'<br />'
                   11574:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   11575:              .'</p>'
                   11576:     );
1.523     raeburn  11577:     if ($passed) {
1.572     www      11578:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11579:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11580:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11581:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11582:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11583:                  $okstudents."\n".
                   11584:                  &Apache::loncommon::end_data_table().'<br />');
                   11585:     }
                   11586:     if ($failed) {
1.572     www      11587:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11588:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11589:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11590:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11591:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11592:                  $badstudents."\n".
                   11593:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      11594:                  &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  11595:     }
1.614     www      11596:     $r->print('</form><br />');
1.523     raeburn  11597:     return;
                   11598: }
                   11599: 
1.542     raeburn  11600: sub verify_scantron_grading {
1.554     raeburn  11601:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  11602:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   11603:         $respnumlookup,$startline) = @_;
1.542     raeburn  11604:     my ($record,%expected,%startpos);
                   11605:     return ($counter,$record) if (!ref($resource));
                   11606:     return ($counter,$record) if (!$resource->is_problem());
                   11607:     my $symb = $resource->symb();
1.554     raeburn  11608:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   11609:     foreach my $part_id (@{$partids}) {
1.542     raeburn  11610:         $counter ++;
                   11611:         $expected{$part_id} = 0;
1.691     raeburn  11612:         my $respnum = $counter;
                   11613:         if ($randomorder || $randompick) {
                   11614:             $respnum = $respnumlookup->{$counter};
                   11615:             $startpos{$part_id} = $startline->{$counter} + 1;
                   11616:         } else {
                   11617:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   11618:         }
                   11619:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   11620:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  11621:             foreach my $item (@sub_lines) {
                   11622:                 $expected{$part_id} += $item;
                   11623:             }
                   11624:         } else {
1.691     raeburn  11625:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  11626:         }
                   11627:     }
                   11628:     if ($symb) {
                   11629:         my %recorded;
                   11630:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   11631:         if ($returnhash{'version'}) {
                   11632:             my %lasthash=();
                   11633:             my $version;
                   11634:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   11635:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   11636:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   11637:                 }
                   11638:             }
                   11639:             foreach my $key (keys(%lasthash)) {
                   11640:                 if ($key =~ /\.scantron$/) {
                   11641:                     my $value = &unescape($lasthash{$key});
                   11642:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   11643:                     if ($value eq '') {
                   11644:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11645:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   11646:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11647:                             }
                   11648:                         }
                   11649:                     } else {
                   11650:                         my @tocheck;
                   11651:                         my @items = split(//,$value);
                   11652:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   11653:                             ($scantron_config->{'Qon'} eq 'number')) {
                   11654:                             if (@items < $expected{$part_id}) {
                   11655:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   11656:                                 my @singles = split(//,$fragment);
                   11657:                                 foreach my $pos (@singles) {
                   11658:                                     if ($pos eq ' ') {
                   11659:                                         push(@tocheck,$pos);
                   11660:                                     } else {
                   11661:                                         my $next = shift(@items);
                   11662:                                         push(@tocheck,$next);
                   11663:                                     }
                   11664:                                 }
                   11665:                             } else {
                   11666:                                 @tocheck = @items;
                   11667:                             }
                   11668:                             foreach my $letter (@tocheck) {
                   11669:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   11670:                                     if ($letter !~ /^[A-J]$/) {
                   11671:                                         $letter = $scantron_config->{'Qoff'};
                   11672:                                     }
                   11673:                                     $recorded{$part_id} .= $letter;
                   11674:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   11675:                                     my $digit;
                   11676:                                     if ($letter !~ /^[A-J]$/) {
                   11677:                                         $digit = $scantron_config->{'Qoff'};
                   11678:                                     } else {
                   11679:                                         $digit = $lettdig->{$letter};
                   11680:                                     }
                   11681:                                     $recorded{$part_id} .= $digit;
                   11682:                                 }
                   11683:                             }
                   11684:                         } else {
                   11685:                             @tocheck = @items;
                   11686:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11687:                                 my $curr_sub = shift(@tocheck);
                   11688:                                 my $digit;
                   11689:                                 if ($curr_sub =~ /^[A-J]$/) {
                   11690:                                     $digit = $lettdig->{$curr_sub}-1;
                   11691:                                 }
                   11692:                                 if ($curr_sub eq 'J') {
                   11693:                                     $digit += scalar($numletts);
                   11694:                                 }
                   11695:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11696:                                     if ($j == $digit) {
                   11697:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   11698:                                     } else {
                   11699:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11700:                                     }
                   11701:                                 }
                   11702:                             }
                   11703:                         }
                   11704:                     }
                   11705:                 }
                   11706:             }
                   11707:         }
1.554     raeburn  11708:         foreach my $part_id (@{$partids}) {
1.542     raeburn  11709:             if ($recorded{$part_id} eq '') {
                   11710:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11711:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11712:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11713:                     }
                   11714:                 }
                   11715:             }
                   11716:             $record .= $recorded{$part_id};
                   11717:         }
                   11718:     }
                   11719:     return ($counter,$record);
                   11720: }
                   11721: 
1.75      albertel 11722: #-------- end of section for handling grading scantron forms -------
                   11723: #
                   11724: #-------------------------------------------------------------------
                   11725: 
1.72      ng       11726: #-------------------------- Menu interface -------------------------
                   11727: #
1.614     www      11728: #--- Href with symb and command ---
                   11729: 
                   11730: sub href_symb_cmd {
                   11731:     my ($symb,$cmd)=@_;
1.796     raeburn  11732:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.
                   11733:            &HTML::Entities::encode($cmd,'<>&"');
1.72      ng       11734: }
                   11735: 
1.443     banghart 11736: sub grading_menu {
1.608     www      11737:     my ($request,$symb) = @_;
1.443     banghart 11738:     if (!$symb) {return '';}
                   11739: 
                   11740:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      11741:                   'command'=>'individual');
1.538     schulted 11742:     
1.598     www      11743:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11744: 
                   11745:     $fields{'command'}='ungraded';
                   11746:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11747: 
                   11748:     $fields{'command'}='table';
                   11749:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11750: 
                   11751:     $fields{'command'}='all_for_one';
                   11752:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11753: 
1.621     www      11754:     $fields{'command'}='downloadfilesselect';
                   11755:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11756: 
1.443     banghart 11757:     $fields{'command'} = 'csvform';
1.538     schulted 11758:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11759:     
1.443     banghart 11760:     $fields{'command'} = 'processclicker';
1.538     schulted 11761:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11762:     
1.443     banghart 11763:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 11764:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      11765: 
                   11766:     $fields{'command'} = 'initialverifyreceipt';
                   11767:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  11768: 
                   11769:     my %permissions;
                   11770:     if ($perm{'mgr'}) {
                   11771:         $permissions{'either'} = 'F';
                   11772:         $permissions{'mgr'} = 'F';
                   11773:     }
                   11774:     if ($perm{'vgr'}) {
                   11775:         $permissions{'either'} = 'F';
                   11776:         $permissions{'vgr'} = 'F';
                   11777:     }
                   11778: 
1.598     www      11779:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 11780:             items =>[
1.598     www      11781:                         {	linktext => 'Select individual students to grade',
                   11782:                     		url => $url1a,
1.781     raeburn  11783:                     		permission => $permissions{'either'},
1.636     wenzelju 11784:                     		icon => 'grade_students.png',
1.598     www      11785:                     		linktitle => 'Grade current resource for a selection of students.'
                   11786:                         }, 
1.764     raeburn  11787:                         {       linktext => 'Grade ungraded submissions',
1.598     www      11788:                                 url => $url1b,
1.781     raeburn  11789:                                 permission => $permissions{'either'},
1.636     wenzelju 11790:                                 icon => 'ungrade_sub.png',
1.598     www      11791:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 11792:                         },
1.598     www      11793: 
                   11794:                         {       linktext => 'Grading table',
                   11795:                                 url => $url1c,
1.781     raeburn  11796:                                 permission => $permissions{'either'},
1.636     wenzelju 11797:                                 icon => 'grading_table.png',
1.598     www      11798:                                 linktitle => 'Grade current resource for all students.'
                   11799:                         },
1.615     www      11800:                         {       linktext => 'Grade page/folder for one student',
1.598     www      11801:                                 url => $url1d,
1.781     raeburn  11802:                                 permission => $permissions{'either'},
1.636     wenzelju 11803:                                 icon => 'grade_PageFolder.png',
1.598     www      11804:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      11805:                         },
                   11806:                         {       linktext => 'Download submissions',
                   11807:                                 url => $url1e,
1.781     raeburn  11808:                                 permission => $permissions{'either'},
1.636     wenzelju 11809:                                 icon => 'download_sub.png',
1.621     www      11810:                                 linktitle => 'Download all students submissions.'
1.598     www      11811:                         }]},
                   11812:                          { categorytitle=>'Automated Grading',
                   11813:                items =>[
                   11814: 
1.538     schulted 11815:                 	    {	linktext => 'Upload Scores',
                   11816:                     		url => $url2,
1.780     raeburn  11817:                     		permission => $permissions{'mgr'},
1.538     schulted 11818:                     		icon => 'uploadscores.png',
                   11819:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   11820:                 	    },
                   11821:                 	    {	linktext => 'Process Clicker',
                   11822:                     		url => $url3,
1.780     raeburn  11823:                     		permission => $permissions{'mgr'},
1.538     schulted 11824:                     		icon => 'addClickerInfoFile.png',
                   11825:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   11826:                 	    },
1.587     raeburn  11827:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 11828:                     		url => $url4,
1.780     raeburn  11829:                     		permission => $permissions{'mgr'},
1.636     wenzelju 11830:                     		icon => 'bubblesheet.png',
1.648     bisitz   11831:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      11832:                 	    },
1.616     www      11833:                             {   linktext => 'Verify Receipt Number',
1.602     www      11834:                                 url => $url5,
1.780     raeburn  11835:                                 permission => $permissions{'either'},
1.636     wenzelju 11836:                                 icon => 'receipt_number.png',
1.602     www      11837:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   11838:                             }
                   11839: 
1.538     schulted 11840:                     ]
                   11841:             });
1.796     raeburn  11842:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   11843:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   11844:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   11845:     if (keys(%passback)) {
                   11846:         $fields{'command'} = 'initialpassback';
                   11847:         my $url6 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11848:         push (@{$menu[1]{items}},
                   11849:                   { linktext => 'Passback of Scores',
                   11850:                     url => $url6,
                   11851:                     permission => $permissions{'either'},
                   11852:                     icon => 'passback.png',
                   11853:                     linktitle => 'Passback scores to launcher CMS for resources accessed via LTI-mediated deep-linking',
                   11854:                   });
                   11855:     }
1.443     banghart 11856:     # Create the menu
                   11857:     my $Str;
1.445     banghart 11858:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   11859:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      11860:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 11861: 
1.602     www      11862:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 11863:     return $Str;    
                   11864: }
                   11865: 
1.598     www      11866: sub ungraded {
                   11867:     my ($request)=@_;
                   11868:     &submit_options($request);
                   11869: }
                   11870: 
1.599     www      11871: sub submit_options_sequence {
1.608     www      11872:     my ($request,$symb) = @_;
1.599     www      11873:     if (!$symb) {return '';}
1.600     www      11874:     &commonJSfunctions($request);
                   11875:     my $result;
1.599     www      11876: 
1.600     www      11877:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11878:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      11879:     $result.=&selectfield(0).
1.601     www      11880:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      11881:             <div>
                   11882:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11883:             </div>
                   11884:         </div>
                   11885:   </form>';
                   11886:     return $result;
                   11887: }
                   11888: 
                   11889: sub submit_options_table {
1.608     www      11890:     my ($request,$symb) = @_;
1.600     www      11891:     if (!$symb) {return '';}
1.599     www      11892:     &commonJSfunctions($request);
1.746     raeburn  11893:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      11894:     my $result;
                   11895: 
                   11896:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11897:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      11898: 
1.745     raeburn  11899:     $result.=&selectfield(1,$is_tool).
1.601     www      11900:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      11901:             <div>
                   11902:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11903:             </div>
                   11904:         </div>
                   11905:   </form>';
                   11906:     return $result;
                   11907: }
1.443     banghart 11908: 
1.621     www      11909: sub submit_options_download {
                   11910:     my ($request,$symb) = @_;
                   11911:     if (!$symb) {return '';}
                   11912: 
1.773     raeburn  11913:     my $res_error;
                   11914:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   11915:         &response_type($symb,\$res_error);
                   11916:     if ($res_error) {
                   11917:         $request->print(&mt('An error occurred retrieving response types'));
                   11918:         return;
                   11919:     }
                   11920:     unless ($numessay) {
                   11921:         $request->print(&mt('No essayresponse items found'));
                   11922:         return;
                   11923:     }
                   11924:     my $table;
                   11925:     if (ref($partlist) eq 'ARRAY') {
                   11926:         if (scalar(@$partlist) > 1 ) {
                   11927:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   11928:         }
                   11929:     }
                   11930: 
1.746     raeburn  11931:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      11932:     &commonJSfunctions($request);
                   11933: 
                   11934:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  11935:                $table."\n".
                   11936:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      11937:     $result.='
                   11938: <h2>
1.750     raeburn  11939:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  11940: </h2>'.&selectfield(1,$is_tool).'
1.621     www      11941:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   11942:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11943:             </div>
                   11944:           </div>
1.600     www      11945: 
                   11946: 
1.621     www      11947:   </form>';
                   11948:     return $result;
                   11949: }
                   11950: 
1.443     banghart 11951: #--- Displays the submissions first page -------
                   11952: sub submit_options {
1.608     www      11953:     my ($request,$symb) = @_;
1.72      ng       11954:     if (!$symb) {return '';}
                   11955: 
1.746     raeburn  11956:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       11957:     &commonJSfunctions($request);
1.473     albertel 11958:     my $result;
1.533     bisitz   11959: 
1.72      ng       11960:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11961: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  11962:     $result.=&selectfield(1,$is_tool).'
1.601     www      11963:                 <input type="hidden" name="command" value="submission" /> 
                   11964: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11965:             </div>
                   11966:           </div>
                   11967:   </form>';
                   11968:     return $result;
                   11969: }
1.533     bisitz   11970: 
1.601     www      11971: sub selectfield {
1.745     raeburn  11972:    my ($full,$is_tool)=@_;
                   11973:    my %options;
                   11974:    if ($is_tool) {
                   11975:        %options =
                   11976:            (&transtatus_options,
                   11977:             'select_form_order' => ['yes','incorrect','all']);
                   11978:    } else {
                   11979:        %options = 
                   11980:            (&substatus_options,
                   11981:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   11982:    }
1.782     raeburn  11983: 
                   11984:   #
                   11985:   # PrepareClasslist() needs to be called to avoid getting a sections list
                   11986:   # for a different course from the @Sections global in lonstatistics.pm, 
                   11987:   # populated by an earlier request.
                   11988:   #
                   11989:    &Apache::lonstatistics::PrepareClasslist();
                   11990: 
1.601     www      11991:    my $result='<div class="LC_columnSection">
1.537     harmsja  11992:   
1.533     bisitz   11993:     <fieldset>
                   11994:       <legend>
                   11995:        '.&mt('Sections').'
                   11996:       </legend>
1.601     www      11997:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   11998:     </fieldset>
1.537     harmsja  11999:   
1.533     bisitz   12000:     <fieldset>
                   12001:       <legend>
                   12002:         '.&mt('Groups').'
                   12003:       </legend>
                   12004:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   12005:     </fieldset>
1.537     harmsja  12006:   
1.533     bisitz   12007:     <fieldset>
                   12008:       <legend>
                   12009:         '.&mt('Access Status').'
                   12010:       </legend>
1.601     www      12011:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   12012:     </fieldset>';
                   12013:     if ($full) {
1.745     raeburn  12014:         my $heading = &mt('Submission Status');
                   12015:         if ($is_tool) {
                   12016:             $heading = &mt('Transaction Status');
                   12017:         }
                   12018:         $result.='
1.533     bisitz   12019:     <fieldset>
                   12020:       <legend>
1.745     raeburn  12021:         '.$heading.'
1.601     www      12022:       </legend>'.
1.635     raeburn  12023:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      12024:    '</fieldset>';
                   12025:     }
                   12026:     $result.='</div><br />';
1.44      ng       12027:     return $result;
1.2       albertel 12028: }
                   12029: 
1.738     raeburn  12030: sub substatus_options {
                   12031:     return &Apache::lonlocal::texthash(
                   12032:                                       'yes'       => 'with submissions',
                   12033:                                       'queued'    => 'in grading queue',
                   12034:                                       'graded'    => 'with ungraded submissions',
                   12035:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  12036:                                       'all'       => 'with any status',
                   12037:                                       );
1.738     raeburn  12038: }
                   12039: 
1.745     raeburn  12040: sub transtatus_options {
                   12041:     return &Apache::lonlocal::texthash(
                   12042:                                        'yes'       => 'with score transactions',
                   12043:                                        'incorrect' => 'with less than full credit',
                   12044:                                        'all'       => 'with any status',
                   12045:                                       );
                   12046: }
                   12047: 
1.285     albertel 12048: sub reset_perm {
                   12049:     undef(%perm);
                   12050: }
                   12051: 
                   12052: sub init_perm {
                   12053:     &reset_perm();
1.770     raeburn  12054:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 12055: 
                   12056: 	my $scope = $env{'request.course.id'};
                   12057: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   12058: 
                   12059: 	    $scope .= '/'.$env{'request.course.sec'};
                   12060: 	    if ( $perm{$test_perm}=
                   12061: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   12062: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   12063: 	    } else {
                   12064: 		delete($perm{$test_perm});
                   12065: 	    }
1.285     albertel 12066: 	}
                   12067:     }
                   12068: }
                   12069: 
1.674     raeburn  12070: sub init_old_essays {
                   12071:     my ($symb,$apath,$adom,$aname) = @_;
                   12072:     if ($symb ne '') {
                   12073:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   12074:         if (keys(%essays) > 0) {
                   12075:             $old_essays{$symb} = \%essays;
                   12076:         }
                   12077:     }
                   12078:     return;
                   12079: }
                   12080: 
                   12081: sub reset_old_essays {
                   12082:     undef(%old_essays);
                   12083: }
                   12084: 
1.400     www      12085: sub gather_clicker_ids {
1.408     albertel 12086:     my %clicker_ids;
1.400     www      12087: 
                   12088:     my $classlist = &Apache::loncoursedata::get_classlist();
                   12089: 
                   12090:     # Set up a couple variables.
1.407     albertel 12091:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   12092:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      12093:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      12094: 
1.407     albertel 12095:     foreach my $student (keys(%$classlist)) {
1.438     www      12096:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 12097:         my $username = $classlist->{$student}->[$username_idx];
                   12098:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      12099:         my $clickers =
1.408     albertel 12100: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      12101:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      12102:             $id=~s/^[\#0]+//;
1.421     www      12103:             $id=~s/[\-\:]//g;
1.407     albertel 12104:             if (exists($clicker_ids{$id})) {
1.408     albertel 12105: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      12106:             } else {
1.408     albertel 12107: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      12108:             }
                   12109:         }
                   12110:     }
1.407     albertel 12111:     return %clicker_ids;
1.400     www      12112: }
                   12113: 
1.402     www      12114: sub gather_adv_clicker_ids {
1.408     albertel 12115:     my %clicker_ids;
1.402     www      12116:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   12117:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   12118:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 12119:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      12120:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   12121:             my ($puname,$pudom)=split(/\:/,$person);
                   12122:             my $clickers =
1.408     albertel 12123: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      12124:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      12125: 		$id=~s/^[\#0]+//;
1.421     www      12126:                 $id=~s/[\-\:]//g;
1.408     albertel 12127: 		if (exists($clicker_ids{$id})) {
                   12128: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   12129: 		} else {
                   12130: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   12131: 		}
1.405     www      12132:             }
1.402     www      12133:         }
                   12134:     }
1.407     albertel 12135:     return %clicker_ids;
1.402     www      12136: }
                   12137: 
1.413     www      12138: sub clicker_grading_parameters {
                   12139:     return ('gradingmechanism' => 'scalar',
                   12140:             'upfiletype' => 'scalar',
                   12141:             'specificid' => 'scalar',
                   12142:             'pcorrect' => 'scalar',
                   12143:             'pincorrect' => 'scalar');
                   12144: }
                   12145: 
1.400     www      12146: sub process_clicker {
1.608     www      12147:     my ($r,$symb)=@_;
1.400     www      12148:     if (!$symb) {return '';}
                   12149:     my $result=&checkforfile_js();
1.632     www      12150:     $result.=&Apache::loncommon::start_data_table().
                   12151:              &Apache::loncommon::start_data_table_header_row().
                   12152:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   12153:              &Apache::loncommon::end_data_table_header_row().
                   12154:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      12155: # Attempt to restore parameters from last session, set defaults if not present
                   12156:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12157:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   12158:                                                  \%Saveable_Parameters);
                   12159:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   12160:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   12161:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   12162:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   12163: 
                   12164:     my %checked;
1.521     www      12165:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      12166:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   12167:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      12168:        }
                   12169:     }
                   12170: 
1.632     www      12171:     my $upload=&mt("Evaluate File");
1.400     www      12172:     my $type=&mt("Type");
1.402     www      12173:     my $attendance=&mt("Award points just for participation");
                   12174:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      12175:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      12176:     my $given=&mt("Correctness determined from given list of answers").' '.
                   12177:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      12178:     my $pcorrect=&mt("Percentage points for correct solution");
                   12179:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      12180:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  12181: 						   {'iclicker' => 'i>clicker',
1.666     www      12182:                                                     'interwrite' => 'interwrite PRS',
                   12183:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 12184:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 12185:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      12186: function sanitycheck() {
                   12187: // Accept only integer percentages
                   12188:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   12189:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   12190: // Find out grading choice
                   12191:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12192:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   12193:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   12194:       }
                   12195:    }
                   12196: // By default, new choice equals user selection
                   12197:    newgradingchoice=gradingchoice;
                   12198: // Not good to give more points for false answers than correct ones
                   12199:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   12200:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   12201:    }
                   12202: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   12203:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   12204:       document.forms.gradesupload.pcorrect.value=100;
                   12205:       document.forms.gradesupload.pincorrect.value=100;
                   12206:    }
                   12207: // If the values are different, cannot be attendance only
                   12208:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   12209:        (gradingchoice=='attendance')) {
                   12210:        newgradingchoice='personnel';
                   12211:    }
                   12212: // Change grading choice to new one
                   12213:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12214:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   12215:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   12216:       } else {
                   12217:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   12218:       }
                   12219:    }
                   12220: // Remember the old state
                   12221:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   12222: }
1.597     wenzelju 12223: ENDUPFORM
                   12224:     $result.= <<ENDUPFORM;
1.400     www      12225: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   12226: <input type="hidden" name="symb" value="$symb" />
                   12227: <input type="hidden" name="command" value="processclickerfile" />
                   12228: <input type="file" name="upfile" size="50" />
                   12229: <br /><label>$type: $selectform</label>
1.632     www      12230: ENDUPFORM
                   12231:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   12232:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   12233:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   12234: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   12235: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      12236: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   12237: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      12238: <br />&nbsp;&nbsp;&nbsp;
                   12239: <input type="text" name="givenanswer" size="50" />
1.413     www      12240: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      12241: ENDGRADINGFORM
1.766     raeburn  12242:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      12243:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   12244:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   12245: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   12246: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  12247: </form>
1.632     www      12248: ENDPERCFORM
                   12249:     $result.='</td>'.
                   12250:              &Apache::loncommon::end_data_table_row().
                   12251:              &Apache::loncommon::end_data_table();
1.400     www      12252:     return $result;
                   12253: }
                   12254: 
                   12255: sub process_clicker_file {
1.766     raeburn  12256:     my ($r,$symb) = @_;
1.400     www      12257:     if (!$symb) {return '';}
1.413     www      12258: 
                   12259:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12260:     &Apache::loncommon::store_course_settings('grades_clicker',
                   12261:                                               \%Saveable_Parameters);
1.598     www      12262:     my $result='';
1.404     www      12263:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 12264: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      12265: 	return $result;
1.404     www      12266:     }
1.522     www      12267:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      12268:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      12269:         return $result;
1.521     www      12270:     }
1.522     www      12271:     my $foundgiven=0;
1.521     www      12272:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12273:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   12274:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      12275:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      12276:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      12277:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   12278:         $foundgiven=$#answers+1;
1.521     www      12279:     }
1.407     albertel 12280:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 12281:     my %correct_ids;
1.404     www      12282:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 12283: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      12284:     }
                   12285:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      12286: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   12287: 	   $correct_id=~tr/a-z/A-Z/;
                   12288: 	   $correct_id=~s/\s//gs;
                   12289: 	   $correct_id=~s/^[\#0]+//;
1.421     www      12290:            $correct_id=~s/[\-\:]//g;
1.414     www      12291:            if ($correct_id) {
                   12292: 	      $correct_ids{$correct_id}='specified';
                   12293:            }
                   12294:         }
1.400     www      12295:     }
1.404     www      12296:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 12297: 	$result.=&mt('Score based on attendance only');
1.521     www      12298:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      12299:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      12300:     } else {
1.408     albertel 12301: 	my $number=0;
1.411     www      12302: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 12303: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      12304: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 12305: 	    if ($correct_ids{$id} eq 'specified') {
                   12306: 		$result.=&mt('specified');
                   12307: 	    } else {
                   12308: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   12309: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   12310: 	    }
                   12311: 	    $number++;
                   12312: 	}
1.411     www      12313:         $result.="</p>\n";
1.710     bisitz   12314:         if ($number==0) {
                   12315:             $result .=
                   12316:                  &Apache::lonhtmlcommon::confirm_success(
                   12317:                      &mt('No IDs found to determine correct answer'),1);
                   12318:             return $result;
                   12319:         }
1.404     www      12320:     }
1.405     www      12321:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   12322:         $result .=
                   12323:             &Apache::lonhtmlcommon::confirm_success(
                   12324:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   12325:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      12326:         return $result;
1.405     www      12327:     }
1.760     raeburn  12328:     my $mimetype;
                   12329:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   12330:         my $mm = new File::MMagic;
                   12331:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   12332:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   12333:             $result.= '<p>'.
                   12334:                 &Apache::lonhtmlcommon::confirm_success(
                   12335:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   12336:             return $result;
                   12337:         }
                   12338:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   12339:         $result .= '<p>'.
                   12340:             &Apache::lonhtmlcommon::confirm_success(
                   12341:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   12342:         return $result;
                   12343:     }
1.410     www      12344: 
                   12345: # Were able to get all the info needed, now analyze the file
                   12346: 
1.411     www      12347:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 12348:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      12349:     $result.=&Apache::loncommon::start_data_table().
                   12350:              &Apache::loncommon::start_data_table_header_row().
                   12351:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   12352:              &Apache::loncommon::end_data_table_header_row().
                   12353:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   12354: <td>
1.410     www      12355: <form method="post" action="/adm/grades" name="clickeranalysis">
                   12356: <input type="hidden" name="symb" value="$symb" />
                   12357: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      12358: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   12359: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   12360: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      12361: ENDHEADER
1.522     www      12362:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12363:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   12364:     } 
1.408     albertel 12365:     my %responses;
                   12366:     my @questiontitles;
1.405     www      12367:     my $errormsg='';
                   12368:     my $number=0;
                   12369:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  12370:         if ($mimetype eq 'text/plain') {
                   12371:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   12372:         } elsif ($mimetype eq 'text/html') {
                   12373:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   12374:         }
                   12375:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      12376:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  12377:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      12378:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   12379:     }
1.411     www      12380:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   12381:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   12382:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   12383:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   12384:              '<br />';
1.522     www      12385:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   12386:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      12387:        return $result;
1.522     www      12388:     } 
1.414     www      12389: # Remember Question Titles
                   12390: # FIXME: Possibly need delimiter other than ":"
                   12391:     for (my $i=0;$i<$number;$i++) {
                   12392:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   12393:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   12394:     }
1.411     www      12395:     my $correct_count=0;
                   12396:     my $student_count=0;
                   12397:     my $unknown_count=0;
1.414     www      12398: # Match answers with usernames
                   12399: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 12400:     foreach my $id (keys(%responses)) {
1.410     www      12401:        if ($correct_ids{$id}) {
1.414     www      12402:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      12403:           $correct_count++;
1.410     www      12404:        } elsif ($clicker_ids{$id}) {
1.437     www      12405:           if ($clicker_ids{$id}=~/\,/) {
                   12406: # More than one user with the same clicker!
1.632     www      12407:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12408:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12409:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      12410:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12411:                            "<select name='multi".$id."'>";
                   12412:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   12413:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   12414:              }
                   12415:              $result.='</select>';
                   12416:              $unknown_count++;
                   12417:           } else {
                   12418: # Good: found one and only one user with the right clicker
                   12419:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   12420:              $student_count++;
                   12421:           }
1.410     www      12422:        } else {
1.632     www      12423:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12424:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12425:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      12426:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12427:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   12428:                    "\n".&mt("Domain").": ".
                   12429:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  12430:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      12431:           $unknown_count++;
1.410     www      12432:        }
1.405     www      12433:     }
1.412     www      12434:     $result.='<hr />'.
                   12435:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      12436:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      12437:        if ($correct_count==0) {
1.696     bisitz   12438:           $errormsg.="Found no correct answers for grading!";
1.412     www      12439:        } elsif ($correct_count>1) {
1.414     www      12440:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      12441:        }
                   12442:     }
1.428     www      12443:     if ($number<1) {
                   12444:        $errormsg.="Found no questions.";
                   12445:     }
1.412     www      12446:     if ($errormsg) {
                   12447:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   12448:     } else {
                   12449:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   12450:     }
1.632     www      12451:     $result.='</form></td>'.
                   12452:              &Apache::loncommon::end_data_table_row().
                   12453:              &Apache::loncommon::end_data_table();
1.614     www      12454:     return $result;
1.400     www      12455: }
                   12456: 
1.405     www      12457: sub iclicker_eval {
1.406     www      12458:     my ($questiontitles,$responses)=@_;
1.405     www      12459:     my $number=0;
                   12460:     my $errormsg='';
                   12461:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      12462:         my %components=&Apache::loncommon::record_sep($line);
                   12463:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 12464: 	if ($entries[0] eq 'Question') {
                   12465: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   12466: 		$$questiontitles[$number]=$entries[$i];
                   12467: 		$number++;
                   12468: 	    }
                   12469: 	}
                   12470: 	if ($entries[0]=~/^\#/) {
                   12471: 	    my $id=$entries[0];
                   12472: 	    my @idresponses;
                   12473: 	    $id=~s/^[\#0]+//;
                   12474: 	    for (my $i=0;$i<$number;$i++) {
                   12475: 		my $idx=3+$i*6;
1.644     www      12476:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 12477: 		push(@idresponses,$entries[$idx]);
                   12478: 	    }
                   12479: 	    $$responses{$id}=join(',',@idresponses);
                   12480: 	}
1.405     www      12481:     }
                   12482:     return ($errormsg,$number);
                   12483: }
                   12484: 
1.760     raeburn  12485: sub iclickerxml_eval {
                   12486:     my ($questiontitles,$responses)=@_;
                   12487:     my $number=0;
                   12488:     my $errormsg='';
                   12489:     my @state;
                   12490:     my %respbyid;
                   12491:     my $p = HTML::Parser->new
                   12492:     (
                   12493:         xml_mode => 1,
                   12494:         start_h =>
                   12495:             [sub {
                   12496:                  my ($tagname,$attr) = @_;
                   12497:                  push(@state,$tagname);
                   12498:                  if ("@state" eq "ssn p") {
                   12499:                      my $title = $attr->{qn};
                   12500:                      $title =~ s/(^\s+|\s+$)//g;
                   12501:                      $questiontitles->[$number]=$title;
                   12502:                  } elsif ("@state" eq "ssn p v") {
                   12503:                      my $id = $attr->{id};
                   12504:                      my $entry = $attr->{ans};
                   12505:                      $id=~s/^[\#0]+//;
                   12506:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   12507:                      $respbyid{$id}[$number] = $entry;
                   12508:                  }
                   12509:             }, "tagname, attr"],
                   12510:          end_h =>
                   12511:                [sub {
                   12512:                    my ($tagname) = @_;
                   12513:                    if ("@state" eq "ssn p") {
                   12514:                        $number++;
                   12515:                    }
                   12516:                    pop(@state);
                   12517:                 }, "tagname"],
                   12518:     );
                   12519: 
                   12520:     $p->parse($env{'form.upfile'});
                   12521:     $p->eof;
                   12522:     foreach my $id (keys(%respbyid)) {
                   12523:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   12524:     }
                   12525:     return ($errormsg,$number);
                   12526: }
                   12527: 
1.419     www      12528: sub interwrite_eval {
                   12529:     my ($questiontitles,$responses)=@_;
                   12530:     my $number=0;
                   12531:     my $errormsg='';
1.420     www      12532:     my $skipline=1;
                   12533:     my $questionnumber=0;
                   12534:     my %idresponses=();
1.419     www      12535:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12536:         my %components=&Apache::loncommon::record_sep($line);
                   12537:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      12538:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   12539:         if ($entries[1] eq 'Response') { $skipline=1; }
                   12540:         next if $skipline;
                   12541:         if ($entries[0]!=$questionnumber) {
                   12542:            $questionnumber=$entries[0];
                   12543:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   12544:            $number++;
1.419     www      12545:         }
1.420     www      12546:         my $id=$entries[4];
                   12547:         $id=~s/^[\#0]+//;
1.421     www      12548:         $id=~s/^v\d*\://i;
                   12549:         $id=~s/[\-\:]//g;
1.420     www      12550:         $idresponses{$id}[$number]=$entries[6];
                   12551:     }
1.524     raeburn  12552:     foreach my $id (keys(%idresponses)) {
1.420     www      12553:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   12554:        $$responses{$id}=~s/^\s*\,//;
1.419     www      12555:     }
                   12556:     return ($errormsg,$number);
                   12557: }
                   12558: 
1.666     www      12559: sub turning_eval {
                   12560:     my ($questiontitles,$responses)=@_;
                   12561:     my $number=0;
                   12562:     my $errormsg='';
                   12563:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12564:         my %components=&Apache::loncommon::record_sep($line);
                   12565:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   12566:         if ($#entries>$number) { $number=$#entries; }
                   12567:         my $id=$entries[0];
                   12568:         my @idresponses;
                   12569:         $id=~s/^[\#0]+//;
                   12570:         unless ($id) { next; }
                   12571:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   12572:             $entries[$idx]=~s/\,/\;/g;
                   12573:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   12574:             push(@idresponses,$entries[$idx]);
                   12575:         }
                   12576:         $$responses{$id}=join(',',@idresponses);
                   12577:     }
                   12578:     for (my $i=1; $i<=$number; $i++) {
                   12579:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   12580:     }
                   12581:     return ($errormsg,$number);
                   12582: }
                   12583: 
                   12584: 
1.414     www      12585: sub assign_clicker_grades {
1.766     raeburn  12586:     my ($r,$symb) = @_;
1.414     www      12587:     if (!$symb) {return '';}
1.416     www      12588: # See which part we are saving to
1.582     raeburn  12589:     my $res_error;
                   12590:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   12591:     if ($res_error) {
                   12592:         return &navmap_errormsg();
                   12593:     }
1.804   ! raeburn  12594:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          12595:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        !          12596:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
        !          12597:     my (%skip_passback,%pbsave); 
1.416     www      12598: # FIXME: This should probably look for the first handgradeable part
                   12599:     my $part=$$partlist[0];
                   12600: # Start screen output
1.766     raeburn  12601:     my $result = &Apache::loncommon::start_data_table().
                   12602:                  &Apache::loncommon::start_data_table_header_row().
                   12603:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   12604:                  &Apache::loncommon::end_data_table_header_row().
                   12605:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      12606: # Get correct result
                   12607: # FIXME: Possibly need delimiter other than ":"
                   12608:     my @correct=();
1.415     www      12609:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   12610:     my $number=$env{'form.number'};
                   12611:     if ($gradingmechanism ne 'attendance') {
1.414     www      12612:        foreach my $key (keys(%env)) {
                   12613:           if ($key=~/^form\.correct\:/) {
                   12614:              my @input=split(/\,/,$env{$key});
                   12615:              for (my $i=0;$i<=$#input;$i++) {
                   12616:                  if (($correct[$i]) && ($input[$i]) &&
                   12617:                      ($correct[$i] ne $input[$i])) {
                   12618:                     $result.='<br /><span class="LC_warning">'.
                   12619:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   12620:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      12621:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      12622:                     $correct[$i]=$input[$i];
                   12623:                  }
                   12624:              }
                   12625:           }
                   12626:        }
1.415     www      12627:        for (my $i=0;$i<$number;$i++) {
1.644     www      12628:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      12629:              $result.='<br /><span class="LC_error">'.
                   12630:                       &mt('No correct result given for question "[_1]"!',
                   12631:                           $env{'form.question:'.$i}).'</span>';
                   12632:           }
                   12633:        }
1.644     www      12634:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      12635:     }
                   12636: # Start grading
1.415     www      12637:     my $pcorrect=$env{'form.pcorrect'};
                   12638:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      12639:     my $storecount=0;
1.632     www      12640:     my %users=();
1.415     www      12641:     foreach my $key (keys(%env)) {
1.420     www      12642:        my $user='';
1.415     www      12643:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      12644:           $user=$1;
                   12645:        }
                   12646:        if ($key=~/^form\.unknown\:(.*)$/) {
                   12647:           my $id=$1;
                   12648:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   12649:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      12650:           } elsif ($env{'form.multi'.$id}) {
                   12651:              $user=$env{'form.multi'.$id};
1.420     www      12652:           }
                   12653:        }
1.632     www      12654:        if ($user) {
                   12655:           if ($users{$user}) {
                   12656:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   12657:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      12658:                       '</span><br />';
                   12659:           }
                   12660:           $users{$user}=1; 
1.415     www      12661:           my @answer=split(/\,/,$env{$key});
                   12662:           my $sum=0;
1.522     www      12663:           my $realnumber=$number;
1.415     www      12664:           for (my $i=0;$i<$number;$i++) {
1.576     www      12665:              if  ($correct[$i] eq '-') {
                   12666:                 $realnumber--;
1.766     raeburn  12667:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      12668:                 if ($gradingmechanism eq 'attendance') {
                   12669:                    $sum+=$pcorrect;
1.576     www      12670:                 } elsif ($correct[$i] eq '*') {
1.522     www      12671:                    $sum+=$pcorrect;
1.415     www      12672:                 } else {
1.644     www      12673: # We actually grade if correct or not
                   12674:                    my $increment=$pincorrect;
                   12675: # Special case: numerical answer "0"
                   12676:                    if ($correct[$i] eq '0') {
                   12677:                       if ($answer[$i]=~/^[0\.]+$/) {
                   12678:                          $increment=$pcorrect;
                   12679:                       }
                   12680: # General numerical answer, both evaluate to something non-zero
                   12681:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   12682:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   12683:                          $increment=$pcorrect;
                   12684:                       }
                   12685: # Must be just alphanumeric
                   12686:                    } elsif ($answer[$i] eq $correct[$i]) {
                   12687:                       $increment=$pcorrect;
1.415     www      12688:                    }
1.644     www      12689:                    $sum+=$increment;
1.415     www      12690:                 }
                   12691:              }
                   12692:           }
1.522     www      12693:           my $ave=$sum/(100*$realnumber);
1.416     www      12694: # Store
                   12695:           my ($username,$domain)=split(/\:/,$user);
                   12696:           my %grades=();
                   12697:           $grades{"resource.$part.solved"}='correct_by_override';
                   12698:           $grades{"resource.$part.awarded"}=$ave;
                   12699:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   12700:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   12701:                                                  $env{'request.course.id'},
                   12702:                                                  $domain,$username);
                   12703:           if ($returncode ne 'ok') {
                   12704:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   12705:           } else {
                   12706:              $storecount++;
1.804   ! raeburn  12707:              if (keys(%needpb)) {
        !          12708:                  my (%weights,%awardeds,%excuseds);
        !          12709:                  my $usec = &Apache::lonnet::getsection($domain,$username,$env{'request.course.id'});
        !          12710:                  $weights{$symb}{$part} = &Apache::lonnet::EXT("resource.$part.weight",$symb,$domain,$username,$usec);
        !          12711:                  $awardeds{$symb}{$part} = $ave;
        !          12712:                  $excuseds{$symb}{$part} = '';
        !          12713:                  &process_passbacks('clickergrade',[$symb],$cdom,$cnum,$domain,$username,$usec,\%weights,
        !          12714:                                     \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
        !          12715:              }
1.416     www      12716:           }
1.415     www      12717:        }
                   12718:     }
                   12719: # We are done
1.549     hauer    12720:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      12721:              '</td>'.
                   12722:              &Apache::loncommon::end_data_table_row().
                   12723:              &Apache::loncommon::end_data_table();
1.614     www      12724:     return $result;
1.414     www      12725: }
                   12726: 
1.582     raeburn  12727: sub navmap_errormsg {
                   12728:     return '<div class="LC_error">'.
                   12729:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  12730:            &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  12731:            '</div>';
                   12732: }
1.607     droeschl 12733: 
1.609     www      12734: sub startpage {
1.777     raeburn  12735:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  12736:     my %args;
                   12737:     if ($onload) {
                   12738:          my %loaditems = (
                   12739:                         'onload' => $onload,
                   12740:                       );
                   12741:          $args{'add_entries'} = \%loaditems;
                   12742:     }
1.671     raeburn  12743:     if ($nomenu) {
1.754     raeburn  12744:         $args{'only_body'} = 1; 
1.777     raeburn  12745:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  12746:     } else {
1.785     raeburn  12747:         if ($env{'request.course.id'}) { 
                   12748:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   12749:         }
1.754     raeburn  12750:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  12751:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  12752:         if ($env{'request.course.id'}) {
                   12753:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   12754:         }
1.671     raeburn  12755:     }
1.613     www      12756:     unless ($nodisplayflag) {
1.773     raeburn  12757:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      12758:     }
1.607     droeschl 12759: }
1.582     raeburn  12760: 
1.622     www      12761: sub select_problem {
                   12762:     my ($r)=@_;
1.632     www      12763:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  12764:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      12765:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   12766:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   12767: }
                   12768: 
1.793     raeburn  12769: #----- display problem, answer, and submissions for a single student (no grading)
                   12770: 
                   12771: sub view_as_user {
                   12772:     my ($symb,$vuname,$vudom,$hasperm) = @_;
                   12773:     my $plainname = &Apache::loncommon::plainname($vuname,$vudom,'lastname');
                   12774:     my $displayname = &nameUserString('',$plainname,$vuname,$vudom);
                   12775:     my $output = &Apache::loncommon::get_student_view($symb,$vuname,$vudom,
                   12776:                                                       $env{'request.course.id'},
                   12777:                                                       undef,{'disable_submit' => 1}).
                   12778:                  "\n\n".
                   12779:                  '<div class="LC_grade_show_user">'.
                   12780:                  '<h2>'.$displayname.'</h2>'.
                   12781:                  "\n".
                   12782:                  &Apache::loncommon::track_student_link('View recent activity',
                   12783:                                                         $vuname,$vudom,'check').' '.
                   12784:                  "\n";
                   12785:     if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) ||
                   12786:         (($env{'request.course.sec'} ne '') &&
                   12787:          &Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
                   12788:         $output .= &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   12789:                                                $vuname,$vudom,$symb,'check');
                   12790:     }
                   12791:     $output .= "\n";
                   12792:     my $companswer = &Apache::loncommon::get_student_answers($symb,$vuname,$vudom,
                   12793:                                                              $env{'request.course.id'});
                   12794:     $companswer=~s|<form(.*?)>||g;
                   12795:     $companswer=~s|</form>||g;
                   12796:     $companswer=~s|name="submit"|name="would_have_been_submit"|g;
                   12797:     $output .= '<div class="LC_Box">'.
                   12798:                '<h3 class="LC_hcell">'.&mt('Correct answer for[_1]',$displayname).'</h3>'.
                   12799:                $companswer.
                   12800:                '</div>'."\n";
                   12801:     my $is_tool = ($symb =~ /ext\.tool$/);
                   12802:     my ($essayurl,%coursedesc_by_cid);
                   12803:     (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   12804:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$vudom,$vuname);
                   12805:     my $res_error;
                   12806:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   12807:         &response_type($symb,\$res_error);
                   12808:     my $fullname;
                   12809:     my $collabinfo;
                   12810:     if ($numessay) {
                   12811:         unless ($hasperm) {
                   12812:             &init_perm();
                   12813:         }
                   12814:         ($collabinfo,$fullname)=
                   12815:             &check_collaborators($symb,$vuname,$vudom,\%record,$handgrade,0);
                   12816:         unless ($hasperm) {
                   12817:             &reset_perm();
                   12818:         }
                   12819:     }
                   12820:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   12821:                     '" src="'.$Apache::lonnet::perlvar{'lonIconsURL'}.
                   12822:                     '/check.gif" height="16" border="0" />';
                   12823:     my ($lastsubonly,$partinfo) =
                   12824:         &show_last_submission($vuname,$vudom,$symb,$essayurl,$responseType,'datesub',
                   12825:                               '',$fullname,\%record,\%coursedesc_by_cid);
                   12826:     $output .= '<div class="LC_Box">'.
                   12827:                '<h3 class="LC_hcell">'.&mt('Submissions').'</h3>'."\n".$collabinfo."\n";
                   12828:     if (($numresp > $numessay) & !$is_tool) {
                   12829:         $output .='<p class="LC_info">'.
                   12830:                   &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon).
                   12831:                   "</p>\n";
                   12832:     }
                   12833:     $output .= $partinfo;
                   12834:     $output .= $lastsubonly;
                   12835:     $output .= &displaySubByDates($symb,\%record,$partlist,$responseType,$checkIcon,$vuname,$vudom);
                   12836:     $output .= '</div></div>'."\n";
                   12837:     return $output;
                   12838: }
                   12839: 
1.1       albertel 12840: sub handler {
1.41      ng       12841:     my $request=$_[0];
1.434     albertel 12842:     &reset_caches();
1.646     raeburn  12843:     if ($request->header_only) {
                   12844:         &Apache::loncommon::content_type($request,'text/html');
                   12845:         $request->send_http_header;
                   12846:         return OK;
                   12847:     }
                   12848:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   12849: 
1.664     raeburn  12850: # see what command we need to execute
                   12851: 
                   12852:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   12853:     my $command=$commands[0];
                   12854: 
1.646     raeburn  12855:     &init_perm();
                   12856:     if (!$env{'request.course.id'}) {
1.664     raeburn  12857:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   12858:                 ($command =~ /^scantronupload/)) {
                   12859:             # Not in a course.
                   12860:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   12861:             return HTTP_NOT_ACCEPTABLE;
                   12862:         }
1.646     raeburn  12863:     } elsif (!%perm) {
                   12864:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  12865:         return OK;
1.41      ng       12866:     }
1.646     raeburn  12867:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       12868:     $request->send_http_header;
1.646     raeburn  12869: 
1.160     albertel 12870:     if ($#commands > 0) {
                   12871: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   12872:     }
1.608     www      12873: 
1.801     raeburn  12874: # -------------------------------------- Flag and buffer for registered cleanup
                   12875:     $registered_cleanup=0;
                   12876:     undef(@Apache::grades::ltipassback);
                   12877: 
1.608     www      12878: # see what the symb is
                   12879: 
                   12880:     my $symb=$env{'form.symb'};
                   12881:     unless ($symb) {
                   12882:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   12883:        $symb=&Apache::lonnet::symbread($url);
                   12884:     }
1.646     raeburn  12885:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      12886: 
1.513     foxr     12887:     $ssi_error = 0;
1.637     www      12888:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      12889: #
1.637     www      12890: # Not called from a resource, but inside a course
1.601     www      12891: #    
1.622     www      12892:         &startpage($request,undef,[],1,1);
                   12893:         &select_problem($request);
1.41      ng       12894:     } else {
1.104     albertel 12895: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  12896:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  12897:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   12898:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12899:                     &choose_task_version_form($symb,$env{'form.student'},
                   12900:                                               $env{'form.userdom'});
                   12901:             }
1.773     raeburn  12902:             my $divforres;
                   12903:             if ($env{'form.student'} eq '') {
                   12904:                 $js .= &part_selector_js();
                   12905:                 $onload = "toggleParts('gradesub');";
                   12906:             } else {
                   12907:                 $divforres = 1;
                   12908:             }
1.778     raeburn  12909:             my $head_extra = $js;
                   12910:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12911:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12912:                 if ($csslinks) {
                   12913:                     $head_extra .= "\n$csslinks";
                   12914:                 }
                   12915:             }
1.777     raeburn  12916:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   12917:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  12918:             if ($versionform) {
1.775     raeburn  12919:                 if ($divforres) {
                   12920:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   12921:                 }
1.671     raeburn  12922:                 $request->print($versionform);
                   12923:             }
1.773     raeburn  12924: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  12925:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   12926:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12927:                 &choose_task_version_form($symb,$env{'form.student'},
                   12928:                                           $env{'form.userdom'},
                   12929:                                           $env{'form.inhibitmenu'});
1.778     raeburn  12930:             my $head_extra = $js;
                   12931:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12932:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12933:                 if ($csslinks) {
                   12934:                     $head_extra .= "\n$csslinks";
                   12935:                 }
                   12936:             }
1.777     raeburn  12937:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   12938:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  12939:             if ($versionform) {
                   12940:                 $request->print($versionform);
                   12941:             }
                   12942:             $request->print('<br clear="all" />');
                   12943:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 12944: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      12945:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12946:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      12947: 	    &pickStudentPage($request,$symb);
1.103     albertel 12948: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  12949:             my $csslinks;
                   12950:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12951:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  12952:             }
1.615     www      12953:             &startpage($request,$symb,
                   12954:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12955:                                        {href=>'',text=>'Select student'},
1.777     raeburn  12956:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      12957: 	    &displayPage($request,$symb);
1.104     albertel 12958: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      12959:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12960:                                        {href=>'',text=>'Select student'},
                   12961:                                        {href=>'',text=>'Grade student'},
                   12962:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      12963: 	    &updateGradeByPage($request,$symb);
1.104     albertel 12964: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  12965:             my $csslinks;
                   12966:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12967:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12968:             }
1.619     www      12969:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  12970:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      12971: 	    &processGroup($request,$symb);
1.104     albertel 12972: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      12973:             &startpage($request,$symb);
                   12974: 	    $request->print(&grading_menu($request,$symb));
1.598     www      12975: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      12976:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      12977: 	    $request->print(&submit_options($request,$symb));
1.598     www      12978:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  12979:             my $js = &part_selector_js();
                   12980:             my $onload = "toggleParts('gradesub');";
                   12981:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   12982:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      12983:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      12984:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      12985:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      12986:             $request->print(&submit_options_table($request,$symb));
1.598     www      12987:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      12988:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      12989:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 12990: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      12991:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      12992: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 12993: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      12994:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   12995:                                        {href=>'',text=>'Store grades'}]);
1.608     www      12996: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 12997: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      12998:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   12999:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   13000:                                                                              text=>"Modify grades"},
                   13001:                                        {href=>'', text=>"Store grades"}]);
1.608     www      13002: 	    $request->print(&editgrades($request,$symb));
1.602     www      13003:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      13004:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      13005:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 13006: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      13007:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   13008:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      13009: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      13010:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      13011:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      13012:             $request->print(&process_clicker($request,$symb));
1.400     www      13013:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      13014:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   13015:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      13016:             $request->print(&process_clicker_file($request,$symb));
1.414     www      13017:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      13018:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   13019:                                        {href=>'', text=>'Process clicker file'},
                   13020:                                        {href=>'', text=>'Store grades'}]);
1.608     www      13021:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 13022: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      13023:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13024: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 13025: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      13026:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13027: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 13028: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      13029:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13030: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 13031: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 13032: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      13033:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13034: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       13035: 	    } else {
1.257     albertel 13036: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   13037: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       13038: 		} else {
1.257     albertel 13039: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       13040: 		}
1.627     www      13041:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13042: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       13043: 	    }
1.246     albertel 13044: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      13045:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      13046: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 13047: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  13048:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   13049:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      13050: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 13051:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      13052:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13053:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 13054: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      13055:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13056: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 13057: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      13058:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13059: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 13060:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  13061:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  13062:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   13063:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      13064:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 13065:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  13066:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      13067:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13068:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  13069:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      13070:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13071:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  13072:         } elsif ($command eq 'scantronupload_delete' &&
                   13073:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   13074:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   13075:             &scantron_upload_delete($request,$symb);
1.523     raeburn  13076:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      13077:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      13078:             $request->print(&checkscantron_results($request,$symb));
                   13079:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  13080:             my $js = &part_selector_js();
                   13081:             my $onload = "toggleParts('gradingMenu');";
                   13082:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   13083:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      13084:             $request->print(&submit_options_download($request,$symb));
                   13085:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   13086:             &startpage($request,$symb,
                   13087:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  13088:     {href=>'', text=>'Download submitted files'}],
                   13089:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  13090:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      13091:             &submit_download_link($request,$symb);
1.796     raeburn  13092:         } elsif ($command eq 'initialpassback') {
                   13093:             &startpage($request,$symb,[{href=>'', text=>'Choose Launcher'}],undef,1);
                   13094:             $request->print(&initialpassback($request,$symb));
                   13095:         } elsif ($command eq 'passback') {
                   13096:             &startpage($request,$symb,
                   13097:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13098:                         {href=>'', text=>'Types of User'}],undef,1);
                   13099:             $request->print(&passback_filters($request,$symb));
                   13100:         } elsif ($command eq 'passbacknames') {
                   13101:             my $chosen;
                   13102:             if ($env{'form.passback'} ne '') {
                   13103:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13104:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13105:                 }
                   13106:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13107:             }
                   13108:             &startpage($request,$symb,
                   13109:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13110:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13111:                         {href=>'', text=>'Select Users'}],undef,1);
                   13112:             $request->print(&names_for_passback($request,$symb));
                   13113:         } elsif ($command eq 'passbackscores') {
                   13114:             my ($chosen,$stu_status);
                   13115:             if ($env{'form.passback'} ne '') {
                   13116:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13117:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13118:                 }
                   13119:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13120:             }
                   13121:             if ($env{'form.Status'}) {
                   13122:                 $stu_status = &HTML::Entities::encode($env{'form.Status'});
                   13123:             }
                   13124:             &startpage($request,$symb,
                   13125:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13126:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13127:                         {href=>&href_symb_cmd($symb,'passbacknames').'&amp;Status='.$stu_status.'&amp;passback='.$chosen, text=>'Select Users'},
                   13128:                         {href=>'', text=>'Execute Passback'}],undef,1);
                   13129:             $request->print(&do_passback($request,$symb));
1.106     albertel 13130: 	} elsif ($command) {
1.620     www      13131:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   13132: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 13133: 	}
1.2       albertel 13134:     }
1.513     foxr     13135:     if ($ssi_error) {
                   13136: 	&ssi_print_error($request);
                   13137:     }
1.671     raeburn  13138:     if ($env{'form.inhibitmenu'}) {
                   13139:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  13140:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  13141:         &Apache::lonquickgrades::endGradeScreen($request);
                   13142:     }
1.434     albertel 13143:     &reset_caches();
1.646     raeburn  13144:     return OK;
1.44      ng       13145: }
                   13146: 
1.1       albertel 13147: 1;
                   13148: 
1.13      albertel 13149: __END__;
1.531     jms      13150: 
                   13151: 
                   13152: =head1 NAME
                   13153: 
                   13154: Apache::grades
                   13155: 
                   13156: =head1 SYNOPSIS
                   13157: 
                   13158: Handles the viewing of grades.
                   13159: 
                   13160: This is part of the LearningOnline Network with CAPA project
                   13161: described at http://www.lon-capa.org.
                   13162: 
                   13163: =head1 OVERVIEW
                   13164: 
                   13165: Do an ssi with retries:
1.715     bisitz   13166: While I'd love to factor out this with the version in lonprintout,
1.531     jms      13167: 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
                   13168: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   13169: 
                   13170: At least the logic that drives this has been pulled out into loncommon.
                   13171: 
                   13172: 
                   13173: 
                   13174: ssi_with_retries - Does the server side include of a resource.
                   13175:                      if the ssi call returns an error we'll retry it up to
                   13176:                      the number of times requested by the caller.
1.715     bisitz   13177:                      If we still have a problem, no text is appended to the
1.531     jms      13178:                      output and we set some global variables.
                   13179:                      to indicate to the caller an SSI error occurred.  
                   13180:                      All of this is supposed to deal with the issues described
1.715     bisitz   13181:                      in LON-CAPA BZ 5631 see:
1.531     jms      13182:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   13183:                      by informing the user that this happened.
                   13184: 
                   13185: Parameters:
                   13186:   resource   - The resource to include.  This is passed directly, without
                   13187:                interpretation to lonnet::ssi.
                   13188:   form       - The form hash parameters that guide the interpretation of the resource
                   13189:                
                   13190:   retries    - Number of retries allowed before giving up completely.
                   13191: Returns:
                   13192:   On success, returns the rendered resource identified by the resource parameter.
                   13193: Side Effects:
                   13194:   The following global variables can be set:
                   13195:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   13196:                               It is up to the caller to initialize this to false
                   13197:                               if desired.
                   13198:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   13199:                               of the resource that could not be rendered by the ssi
                   13200:                               call.
                   13201:    ssi_error_message   - The error string fetched from the ssi response
                   13202:                               in the event of an error.
                   13203: 
                   13204: 
                   13205: =head1 HANDLER SUBROUTINE
                   13206: 
                   13207: ssi_with_retries()
                   13208: 
                   13209: =head1 SUBROUTINES
                   13210: 
                   13211: =over
                   13212: 
1.671     raeburn  13213: =head1 Routines to display previous version of a Task for a specific student
                   13214: 
                   13215: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   13216: can receive another opportunity. Access to tasks is slot-based. If a slot
                   13217: requires a proctor to check-in the student, a new version of the Task will
                   13218: be created when the student is checked in to the new opportunity.
                   13219: 
                   13220: If a particular student has tried two or more versions of a particular task,
                   13221: the submission screen provides a user with vgr privileges (e.g., a Course
                   13222: Coordinator) the ability to display a previous version worked on by the
                   13223: student.  By default, the current version is displayed. If a previous version
                   13224: has been selected for display, submission data are only shown that pertain
                   13225: to that particular version, and the interface to submit grades is not shown.
                   13226: 
                   13227: =over 4
                   13228: 
                   13229: =item show_previous_task_version()
                   13230: 
                   13231: Displays a specified version of a student's Task, as the student sees it.
                   13232: 
                   13233: Inputs: 2
                   13234:         request - request object
                   13235:         symb    - unique symb for current instance of resource
                   13236: 
                   13237: Output: None.
                   13238: 
                   13239: Side Effects: calls &show_problem() to print version of Task, with
                   13240:               version contained in form item: $env{'form.previousversion'}
                   13241: 
                   13242: =item choose_task_version_form()
                   13243: 
                   13244: Displays a web form used to select which version of a student's view of a
                   13245: Task should be displayed.  Either launches a pop-up window, or replaces
                   13246: content in existing pop-up, or replaces page in main window.
                   13247: 
                   13248: Inputs: 4
                   13249:         symb    - unique symb for current instance of resource
                   13250:         uname   - username of student
                   13251:         udom    - domain of student
                   13252:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13253:                   breadcrumbs etc., are displayed
                   13254: 
                   13255: Output: 4
                   13256:         current   - student's current version
                   13257:         displayed - student's version being displayed
                   13258:         result    - scalar containing HTML for web form used to switch to
                   13259:                     a different version (or a link to close window, if pop-up).
                   13260:         js        - javascript for processing selection in versions web form
                   13261: 
                   13262: Side Effects: None.
                   13263: 
                   13264: =item previous_display_javascript()
                   13265: 
                   13266: Inputs: 2
                   13267:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13268:                   breadcrumbs etc., are displayed.
                   13269:         current - student's current version number.
                   13270: 
                   13271: Output: 1
                   13272:         js      - javascript for processing selection in versions web form.
                   13273: 
                   13274: Side Effects: None.
                   13275: 
                   13276: =back
                   13277: 
                   13278: =head1 Routines to process bubblesheet data.
                   13279: 
                   13280: =over 4
                   13281: 
1.531     jms      13282: =item scantron_get_correction() : 
                   13283: 
                   13284:    Builds the interface screen to interact with the operator to fix a
                   13285:    specific error condition in a specific scanline
                   13286: 
                   13287:  Arguments:
                   13288:     $r           - Apache request object
                   13289:     $i           - number of the current scanline
                   13290:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  13291:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      13292:     $line        - full contents of the current scanline
                   13293:     $error       - error condition, valid values are
                   13294:                    'incorrectCODE', 'duplicateCODE',
                   13295:                    'doublebubble', 'missingbubble',
                   13296:                    'duplicateID', 'incorrectID'
                   13297:     $arg         - extra information needed
                   13298:        For errors:
                   13299:          - duplicateID   - paper number that this studentID was seen before on
                   13300:          - duplicateCODE - array ref of the paper numbers this CODE was
                   13301:                            seen on before
                   13302:          - incorrectCODE - current incorrect CODE 
                   13303:          - doublebubble  - array ref of the bubble lines that have double
                   13304:                            bubble errors
                   13305:          - missingbubble - array ref of the bubble lines that have missing
                   13306:                            bubble errors
                   13307: 
1.788     raeburn  13308:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   13309:    $randompick  - True if exam folder (or a sub-folder) has randompick set
1.691     raeburn  13310:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   13311:                      for current line to question number used for same question
                   13312:                      in "Master Seqence" (as seen by Course Coordinator).
                   13313:    $startline   - Reference to hash where key is question number (0 is first)
                   13314:                   and value is number of first bubble line for current student
                   13315:                   or code-based randompick and/or randomorder.
                   13316: 
                   13317: 
                   13318: 
1.531     jms      13319: =item  scantron_get_maxbubble() : 
                   13320: 
1.582     raeburn  13321:    Arguments:
                   13322:        $nav_error  - Reference to scalar which is a flag to indicate a
                   13323:                       failure to retrieve a navmap object.
                   13324:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   13325:        calling routine should trap the error condition and display the warning
                   13326:        found in &navmap_errormsg().
                   13327: 
1.649     raeburn  13328:        $scantron_config - Reference to bubblesheet format configuration hash.
                   13329: 
1.531     jms      13330:    Returns the maximum number of bubble lines that are expected to
                   13331:    occur. Does this by walking the selected sequence rendering the
                   13332:    resource and then checking &Apache::lonxml::get_problem_counter()
                   13333:    for what the current value of the problem counter is.
                   13334: 
                   13335:    Caches the results to $env{'form.scantron_maxbubble'},
                   13336:    $env{'form.scantron.bubble_lines.n'}, 
                   13337:    $env{'form.scantron.first_bubble_line.n'} and
                   13338:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  13339:    which are the total number of bubble lines, the number of bubble
1.531     jms      13340:    lines for response n and number of the first bubble line for response n,
                   13341:    and a comma separated list of numbers of bubble lines for sub-questions
                   13342:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   13343: 
                   13344: 
                   13345: =item  scantron_validate_missingbubbles() : 
                   13346: 
                   13347:    Validates all scanlines in the selected file to not have any
                   13348:     answers that don't have bubbles that have not been verified
                   13349:     to be bubble free.
                   13350: 
                   13351: =item  scantron_process_students() : 
                   13352: 
1.659     raeburn  13353:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      13354: 
                   13355:    The parsed scanline hash is added to %env 
                   13356: 
                   13357:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   13358:    foreach resource , with the form data of
                   13359: 
                   13360: 	'submitted'     =>'scantron' 
                   13361: 	'grade_target'  =>'grade',
                   13362: 	'grade_username'=> username of student
                   13363: 	'grade_domain'  => domain of student
                   13364: 	'grade_courseid'=> of course
                   13365: 	'grade_symb'    => symb of resource to grade
                   13366: 
                   13367:     This triggers a grading pass. The problem grading code takes care
                   13368:     of converting the bubbled letter information (now in %env) into a
                   13369:     valid submission.
                   13370: 
                   13371: =item  scantron_upload_scantron_data() :
                   13372: 
1.659     raeburn  13373:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      13374: 
                   13375: =item  scantron_upload_scantron_data_save() : 
                   13376: 
                   13377:    Adds a provided bubble information data file to the course if user
1.770     raeburn  13378:    has the correct privileges to do so.
                   13379: 
                   13380: = item scantron_upload_delete() :
                   13381: 
                   13382:    Deletes a previously uploaded bubble information data file, if user
                   13383:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      13384: 
                   13385: =item  valid_file() :
                   13386: 
                   13387:    Validates that the requested bubble data file exists in the course.
                   13388: 
                   13389: =item  scantron_download_scantron_data() : 
                   13390: 
                   13391:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  13392:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      13393:    course.
                   13394: 
                   13395: =item  scantron_validate_ID() : 
                   13396: 
                   13397:    Validates all scanlines in the selected file to not have any
1.556     weissno  13398:    invalid or underspecified student/employee IDs
1.531     jms      13399: 
1.582     raeburn  13400: =item navmap_errormsg() :
                   13401: 
                   13402:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  13403:    Should be called whenever the request to instantiate a navmap object fails.
                   13404: 
                   13405: =back
1.582     raeburn  13406: 
1.531     jms      13407: =back
                   13408: 
                   13409: =cut

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