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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.798   ! raeburn     4: # $Id: grades.pm,v 1.797 2024/12/09 02:29:37 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.796     raeburn  1461:                                             'linkprot' => $linkprotector,
                   1462:                                             'total'    => $total,
                   1463:                                             'possible' => $possible,
                   1464:                                             'score'    => $score,
                   1465:                                         };
                   1466:                                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1467:                                     }
                   1468:                                 } else {
                   1469:                                     if (($id ne '') && ($url ne '')) {
                   1470:                                         $zeroposs{$student} = 1;
                   1471:                                     } else {
                   1472:                                         $nopbinfo{$student} = 1;
                   1473:                                     }
                   1474:                                 }
                   1475:                             }
                   1476:                             &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
                   1477:                             if ($ctr%2 ==1) {
                   1478:                                 $outcome .= &Apache::loncommon::end_data_table_row();
                   1479:                             }
                   1480:                             $outcome .= &Apache::loncommon::end_data_table();
                   1481:                             if ($ctr) {
                   1482:                                 $request->print('<p><br />'.&mt('Scores sent to launcher CMS').'</p>'.
                   1483:                                                 '<p>'.$outcome.'</p>');
                   1484:                             } else {
                   1485:                                 $request->print('<p>'.&mt('No scores sent to launcher CMS').'</p>');
                   1486:                             }
                   1487:                             if (keys(%tosend)) {
                   1488:                                 $request->print('<p>'.&mt('No scores sent for following'));
                   1489:                                 my ($zeros,$nopbcreds,$noconfirm,$noscore);
                   1490:                                 foreach my $student (sort
                   1491:                                 {
                   1492:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1493:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1494:                                      }
                   1495:                                      return $a cmp $b;
                   1496:                                 } (keys(%$fullname))) {
                   1497:                                     next unless ($tosend{$student});
                   1498:                                     my ($uname,$udom) = split(/:/,$student);
                   1499:                                     my $line = '<li>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).'</li>'."\n";
                   1500:                                     if ($zeroposs{$student}) {
                   1501:                                         $zeros .= $line;
                   1502:                                     } elsif ($nopbinfo{$student}) {
                   1503:                                         $nopbcreds .= $line;
                   1504:                                     } elsif ($remotenotok{$student}) {
                   1505:                                         $noconfirm .= $line;
                   1506:                                     } elsif ($scorenotok{$student}) {
                   1507:                                         $noscore .= $line;
                   1508:                                     }
                   1509:                                 }
                   1510:                                 if ($zeros) {
                   1511:                                     $request->print('<br />'.&mt('Total points possible was 0').':'.
                   1512:                                                     '<ul>'.$zeros.'</ul><br />');
                   1513:                                 }
                   1514:                                 if ($nopbcreds) {
                   1515:                                     $request->print('<br />'.&mt('Missing unique identifier and/or passback location').':'.
                   1516:                                                     '<ul>'.$nopbcreds.'</ul><br />');
                   1517:                                 }
                   1518:                                 if ($noconfirm) {
                   1519:                                     $request->print('<br />'.&mt('Score receipt not confirmed by receiving CMS').':'.
                   1520:                                                     '<ul>'.$noconfirm.'</ul><br />');
                   1521:                                 }
                   1522:                                 if ($noscore) {
                   1523:                                     $request->print('<br />'.&mt('Score computation or transmission failed').':'.
                   1524:                                                     '<ul>'.$noscore.'</ul><br />');
                   1525:                                 }
                   1526:                                 $request->print('</p>');
                   1527:                             }
                   1528:                         } else {
                   1529:                             $error = &mt('Settings for deep-link launch target unavailable, so no scores were sent');
                   1530:                         }
                   1531:                     } else {
                   1532:                         $error = &mt('No available students for whom scores can be sent.');
                   1533:                     }
                   1534:                 } else {
                   1535:                     $error = &mt('Classlist could not be retrieved so no scores were sent.');
                   1536:                 }
                   1537:             } else {
                   1538:                 $error = &mt('No students selected to receive scores so none were sent.');
                   1539:             }
                   1540:         } else {
                   1541:             if ($env{'form.passback'}) {
                   1542:                 $error = &mt('Deep-link launch target was invalid so no scores were sent.');
                   1543:             } else {
                   1544:                 $error = &mt('Deep-link launch target was missing so no scores were sent.');
                   1545:             }
                   1546:         }
                   1547:     } else {
                   1548:         $error = &mt('You do not have permission to manage grades, so no scores were sent');
                   1549:     }
                   1550:     if ($error) {
                   1551:         $request->print('<p class="LC_info">'.$error.'</p>');
                   1552:     }
                   1553:     return;
                   1554: }
                   1555: 
                   1556: sub get_passback_launcher {
                   1557:     my ($cdom,$cnum,$chosen) = @_;
                   1558:     my ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1559:     my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
                   1560:     my ($appname,$setter);
                   1561:     if ($ltitype eq 'c') {
                   1562:         my %lti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1563:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1564:             $appname = $lti{$ltinum}{'name'};
                   1565:             if ($appname) {
                   1566:                 $setter = ' (defined in course)';
                   1567:             }
                   1568:         }
                   1569:     } elsif ($ltitype eq 'd') {
                   1570:         my %lti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1571:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1572:             $appname = $lti{$ltinum}{'name'};
                   1573:             if ($appname) {
                   1574:                 $setter = ' (defined in domain)';
                   1575:             }
                   1576:         }
                   1577:     }
                   1578:     if ($linkuri =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   1579:         my $key = $1;
                   1580:         my $tinyurl;
                   1581:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   1582:         if (defined($cached)) {
                   1583:             $tinyurl = $result;
                   1584:         } else {
                   1585:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   1586:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   1587:             if ($currtiny{$key} ne '') {
                   1588:                 $tinyurl = $currtiny{$key};
                   1589:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   1590:             }
                   1591:         }
                   1592:         if ($tinyurl) {
                   1593:             my ($crsnum,$launchsymb) = split(/\&/,$tinyurl);
                   1594:             if ($crsnum eq $cnum) {
                   1595:                 my %passback = &Apache::lonnet::get('nohist_linkprot_passback',[$launchsymb],$cdom,$cnum);
                   1596:                 if (ref($passback{$launchsymb}) eq 'HASH') {
                   1597:                     if (exists($passback{$launchsymb}{$chosen})) {
1.798   ! raeburn  1598:                         return ($launchsymb,$appname,$setter);
1.796     raeburn  1599:                     }
                   1600:                 }
                   1601:             }
                   1602:         }
                   1603:     }
                   1604:     return ();
                   1605: }
                   1606: 
                   1607: sub sections_and_groups {
                   1608:     my (@sections,@groups,$group_display);
                   1609:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   1610:     if (grep(/^all$/,@groups)) {
                   1611:          @groups = ('all');
                   1612:          $group_display = 'all';
                   1613:     } elsif (grep(/^none$/,@groups)) {
                   1614:          @groups = ('none');
                   1615:          $group_display = 'none';
                   1616:     } elsif (@groups > 0) {
                   1617:          $group_display = join(', ',@groups);
                   1618:     }
                   1619:     if ($env{'request.course.sec'} ne '') {
                   1620:         @sections = ($env{'request.course.sec'});
                   1621:     } else {
                   1622:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1623:     }
                   1624:     my $disabled = ' disabled="disabled"';
                   1625:     if ($perm{'mgr'}) {
                   1626:         if (grep(/^all$/,@sections)) {
                   1627:             undef($disabled);
                   1628:         } else {
                   1629:             foreach my $sec (@sections) {
                   1630:                 if (&canmodify($sec)) {
                   1631:                     undef($disabled);
                   1632:                     last;
                   1633:                 }
                   1634:             }
                   1635:         }
                   1636:     }
                   1637:     if (grep(/^all$/,@sections)) {
                   1638:         @sections = ('all');
                   1639:     }
                   1640:     return(\@sections,\@groups,$group_display,$disabled);
                   1641: }
                   1642: 
                   1643: sub launcher_info_box {
                   1644:     my ($launcher,$appname,$setter,$linkuri,$scope) = @_;
                   1645:     my $shownscope;
                   1646:     if ($scope eq 'res') {
                   1647:         $shownscope = &mt('Resource');
                   1648:     } elsif ($scope eq 'map') {
                   1649:         $shownscope = &mt('Folder');
                   1650:     }  elsif ($scope eq 'rec') {
                   1651:         $shownscope = &mt('Folder + sub-folders');
                   1652:     }
                   1653:     return '<p>'.
                   1654:            &Apache::lonhtmlcommon::start_pick_box().
                   1655:            &Apache::lonhtmlcommon::row_title(&mt('Launch Item Title')).
1.797     raeburn  1656:            &Apache::lonnet::gettitle($launcher).
1.796     raeburn  1657:            &Apache::lonhtmlcommon::row_closure().
                   1658:            &Apache::lonhtmlcommon::row_title(&mt('Deep-link')).
                   1659:            $linkuri.
                   1660:            &Apache::lonhtmlcommon::row_closure().
                   1661:            &Apache::lonhtmlcommon::row_title(&mt('Launcher')).
                   1662:            $appname.' '.$setter.
                   1663:            &Apache::lonhtmlcommon::row_closure().
                   1664:            &Apache::lonhtmlcommon::row_title(&mt('Score Type')).
                   1665:            $shownscope.      
                   1666:            &Apache::lonhtmlcommon::row_closure(1).
                   1667:            &Apache::lonhtmlcommon::end_pick_box().'</p>'."\n";
                   1668: }
                   1669: 
1.798   ! raeburn  1670: sub passbacks_for_symb {
        !          1671:     my ($cdom,$cnum,$symb) = @_;
        !          1672:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
        !          1673:     my %needpb;
        !          1674:     if (keys(%passback)) {
        !          1675:         my $checkpb = 1;
        !          1676:         if (exists($passback{$symb})) {
        !          1677:             if (keys(%passback) == 1) {
        !          1678:                 undef($checkpb);
        !          1679:             }
        !          1680:             if (ref($passback{$symb}) eq 'HASH') {
        !          1681:                 foreach my $launcher (keys(%{$passback{$symb}})) {
        !          1682:                     $needpb{$launcher} = 1;
        !          1683:                 }
        !          1684:             }
        !          1685:         }
        !          1686:         if ($checkpb) {
        !          1687:             my ($map,$id,$url) = &Apache::lonnet::decode_symb($symb);
        !          1688:             my $navmap = Apache::lonnavmaps::navmap->new();
        !          1689:             if (ref($navmap)) {
        !          1690:                 my $mapres = $navmap->getResourceByUrl($map);
        !          1691:                 if (ref($mapres)) {
        !          1692:                     my $mapsymb = $mapres->symb();
        !          1693:                     if (exists($passback{$mapsymb})) {
        !          1694:                         if (keys(%passback) == 1) {
        !          1695:                             undef($checkpb);
        !          1696:                         }
        !          1697:                         if (ref($passback{$mapsymb}) eq 'HASH') {
        !          1698:                             foreach my $launcher (keys(%{$passback{$mapsymb}})) {
        !          1699:                                 $needpb{$launcher} = 1;
        !          1700:                             }
        !          1701:                         }
        !          1702:                     }
        !          1703:                     my %posspb;
        !          1704:                     if ($checkpb) {
        !          1705:                         my @recurseup = $navmap->recurseup_maps($map,1);
        !          1706:                         if (@recurseup) {
        !          1707:                             map { $posspb{$_} = 1; } @recurseup;
        !          1708:                         }
        !          1709:                     }
        !          1710:                     foreach my $key (keys(%passback)) {
        !          1711:                         if (exists($posspb{$key})) {
        !          1712:                             if (ref($passback{$key}) eq 'HASH') {
        !          1713:                                 foreach my $launcher (keys(%{$passback{$key}})) {
        !          1714:                                     my ($linkuri,$linkprotector,$scope) = split("\0",$launcher);
        !          1715:                                     next unless ($scope eq 'rec');
        !          1716:                                     $needpb{$launcher} = 1;
        !          1717:                                 }
        !          1718:                             }
        !          1719:                         }
        !          1720:                     }
        !          1721:                 }
        !          1722:             }
        !          1723:         }
        !          1724:     }
        !          1725:     return %needpb;
        !          1726: }
        !          1727: 
        !          1728: sub process_passbacks {
        !          1729:     my ($context,$symbs,$cdom,$cnum,$udom,$uname,$weights,$awardeds,$excuseds,$needpb,
        !          1730:         $skip_passback,$pbsave,$pbids) = @_;
        !          1731:     if ((ref($needpb) eq 'HASH') && (ref($skip_passback) eq 'HASH') && (ref($pbsave) eq 'HASH')) {
        !          1732:         my (%weight,%awarded,%excused);
        !          1733:         if ((ref($symbs) eq 'ARRAY') && (ref($weights) eq 'HASH') && (ref($awardeds) eq 'HASH') &&
        !          1734:             (ref($excuseds) eq 'HASH')) {
        !          1735:             %weight = %{$weights};
        !          1736:             %awarded = %{$awardeds};
        !          1737:             %excused = %{$excuseds};
        !          1738:         }
        !          1739:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
        !          1740:         my @launchers = keys(%{$needpb});
        !          1741:         my %pbinfo;
        !          1742:         if (ref($pbids) eq 'HASH') {
        !          1743:             %pbinfo = %{$pbids};
        !          1744:         } else {
        !          1745:             %pbinfo = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@launchers,$udom,$uname);
        !          1746:         }
        !          1747:         my %pbc = &common_passback_info();
        !          1748:         foreach my $launcher (@launchers) {
        !          1749:             if (ref($pbinfo{$launcher}) eq 'ARRAY') {
        !          1750:                 my $pbid = $pbinfo{$launcher}[0];
        !          1751:                 my $pburl = $pbinfo{$launcher}[1];
        !          1752:                 my (%total_by_symb,%possible_by_symb);
        !          1753:                 if (($pbid ne '') && ($pburl ne '')) {
        !          1754:                     next if ($skip_passback->{$launcher});
        !          1755:                     my %pb = %pbc;
        !          1756:                     if ((exists($pbsave->{$launcher})) &&
        !          1757:                         (ref($pbsave->{$launcher}) eq 'HASH')) {
        !          1758:                         foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
        !          1759:                                           'symb','map','pbscope','linkuri','linkprotector','scope') {
        !          1760:                             $pb{$item} = $pbsave->{$launcher}{$item};
        !          1761:                         }
        !          1762:                     } else {
        !          1763:                         my $ltitype;
        !          1764:                         ($pb{'linkuri'},$pb{'linkprotector'},$pb{'scope'}) = split("\0",$launcher);
        !          1765:                         ($pb{'ltinum'},$ltitype) = ($pb{'linkprotector'} =~ /^(\d+)(c|d)$/);
        !          1766:                         if ($ltitype eq 'c') {
        !          1767:                             my %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
        !          1768:                             $pb{'lti_in_use'} = $crslti{$pb{'ltinum'}};
        !          1769:                             $pb{'crsdef'} = 1;
        !          1770:                         } else {
        !          1771:                             my %domlti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
        !          1772:                             $pb{'lti_in_use'} = $domlti{$pb{'ltinum'}};
        !          1773:                         }
        !          1774:                         if (ref($pb{'lti_in_use'}) eq 'HASH') {
        !          1775:                             $pb{'msgformat'} = $pb{'lti_in_use'}->{'passbackformat'};
        !          1776:                             $pb{'keynum'} = $pb{'lti_in_use'}->{'cipher'};
        !          1777:                             $pb{'scoretype'} = 'decimal';
        !          1778:                             if ($pb{'lti_in_use'}->{'scoreformat'} =~ /^(decimal|ratio|percentage)$/) {
        !          1779:                                 $pb{'scoretype'} = $1;
        !          1780:                             }
        !          1781:                             $pb{'symb'} = &Apache::loncommon::symb_from_tinyurl($pb{'linkuri'},$cnum,$cdom);
        !          1782:                             if ($pb{'symb'} =~ /\.(page|sequence)$/) {
        !          1783:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[2]);
        !          1784:                             } else {
        !          1785:                                 $pb{'map'} = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pb{'symb'}))[0]);
        !          1786:                             }
        !          1787:                             $pb{'map'} = &Apache::lonnet::clutter($pb{'map'});
        !          1788:                             if ($pb{'scope'} eq 'res') {
        !          1789:                                 $pb{'pbscope'} = 'resource';
        !          1790:                             } elsif ($pb{'scope'} eq 'map') {
        !          1791:                                 $pb{'pbscope'} = 'nonrec';
        !          1792:                             } elsif ($pb{'scope'} eq 'rec') {
        !          1793:                                 $pb{'pbscope'} = 'map';
        !          1794:                             }
        !          1795:                             foreach my $item ('lti_in_use','crsdef','ltinum','keynum','scoretype','msgformat',
        !          1796:                                               'symb','map','pbscope','linkuri','linkprotector','scope') {
        !          1797:                                 $pbsave->{$launcher}{$item} = $pb{$item};
        !          1798:                             }
        !          1799:                         } else {
        !          1800:                             $skip_passback->{$launcher} = 1;
        !          1801:                         }
        !          1802:                     }
        !          1803:                     if (ref($symbs) eq 'ARRAY') {
        !          1804:                         foreach my $symb (@{$symbs}) {
        !          1805:                             if ((ref($weight{$symb}) eq 'HASH') && (ref($awarded{$symb}) eq 'HASH') &&
        !          1806:                                 (ref($excused{$symb}) eq 'HASH')) {
        !          1807:                                 foreach my $part (keys(%{$weight{$symb}})) {
        !          1808:                                     if ($excused{$symb}{$part}) {
        !          1809:                                         next;
        !          1810:                                     }
        !          1811:                                     my $partweight = $weight{$symb}{$part} eq '' ? 1 :
        !          1812:                                                      $weight{$symb}{$part};
        !          1813:                                     if ($awarded{$symb}{$part}) {
        !          1814:                                         $total_by_symb{$symb} += $partweight * $awarded{$symb}{$part};
        !          1815:                                     }
        !          1816:                                     $possible_by_symb{$symb} += $partweight;
        !          1817:                                 }
        !          1818:                             }
        !          1819:                         }
        !          1820:                     }
        !          1821:                     if ($context eq 'updatebypage') {
        !          1822:                         my $ltigrade = {
        !          1823:                                         'ltinum'     => $pb{'ltinum'},
        !          1824:                                         'lti'        => $pb{'lti_in_use'},
        !          1825:                                         'crsdef'     => $pb{'crsdef'},
        !          1826:                                         'cid'        => $cdom.'_'.$cnum,
        !          1827:                                         'uname'      => $uname,
        !          1828:                                         'udom'       => $udom,
        !          1829:                                         'uhome'      => $uhome,
        !          1830:                                         'pbid'       => $pbid,
        !          1831:                                         'pburl'      => $pburl,
        !          1832:                                         'pbtype'     => $pb{'type'},
        !          1833:                                         'pbscope'    => $pb{'pbscope'},
        !          1834:                                         'pbmap'      => $pb{'map'},
        !          1835:                                         'pbsymb'     => $pb{'symb'},
        !          1836:                                         'format'     => $pb{'scoretype'},
        !          1837:                                         'scope'      => $pb{'scope'},
        !          1838:                                         'clientip'   => $pb{'clientip'},
        !          1839:                                         'linkprot'   => $pb{'linkprotector'},
        !          1840:                                         'total_s'    => \%total_by_symb,
        !          1841:                                         'possible_s' => \%possible_by_symb,
        !          1842:                         };
        !          1843:                         push(@Apache::lonhomework::ltipassback,$ltigrade);
        !          1844:                         next;
        !          1845:                     }
        !          1846:                     my ($total,$possible);
        !          1847:                     if ($pb{'pbscope'} eq 'resource') {
        !          1848:                         $total = $total_by_symb{$pb{'symb'}};
        !          1849:                         $possible = $possible_by_symb{$pb{'symb'}};
        !          1850:                     } elsif (($pb{'pbscope'} eq 'map') || ($pb{'pbscope'} eq 'nonrec')) {
        !          1851:                         ($total,$possible) =
        !          1852:                             &Apache::lonhomework::get_lti_score($uname,$udom,$pb{'map'},$pb{'pbscope'},
        !          1853:                                                                 \%total_by_symb,\%possible_by_symb);
        !          1854:                     }
        !          1855:                     if (!$possible) {
        !          1856:                         $total = 0;
        !          1857:                         $possible = 1;
        !          1858:                     }
        !          1859:                     my ($sent,$score,$code,$result) =
        !          1860:                         &LONCAPA::ltiutils::send_grade($cdom,$cnum,$pb{'crsdef'},$pb{'type'},$pb{'ltinum'},
        !          1861:                                                        $pb{'keynum'},$pbid,$pburl,$pb{'scoretype'},$pb{'sigmethod'},
        !          1862:                                                        $pb{'msgformat'},$total,$possible);
        !          1863:                     my $no_passback;
        !          1864:                     if ($sent) {
        !          1865:                         if ($code == 200) {
        !          1866:                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
        !          1867:                             my $store = {
        !          1868:                                 'score' => $score,
        !          1869:                                 'ip' => $pb{'ip'},
        !          1870:                                 'host' => $pb{'lonhost'},
        !          1871:                                 'protector' => $pb{'linkprotector'},
        !          1872:                                 'deeplink' => $pb{'linkuri'},
        !          1873:                                 'scope' => $pb{'scope'},
        !          1874:                                 'url' => $pburl,
        !          1875:                                 'id' => $pbid,
        !          1876:                                 'clientip' => $pb{'clientip'},
        !          1877:                                 'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
        !          1878:                             };
        !          1879:                             my $value='';
        !          1880:                             foreach my $key (keys(%{$store})) {
        !          1881:                                  $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
        !          1882:                             }
        !          1883:                             $value=~s/\&$//;
        !          1884:                             &Apache::lonnet::courselog(&escape($pb{'linkuri'}).':'.$uname.':'.$udom.':EXPORT:'.$value);
        !          1885:                             &Apache::lonnet::cstore({'score' => $score},$launcher,$namespace,$udom,$uname,'',$pb{'ip'},1);
        !          1886:                         } else {
        !          1887:                             $no_passback = 1;
        !          1888:                         }
        !          1889:                     } else {
        !          1890:                         $no_passback = 1;
        !          1891:                     }
        !          1892:                     if ($no_passback) {
        !          1893:                         &Apache::lonnet::log($udom,$uname,$uhome,$no_passback." score: $score; total: $total; possible: $possible");
        !          1894:                         my $ltigrade = {
        !          1895:                            'ltinum'   => $pb{'ltinum'},
        !          1896:                            'lti'      => $pb{'lti_in_use'},
        !          1897:                            'crsdef'   => $pb{'crsdef'},
        !          1898:                            'cid'      => $cdom.'_'.$cnum,
        !          1899:                            'uname'    => $uname,
        !          1900:                            'udom'     => $udom,
        !          1901:                            'uhome'    => $uhome,
        !          1902:                            'pbid'     => $pbid,
        !          1903:                            'pburl'    => $pburl,
        !          1904:                            'pbtype'   => $pb{'type'},
        !          1905:                            'pbscope'  => $pb{'pbscope'},
        !          1906:                            'pbmap'    => $pb{'map'},
        !          1907:                            'pbsymb'   => $pb{'symb'},
        !          1908:                            'format'   => $pb{'scoretype'},
        !          1909:                            'scope'    => $pb{'scope'},
        !          1910:                            'clientip' => $pb{'clientip'},
        !          1911:                            'linkprot' => $pb{'linkprotector'},
        !          1912:                            'total'    => $total,
        !          1913:                            'possible' => $possible,
        !          1914:                            'score'    => $score,
        !          1915:                         };
        !          1916:                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
        !          1917:                     }
        !          1918:                 }
        !          1919:             }
        !          1920:         }
        !          1921:     }
        !          1922:     return;
        !          1923: }
        !          1924: 
        !          1925: sub common_passback_info {
        !          1926:     my %pbc = (
        !          1927:                sigmethod => 'HMAC-SHA1',
        !          1928:                type      => 'linkprot',
        !          1929:                clientip  => &Apache::lonnet::get_requestor_ip(),
        !          1930:                lonhost   => $Apache::lonnet::perlvar{'lonHostID'},
        !          1931:                ip        => &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}),
        !          1932:              );
        !          1933:     return %pbc;
        !          1934: }
        !          1935: 
1.44      ng       1936: #--- This is called by a number of programs.
                   1937: #--- Called from the Grading Menu - View/Grade an individual student
                   1938: #--- Also called directly when one clicks on the subm button 
                   1939: #    on the problem page.
1.30      ng       1940: sub listStudents {
1.773     raeburn  1941:     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1942: 
1.747     raeburn  1943:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1944:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1945:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1946:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1947:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www      1948:     unless ($submitonly) {
1.766     raeburn  1949:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www      1950:     }
1.49      albertel 1951: 
1.632     www      1952:     my $result='';
1.623     www      1953:     my $res_error;
1.773     raeburn  1954:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   1955: 
                   1956:     my $table;
                   1957:     if (ref($partlist) eq 'ARRAY') {
                   1958:         if (scalar(@$partlist) > 1 ) {
                   1959:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1960:         } elsif ($divforres) {
                   1961:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1962:         } else {
                   1963:             $table = '<br clear="all" />';
                   1964:         }
                   1965:     }
1.49      albertel 1966: 
1.796     raeburn  1967:     $request->print(&checkselect_js());
1.597     wenzelju 1968:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1969: 
                   1970:     function reLoadList(formname) {
1.112     ng       1971: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1972: 	formname.command.value = 'submission';
                   1973: 	formname.submit();
                   1974:     }
1.45      ng       1975: LISTJAVASCRIPT
                   1976: 
1.118     ng       1977:     &commonJSfunctions($request);
1.41      ng       1978:     $request->print($result);
1.39      ng       1979: 
1.154     albertel 1980:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.773     raeburn  1981: 	"\n".$table;
                   1982: 
1.561     bisitz   1983:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn  1984:     unless ($is_tool) {
                   1985:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1986:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1987:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1988:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1989:                       .&Apache::lonhtmlcommon::row_closure();
                   1990:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1991:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1992:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1993:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1994:                       .&Apache::lonhtmlcommon::row_closure();
                   1995:     }
1.485     albertel 1996: 
1.442     banghart 1997:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1998:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1999:     $env{'form.Status'} = $saveStatus;
1.745     raeburn  2000:     my %optiontext;
                   2001:     if ($is_tool) {
                   2002:         %optiontext = &Apache::lonlocal::texthash (
                   2003:                           lastonly => 'last transaction',
                   2004:                           last     => 'last transaction with details',
                   2005:                           datesub  => 'all transactions',
                   2006:                           all      => 'all transactions with details',
                   2007:                       );
                   2008:     } else {
                   2009:         %optiontext = &Apache::lonlocal::texthash (
                   2010:                           lastonly => 'last submission',
                   2011:                           last     => 'last submission with details',
                   2012:                           datesub  => 'all submissions',
                   2013:                           all      => 'all submissions with details',
                   2014:                       );
                   2015:     }
1.773     raeburn  2016:     my $submission_options =
1.592     bisitz   2017:         '<span class="LC_nobreak">'.
1.624     www      2018:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  2019:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   2020:         '<span class="LC_nobreak">'.
                   2021:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  2022:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   2023:         '<span class="LC_nobreak">'.
1.628     www      2024:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  2025:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   2026:         '<span class="LC_nobreak">'.
                   2027:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  2028:         $optiontext{'all'}.'</label></span>';
                   2029:     my $viewtitle;
                   2030:     if ($is_tool) {
                   2031:         $viewtitle = &mt('View Transactions');
                   2032:     } else {
                   2033:         $viewtitle = &mt('View Submissions');
                   2034:     }
1.773     raeburn  2035:     my ($compmsg,$nocompmsg);
                   2036:     $nocompmsg = ' checked="checked"';
                   2037:     if ($numessay) {
                   2038:         $compmsg = $nocompmsg;
                   2039:         $nocompmsg = '';
                   2040:     }
1.745     raeburn  2041:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.780     raeburn  2042:                   .$submission_options;
                   2043: # Check if any gradable
                   2044:     my $showmore;
                   2045:     if ($perm{'mgr'}) {
                   2046:         my @sections;
                   2047:         if ($env{'request.course.sec'} ne '') {
                   2048:             @sections = ($env{'request.course.sec'});
1.783     raeburn  2049:         } elsif ($env{'form.section'} eq '') {
                   2050:             @sections = ('all');
1.780     raeburn  2051:         } else {
                   2052:             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   2053:         }
                   2054:         if (grep(/^all$/,@sections)) {
                   2055:             $showmore = 1;
                   2056:         } else {
                   2057:             foreach my $sec (@sections) {
                   2058:                 if (&canmodify($sec)) {
                   2059:                     $showmore = 1;
                   2060:                     last;
                   2061:                 }
                   2062:             }
                   2063:         }
                   2064:     }
                   2065: 
                   2066:     if ($showmore) {
                   2067:         $gradeTable .=
                   2068:                    &Apache::lonhtmlcommon::row_closure()
1.773     raeburn  2069:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   2070:                   .'<span class="LC_nobreak">'
                   2071:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   2072:                   .&mt('No').('&nbsp;'x2).'</label>'
                   2073:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   2074:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   2075:                   .&Apache::lonhtmlcommon::row_closure();
                   2076: 
1.780     raeburn  2077:         $gradeTable .= 
                   2078:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   2079:                   .'<select name="increment">'
                   2080:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   2081:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   2082:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   2083:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773     raeburn  2084:                   .'</select>';
1.780     raeburn  2085:     }
1.485     albertel 2086:     $gradeTable .= 
1.432     banghart 2087:         &build_section_inputs().
1.45      ng       2088: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 2089: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       2090: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      2091:     if (exists($env{'form.Status'})) {
1.784     raeburn  2092: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng       2093:     } else {
1.773     raeburn  2094:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2095:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   2096:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773     raeburn  2097:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       2098:     }
1.773     raeburn  2099:     if ($numessay) {
                   2100:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   2101:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   2102:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  2103:     }
1.773     raeburn  2104:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
                   2105:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  2106:     my $regrademsg;
                   2107:     if ($is_tool) {
                   2108:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
                   2109:     } else {
                   2110:         $regrademsg = &mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.");
                   2111:     }
1.561     bisitz   2112:     $gradeTable .= '<p>'
1.745     raeburn  2113:                   .$regrademsg."\n"
1.561     bisitz   2114:                   .'<input type="hidden" name="command" value="processGroup" />'
                   2115:                   .'</p>';
1.249     albertel 2116: 
                   2117: # checkall buttons
                   2118:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       2119:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   2120:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   2121:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 2122:     $gradeTable.=&check_buttons();
1.450     banghart 2123:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 2124:     $gradeTable.= &Apache::loncommon::start_data_table().
                   2125: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       2126:     my $loop = 0;
                   2127:     while ($loop < 2) {
1.485     albertel 2128: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   2129: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      2130: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 2131: 	    foreach my $part (sort(@$partlist)) {
                   2132: 		my $display_part=
                   2133: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   2134: 		$gradeTable.=
                   2135: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       2136: 	    }
1.301     albertel 2137: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 2138: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       2139: 	}
                   2140: 	$loop++;
1.126     ng       2141: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       2142:     }
1.474     albertel 2143:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       2144: 
1.45      ng       2145:     my $ctr = 0;
1.294     albertel 2146:     foreach my $student (sort 
                   2147: 			 {
                   2148: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2149: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2150: 			     }
                   2151: 			     return $a cmp $b;
                   2152: 			 }
                   2153: 			 (keys(%$fullname))) {
1.41      ng       2154: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2155: 
1.110     ng       2156: 	my %status = ();
1.301     albertel 2157: 
                   2158: 	if ($submitonly eq 'queued') {
                   2159: 	    my %queue_status = 
                   2160: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2161: 							$udom,$uname);
                   2162: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2163: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   2164: 	}
                   2165: 
1.618     www      2166: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 2167: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2168: 	    my $submitted = 0;
1.164     albertel 2169: 	    my $graded = 0;
1.248     albertel 2170: 	    my $incorrect = 0;
1.110     ng       2171: 	    foreach (keys(%status)) {
1.145     albertel 2172: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2173: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   2174: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   2175: 		
1.110     ng       2176: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2177: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 2178: 		    $submitted = 0;
1.150     albertel 2179: 		    my ($part)=split(/\./,$partid);
1.110     ng       2180: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 2181: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       2182: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   2183: 		}
1.41      ng       2184: 	    }
1.248     albertel 2185: 	    
1.156     albertel 2186: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2187: 				     $submitonly eq 'incorrect' ||
                   2188: 				     $submitonly eq 'graded'));
1.248     albertel 2189: 	    next if (!$graded && ($submitonly eq 'graded'));
                   2190: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2191: 	}
1.34      ng       2192: 
1.45      ng       2193: 	$ctr++;
1.249     albertel 2194: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 2195:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 2196: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 2197: 	    if ($ctr%2 ==1) {
                   2198: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   2199: 	    }
1.126     ng       2200: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   2201:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 2202:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   2203: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   2204: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 2205: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       2206: 
1.618     www      2207: 	    if ($submitonly ne 'all') {
1.524     raeburn  2208: 		foreach (sort(keys(%status))) {
1.485     albertel 2209: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   2210: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       2211: 		}
1.41      ng       2212: 	    }
1.126     ng       2213: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 2214: 	    if ($ctr%2 ==0) {
                   2215: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   2216: 	    }
1.41      ng       2217: 	}
                   2218:     }
1.110     ng       2219:     if ($ctr%2 ==1) {
1.126     ng       2220: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      2221: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       2222: 		foreach (@$partlist) {
                   2223: 		    $gradeTable.='<td>&nbsp;</td>';
                   2224: 		}
1.301     albertel 2225: 	    } elsif ($submitonly eq 'queued') {
                   2226: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       2227: 	    }
1.474     albertel 2228: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       2229:     }
                   2230: 
1.474     albertel 2231:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   2232:         '<input type="button" '.
                   2233:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   2234:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       2235:     if ($ctr == 0) {
1.96      albertel 2236: 	my $num_students=(scalar(keys(%$fullname)));
                   2237: 	if ($num_students eq 0) {
1.485     albertel 2238: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 2239: 	} else {
1.171     albertel 2240: 	    my $submissions='submissions';
                   2241: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   2242: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 2243: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 2244: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   2245: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 2246: 		    $num_students).
                   2247: 		'</span><br />';
1.96      albertel 2248: 	}
1.46      ng       2249:     } elsif ($ctr == 1) {
1.474     albertel 2250: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       2251:     }
                   2252:     $request->print($gradeTable);
1.44      ng       2253:     return '';
1.10      ng       2254: }
                   2255: 
1.796     raeburn  2256: #---- Called from the listStudents and the names_for_passback routines.
                   2257: 
                   2258: sub checkselect_js {
                   2259:     my ($formname) = @_;
                   2260:     if ($formname eq '') {
                   2261:         $formname = 'gradesub';
                   2262:     }
                   2263:     my %js_lt;
                   2264:     if ($formname eq 'passbackusers') {
                   2265:         %js_lt = &Apache::lonlocal::texthash (
                   2266:                      'multiple' => 'Please select a student or group of students before pushing the Save Scores button.',
                   2267:                      'single'   => 'Please select the student before pushing the Save Scores button.',
                   2268:                  );
                   2269:     } else {
                   2270:         %js_lt = &Apache::lonlocal::texthash (
                   2271:                      'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   2272:                      'single'   => 'Please select the student before clicking on the Next button.',
                   2273:                  );
                   2274:     }
                   2275:     &js_escape(\%js_lt);
                   2276:     return &Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT);
                   2277: 
                   2278:     function checkSelect(checkBox) {
                   2279:         var ctr=0;
                   2280:         var sense="";
                   2281:         var len = checkBox.length;
                   2282:         if (len == undefined) len = 1;
                   2283:         if (len > 1) {
                   2284:             for (var i=0; i<len; i++) {
                   2285:                 if (checkBox[i].checked) {
                   2286:                     ctr++;
                   2287:                 }
                   2288:             }
                   2289:             sense = '$js_lt{'multiple'}';
                   2290:         } else {
                   2291:             if (checkBox.checked) {
                   2292:                 ctr = 1;
                   2293:             }
                   2294:             sense = '$js_lt{'single'}';
                   2295:         }
                   2296:         if (ctr == 0) {
                   2297:             alert(sense);
                   2298:             return false;
                   2299:         }
                   2300:         document.$formname.submit();
                   2301:     }
                   2302: LISTJAVASCRIPT
                   2303: 
                   2304: }
1.249     albertel 2305: 
                   2306: sub check_script {
1.766     raeburn  2307:     my ($form,$type) = @_;
                   2308:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 2309:     function checkall() {
                   2310:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2311:             ele = document.forms.'.$form.'.elements[i];
                   2312:             if (ele.name == "'.$type.'") {
                   2313:             document.forms.'.$form.'.elements[i].checked=true;
                   2314:                                        }
                   2315:         }
                   2316:     }
                   2317: 
                   2318:     function checksec() {
                   2319:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2320:             ele = document.forms.'.$form.'.elements[i];
                   2321:            string = document.forms.'.$form.'.chksec.value;
                   2322:            if
                   2323:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   2324:               document.forms.'.$form.'.elements[i].checked=true;
                   2325:             }
                   2326:         }
                   2327:     }
                   2328: 
                   2329: 
                   2330:     function uncheckall() {
                   2331:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2332:             ele = document.forms.'.$form.'.elements[i];
                   2333:             if (ele.name == "'.$type.'") {
                   2334:             document.forms.'.$form.'.elements[i].checked=false;
                   2335:                                        }
                   2336:         }
                   2337:     }
                   2338: 
1.597     wenzelju 2339: '."\n");
1.249     albertel 2340:     return $chkallscript;
                   2341: }
                   2342: 
                   2343: sub check_buttons {
1.485     albertel 2344:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   2345:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   2346:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 2347:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   2348:     return $buttons;
                   2349: }
                   2350: 
1.44      ng       2351: #     Displays the submissions for one student or a group of students
1.34      ng       2352: sub processGroup {
1.766     raeburn  2353:     my ($request,$symb) = @_;
1.41      ng       2354:     my $ctr        = 0;
1.155     albertel 2355:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       2356:     my $total      = scalar(@stuchecked)-1;
1.45      ng       2357: 
1.396     banghart 2358:     foreach my $student (@stuchecked) {
                   2359: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 2360: 	$env{'form.student'}        = $uname;
                   2361: 	$env{'form.userdom'}        = $udom;
                   2362: 	$env{'form.fullname'}       = $fullname;
1.619     www      2363: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2364: 	$ctr++;
                   2365:     }
                   2366:     return '';
1.35      ng       2367: }
1.34      ng       2368: 
1.44      ng       2369: #------------------------------------------------------------------------------------
                   2370: #
                   2371: #-------------------------- Next few routines handles grading by student, essentially
                   2372: #                           handles essay response type problem/part
                   2373: #
                   2374: #--- Javascript to handle the submission page functionality ---
                   2375: sub sub_page_js {
                   2376:     my $request = shift;
1.736     damieng  2377:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   2378:     &js_escape(\$alertmsg);
1.597     wenzelju 2379:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       2380:     function updateRadio(formname,id,weight) {
1.125     ng       2381: 	var gradeBox = formname["GD_BOX"+id];
                   2382: 	var radioButton = formname["RADVAL"+id];
                   2383: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       2384: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       2385: 	gradeBox.value = pts;
                   2386: 	var resetbox = false;
                   2387: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  2388: 	    alert("$alertmsg"+pts);
1.71      ng       2389: 	    for (var i=0; i<radioButton.length; i++) {
                   2390: 		if (radioButton[i].checked) {
                   2391: 		    gradeBox.value = i;
                   2392: 		    resetbox = true;
                   2393: 		}
                   2394: 	    }
                   2395: 	    if (!resetbox) {
                   2396: 		formtextbox.value = "";
                   2397: 	    }
                   2398: 	    return;
1.44      ng       2399: 	}
1.71      ng       2400: 
                   2401: 	if (pts > weight) {
                   2402: 	    var resp = confirm("You entered a value ("+pts+
                   2403: 			       ") greater than the weight for the part. Accept?");
                   2404: 	    if (resp == false) {
1.125     ng       2405: 		gradeBox.value = oldpts;
1.71      ng       2406: 		return;
                   2407: 	    }
1.44      ng       2408: 	}
1.13      albertel 2409: 
1.71      ng       2410: 	for (var i=0; i<radioButton.length; i++) {
                   2411: 	    radioButton[i].checked=false;
                   2412: 	    if (pts == i && pts != "") {
                   2413: 		radioButton[i].checked=true;
                   2414: 	    }
                   2415: 	}
                   2416: 	updateSelect(formname,id);
1.125     ng       2417: 	formname["stores"+id].value = "0";
1.41      ng       2418:     }
1.5       albertel 2419: 
1.72      ng       2420:     function writeBox(formname,id,pts) {
1.125     ng       2421: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2422: 	if (checkSolved(formname,id) == 'update') {
                   2423: 	    gradeBox.value = pts;
                   2424: 	} else {
1.125     ng       2425: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       2426: 	    gradeBox.value = oldpts;
1.125     ng       2427: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       2428: 	    for (var i=0; i<radioButton.length; i++) {
                   2429: 		radioButton[i].checked=false;
1.72      ng       2430: 		if (i == oldpts) {
1.71      ng       2431: 		    radioButton[i].checked=true;
                   2432: 		}
                   2433: 	    }
1.41      ng       2434: 	}
1.125     ng       2435: 	formname["stores"+id].value = "0";
1.71      ng       2436: 	updateSelect(formname,id);
                   2437: 	return;
1.41      ng       2438:     }
1.44      ng       2439: 
1.71      ng       2440:     function clearRadBox(formname,id) {
                   2441: 	if (checkSolved(formname,id) == 'noupdate') {
                   2442: 	    updateSelect(formname,id);
                   2443: 	    return;
                   2444: 	}
1.125     ng       2445: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       2446: 	for (var i=0; i<gradeSelect.length; i++) {
                   2447: 	    if (gradeSelect[i].selected) {
                   2448: 		var selectx=i;
                   2449: 	    }
                   2450: 	}
1.125     ng       2451: 	var stores = formname["stores"+id];
1.71      ng       2452: 	if (selectx == stores.value) { return };
1.125     ng       2453: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2454: 	gradeBox.value = "";
1.125     ng       2455: 	var radioButton = formname["RADVAL"+id];
1.71      ng       2456: 	for (var i=0; i<radioButton.length; i++) {
                   2457: 	    radioButton[i].checked=false;
                   2458: 	}
                   2459: 	stores.value = selectx;
                   2460:     }
1.5       albertel 2461: 
1.71      ng       2462:     function checkSolved(formname,id) {
1.125     ng       2463: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       2464: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   2465: 	    if (!reply) {return "noupdate";}
1.120     ng       2466: 	    formname.overRideScore.value = 'yes';
1.41      ng       2467: 	}
1.71      ng       2468: 	return "update";
1.13      albertel 2469:     }
1.71      ng       2470: 
                   2471:     function updateSelect(formname,id) {
1.125     ng       2472: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       2473: 	return;
1.41      ng       2474:     }
1.33      ng       2475: 
1.121     ng       2476: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       2477:     function checksubmit(formname,val,total,parttot) {
1.121     ng       2478: 	formname.gradeOpt.value = val;
1.71      ng       2479: 	if (val == "Save & Next") {
                   2480: 	    for (i=0;i<=total;i++) {
                   2481: 		for (j=0;j<parttot;j++) {
1.125     ng       2482: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       2483: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2484: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       2485: 			if (points == "") {
1.125     ng       2486: 			    var name = formname["name"+i].value;
1.129     ng       2487: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   2488: 			    var resp = confirm("You did not assign a score for "+studentID+
                   2489: 					       ", part "+partid+". Continue?");
1.71      ng       2490: 			    if (resp == false) {
1.125     ng       2491: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       2492: 				return false;
                   2493: 			    }
                   2494: 			}
                   2495: 		    }
                   2496: 		}
                   2497: 	    }
                   2498: 	}
1.120     ng       2499: 	formname.submit();
                   2500:     }
                   2501: 
1.71      ng       2502: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   2503:     function checkSubmitPage(formname,total) {
                   2504: 	noscore = new Array(100);
                   2505: 	var ptr = 0;
                   2506: 	for (i=1;i<total;i++) {
1.125     ng       2507: 	    var partid = formname["q_"+i].value;
1.127     ng       2508: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2509: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   2510: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       2511: 		if (points == "" && status != "correct_by_student") {
                   2512: 		    noscore[ptr] = i;
                   2513: 		    ptr++;
                   2514: 		}
                   2515: 	    }
                   2516: 	}
                   2517: 	if (ptr != 0) {
                   2518: 	    var sense = ptr == 1 ? ": " : "s: ";
                   2519: 	    var prolist = "";
                   2520: 	    if (ptr == 1) {
                   2521: 		prolist = noscore[0];
                   2522: 	    } else {
                   2523: 		var i = 0;
                   2524: 		while (i < ptr-1) {
                   2525: 		    prolist += noscore[i]+", ";
                   2526: 		    i++;
                   2527: 		}
                   2528: 		prolist += "and "+noscore[i];
                   2529: 	    }
                   2530: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   2531: 	    if (resp == false) {
                   2532: 		return false;
                   2533: 	    }
                   2534: 	}
1.45      ng       2535: 
1.71      ng       2536: 	formname.submit();
                   2537:     }
                   2538: SUBJAVASCRIPT
                   2539: }
1.45      ng       2540: 
1.773     raeburn  2541: #--- javascript for grading message center
                   2542: sub sub_grademessage_js {
1.71      ng       2543:     my $request = shift;
1.80      ng       2544:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       2545:     &commonJSfunctions($request);
1.350     albertel 2546: 
1.629     www      2547:     my $inner_js_msg_central= (<<INNERJS);
                   2548: <script type="text/javascript">
1.350     albertel 2549:     function checkInput() {
                   2550:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   2551:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   2552:       var usrctr = document.msgcenter.usrctr.value;
                   2553:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   2554:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   2555: 
                   2556:       var msgchk = "";
                   2557:       if (document.msgcenter.subchk.checked) {
                   2558:          msgchk = "msgsub,";
                   2559:       }
                   2560:       var includemsg = 0;
                   2561:       for (var i=1; i<=nmsg; i++) {
                   2562:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   2563:           var frmmsg = document.msgcenter["msg"+i];
                   2564:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   2565:           var showflg = opener.document.SCORE["shownOnce"+i];
                   2566:           showflg.value = "1";
                   2567:           var chkbox = document.msgcenter["msgn"+i];
                   2568:           if (chkbox.checked) {
                   2569:              msgchk += "savemsg"+i+",";
                   2570:              includemsg = 1;
                   2571:           }
                   2572:       }
                   2573:       if (document.msgcenter.newmsgchk.checked) {
                   2574:          msgchk += "newmsg"+usrctr;
                   2575:          includemsg = 1;
                   2576:       }
                   2577:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   2578:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   2579:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   2580:       includemsg.value = msgchk;
                   2581: 
                   2582:       self.close()
                   2583: 
                   2584:     }
1.629     www      2585: </script>
1.350     albertel 2586: INNERJS
                   2587: 
1.773     raeburn  2588:     my $start_page_msg_central =
1.351     albertel 2589:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   2590: 				       {'js_ready'  => 1,
                   2591: 					'only_body' => 1,
                   2592: 					'bgcolor'   =>'#FFFFFF',});
1.773     raeburn  2593:     my $end_page_msg_central =
1.350     albertel 2594: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   2595: 
1.219     www      2596:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 2597:     $docopen=~s/^document\.//;
1.773     raeburn  2598: 
1.736     damieng  2599:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  2600:                 comp => 'Compose Message for: ',
                   2601:                 incl => 'Include',
1.656     raeburn  2602:                 type => 'Type',
1.652     raeburn  2603:                 subj => 'Subject',
                   2604:                 mesa => 'Message',
                   2605:                 new  => 'New',
                   2606:                 save => 'Save',
                   2607:                 canc => 'Cancel',
                   2608:              );
1.736     damieng  2609:     &html_escape(\%html_js_lt);
                   2610:     &js_escape(\%html_js_lt);
1.597     wenzelju 2611:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       2612: 
1.44      ng       2613: //===================== Script to view submitted by ==================
                   2614:   function viewSubmitter(submitter) {
                   2615:     document.SCORE.refresh.value = "on";
                   2616:     document.SCORE.NCT.value = "1";
                   2617:     document.SCORE.unamedom0.value = submitter;
                   2618:     document.SCORE.submit();
                   2619:     return;
                   2620:   }
                   2621: 
                   2622: //====================== Script for composing message ==============
1.80      ng       2623:    // preload images
                   2624:    img1 = new Image();
                   2625:    img1.src = "$iconpath/mailbkgrd.gif";
                   2626:    img2 = new Image();
                   2627:    img2.src = "$iconpath/mailto.gif";
                   2628: 
1.44      ng       2629:   function msgCenter(msgform,usrctr,fullname) {
                   2630:     var Nmsg  = msgform.savemsgN.value;
                   2631:     savedMsgHeader(Nmsg,usrctr,fullname);
                   2632:     var subject = msgform.msgsub.value;
1.127     ng       2633:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       2634:     re = /msgsub/;
                   2635:     var shwsel = "";
                   2636:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       2637:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   2638:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       2639:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       2640: 	var testmsg = "savemsg"+i+",";
                   2641: 	re = new RegExp(testmsg,"g");
1.44      ng       2642: 	shwsel = "";
                   2643: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       2644: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       2645: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       2646: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   2647: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       2648:     }
1.125     ng       2649:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       2650:     shwsel = "";
                   2651:     re = /newmsg/;
                   2652:     if (re.test(msgchk)) { shwsel = "checked" }
                   2653:     newMsg(newmsg,shwsel);
                   2654:     msgTail(); 
                   2655:     return;
                   2656:   }
                   2657: 
1.123     ng       2658:   function checkEntities(strx) {
                   2659:     if (strx.length == 0) return strx;
                   2660:     var orgStr = ["&", "<", ">", '"']; 
                   2661:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   2662:     var counter = 0;
                   2663:     while (counter < 4) {
                   2664: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   2665: 	counter++;
                   2666:     }
                   2667:     return strx;
                   2668:   }
                   2669: 
                   2670:   function strReplace(strx, orgStr, newStr) {
                   2671:     return strx.split(orgStr).join(newStr);
                   2672:   }
                   2673: 
1.44      ng       2674:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       2675:     var height = 70*Nmsg+250;
1.44      ng       2676:     if (height > 600) {
                   2677: 	height = 600;
                   2678:     }
1.118     ng       2679:     var xpos = (screen.width-600)/2;
                   2680:     xpos = (xpos < 0) ? '0' : xpos;
                   2681:     var ypos = (screen.height-height)/2-30;
                   2682:     ypos = (ypos < 0) ? '0' : ypos;
                   2683: 
1.668     www      2684:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       2685:     pWin.focus();
                   2686:     pDoc = pWin.document;
1.219     www      2687:     pDoc.$docopen;
1.351     albertel 2688:     pDoc.write('$start_page_msg_central');
1.76      ng       2689: 
                   2690:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   2691:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  2692:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       2693: 
1.676     golterma 2694:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  2695:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       2696: }
                   2697:     function displaySubject(msg,shwsel) {
1.76      ng       2698:     pDoc = pWin.document;
1.676     golterma 2699:     pDoc.write("<tr>");
                   2700:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2701:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 2702:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       2703: }
                   2704: 
1.72      ng       2705:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       2706:     pDoc = pWin.document;
1.676     golterma 2707:     pDoc.write("<tr>");
                   2708:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 2709:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   2710:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2711: }
                   2712: 
                   2713:   function newMsg(newmsg,shwsel) {
1.76      ng       2714:     pDoc = pWin.document;
1.676     golterma 2715:     pDoc.write("<tr>");
                   2716:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2717:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 2718:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2719: }
                   2720: 
                   2721:   function msgTail() {
1.76      ng       2722:     pDoc = pWin.document;
1.676     golterma 2723:     //pDoc.write("<\\/table>");
1.465     albertel 2724:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  2725:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   2726:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 2727:     pDoc.write("<\\/form>");
1.351     albertel 2728:     pDoc.write('$end_page_msg_central');
1.128     ng       2729:     pDoc.close();
1.44      ng       2730: }
                   2731: 
1.773     raeburn  2732: SUBJAVASCRIPT
                   2733: }
                   2734: 
                   2735: #--- javascript for essay type problem --
                   2736: sub sub_page_kw_js {
                   2737:     my $request = shift;
                   2738: 
                   2739:     unless ($env{'form.compmsg'}) {
                   2740:         &commonJSfunctions($request);
                   2741:     }
                   2742: 
                   2743:     my $inner_js_highlight_central= (<<INNERJS);
                   2744: <script type="text/javascript">
                   2745:     function updateChoice(flag) {
                   2746:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   2747:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   2748:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   2749:       opener.document.SCORE.refresh.value = "on";
                   2750:       if (opener.document.SCORE.keywords.value!=""){
                   2751:          opener.document.SCORE.submit();
                   2752:       }
                   2753:       self.close()
                   2754:     }
                   2755: </script>
                   2756: INNERJS
                   2757: 
                   2758:     my $start_page_highlight_central =
                   2759:         &Apache::loncommon::start_page('Highlight Central',
                   2760:                                        $inner_js_highlight_central,
                   2761:                                        {'js_ready'  => 1,
                   2762:                                         'only_body' => 1,
                   2763:                                         'bgcolor'   =>'#FFFFFF',});
                   2764:     my $end_page_highlight_central =
                   2765:         &Apache::loncommon::end_page({'js_ready' => 1});
                   2766: 
                   2767:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   2768:     $docopen=~s/^document\.//;
                   2769: 
                   2770:     my %js_lt = &Apache::lonlocal::texthash(
                   2771:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   2772:                 plse => 'Please select a word or group of words from document and then click this link.',
                   2773:                 adds => 'Add selection to keyword list? Edit if desired.',
                   2774:                 col1 => 'red',
                   2775:                 col2 => 'green',
                   2776:                 col3 => 'blue',
                   2777:                 siz1 => 'normal',
                   2778:                 siz2 => '+1',
                   2779:                 siz3 => '+2',
                   2780:                 sty1 => 'normal',
                   2781:                 sty2 => 'italic',
                   2782:                 sty3 => 'bold',
                   2783:              );
                   2784:     my %html_js_lt = &Apache::lonlocal::texthash(
                   2785:                 save => 'Save',
                   2786:                 canc => 'Cancel',
                   2787:                 kehi => 'Keyword Highlight Options',
                   2788:                 txtc => 'Text Color',
                   2789:                 font => 'Font Size',
                   2790:                 fnst => 'Font Style',
                   2791:              );
                   2792:     &js_escape(\%js_lt);
                   2793:     &html_escape(\%html_js_lt);
                   2794:     &js_escape(\%html_js_lt);
                   2795:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   2796: 
                   2797: //===================== Show list of keywords ====================
                   2798:   function keywords(formname) {
                   2799:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   2800:     if (nret==null) return;
                   2801:     formname.keywords.value = nret;
                   2802: 
                   2803:     if (formname.keywords.value != "") {
                   2804:         formname.refresh.value = "on";
                   2805:         formname.submit();
                   2806:     }
                   2807:     return;
                   2808:   }
                   2809: 
                   2810: //===================== Script to add keyword(s) ==================
                   2811:   function getSel() {
                   2812:     if (document.getSelection) txt = document.getSelection();
                   2813:     else if (document.selection) txt = document.selection.createRange().text;
                   2814:     else return;
                   2815:     if (typeof(txt) != 'string') {
                   2816:         txt = String(txt);
                   2817:     }
                   2818:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   2819:     if (cleantxt=="") {
                   2820:         alert("$js_lt{'plse'}");
                   2821:         return;
                   2822:     }
                   2823:     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   2824:     if (nret==null) return;
                   2825:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   2826:     if (document.SCORE.keywords.value != "") {
                   2827:         document.SCORE.refresh.value = "on";
                   2828:         document.SCORE.submit();
                   2829:     }
                   2830:     return;
                   2831:   }
                   2832: 
1.44      ng       2833: //====================== Script for keyword highlight options ==============
                   2834:   function kwhighlight() {
                   2835:     var kwclr    = document.SCORE.kwclr.value;
                   2836:     var kwsize   = document.SCORE.kwsize.value;
                   2837:     var kwstyle  = document.SCORE.kwstyle.value;
                   2838:     var redsel = "";
                   2839:     var grnsel = "";
                   2840:     var blusel = "";
1.736     damieng  2841:     var txtcol1 = "$js_lt{'col1'}";
                   2842:     var txtcol2 = "$js_lt{'col2'}";
                   2843:     var txtcol3 = "$js_lt{'col3'}";
                   2844:     var txtsiz1 = "$js_lt{'siz1'}";
                   2845:     var txtsiz2 = "$js_lt{'siz2'}";
                   2846:     var txtsiz3 = "$js_lt{'siz3'}";
                   2847:     var txtsty1 = "$js_lt{'sty1'}";
                   2848:     var txtsty2 = "$js_lt{'sty2'}";
                   2849:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   2850:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   2851:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   2852:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       2853:     var sznsel = "";
                   2854:     var sz1sel = "";
                   2855:     var sz2sel = "";
1.718     bisitz   2856:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   2857:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   2858:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       2859:     var synsel = "";
                   2860:     var syisel = "";
                   2861:     var sybsel = "";
1.718     bisitz   2862:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   2863:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   2864:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       2865:     highlightCentral();
1.718     bisitz   2866:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   2867:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   2868:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       2869:     highlightend();
                   2870:     return;
                   2871:   }
                   2872: 
                   2873:   function highlightCentral() {
1.76      ng       2874: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       2875:     var xpos = (screen.width-400)/2;
                   2876:     xpos = (xpos < 0) ? '0' : xpos;
                   2877:     var ypos = (screen.height-330)/2-30;
                   2878:     ypos = (ypos < 0) ? '0' : ypos;
                   2879: 
1.206     albertel 2880:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       2881:     hwdWin.focus();
                   2882:     var hDoc = hwdWin.document;
1.219     www      2883:     hDoc.$docopen;
1.351     albertel 2884:     hDoc.write('$start_page_highlight_central');
1.76      ng       2885:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  2886:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       2887: 
1.718     bisitz   2888:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  2889:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       2890:   }
                   2891: 
                   2892:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       2893:     var hDoc = hwdWin.document;
1.718     bisitz   2894:     hDoc.write("<tr>");
1.76      ng       2895:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2896:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       2897:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2898:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       2899:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2900:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 2901:     hDoc.write("<\\/tr>");
1.44      ng       2902:   }
                   2903: 
                   2904:   function highlightend() { 
1.76      ng       2905:     var hDoc = hwdWin.document;
1.718     bisitz   2906:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  2907:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   2908:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 2909:     hDoc.write("<\\/form>");
1.351     albertel 2910:     hDoc.write('$end_page_highlight_central');
1.128     ng       2911:     hDoc.close();
1.44      ng       2912:   }
                   2913: 
                   2914: SUBJAVASCRIPT
                   2915: }
                   2916: 
1.349     albertel 2917: sub get_increment {
1.348     bowersj2 2918:     my $increment = $env{'form.increment'};
                   2919:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   2920:         $increment != .1) {
                   2921:         $increment = 1;
                   2922:     }
                   2923:     return $increment;
                   2924: }
                   2925: 
1.585     bisitz   2926: sub gradeBox_start {
                   2927:     return (
                   2928:         &Apache::loncommon::start_data_table()
                   2929:        .&Apache::loncommon::start_data_table_header_row()
                   2930:        .'<th>'.&mt('Part').'</th>'
                   2931:        .'<th>'.&mt('Points').'</th>'
                   2932:        .'<th>&nbsp;</th>'
                   2933:        .'<th>'.&mt('Assign Grade').'</th>'
                   2934:        .'<th>'.&mt('Weight').'</th>'
                   2935:        .'<th>'.&mt('Grade Status').'</th>'
                   2936:        .&Apache::loncommon::end_data_table_header_row()
                   2937:     );
                   2938: }
                   2939: 
                   2940: sub gradeBox_end {
                   2941:     return (
                   2942:         &Apache::loncommon::end_data_table()
                   2943:     );
                   2944: }
1.71      ng       2945: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   2946: sub gradeBox {
1.322     albertel 2947:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 2948:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2949: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2950:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2951:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2952:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2953:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2954:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2955: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   2956:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2957:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2958:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2959: 				       [$partid]);
                   2960:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2961:     if ($last_resets{$partid}) {
                   2962:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2963:     }
1.695     bisitz   2964:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2965:     my $ctr = 0;
1.348     bowersj2 2966:     my $thisweight = 0;
1.349     albertel 2967:     my $increment = &get_increment();
1.485     albertel 2968: 
                   2969:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2970:     while ($thisweight<=$wgt) {
1.532     bisitz   2971: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2972:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2973: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2974: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2975: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2976:         $thisweight += $increment;
1.71      ng       2977: 	$ctr++;
                   2978:     }
1.485     albertel 2979:     $radio.='</tr></table>';
                   2980: 
                   2981:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2982: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2983: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2984: 	$wgt.')" /></td>'."\n";
1.485     albertel 2985:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2986: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2987: 	' </td>'."\n";
                   2988:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2989: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2990:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2991: 	$line.='<option></option>'.
                   2992: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2993:     } else {
1.485     albertel 2994: 	$line.='<option selected="selected"></option>'.
                   2995: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2996:     }
1.485     albertel 2997:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2998: 
                   2999: 
                   3000:     $result .= 
1.695     bisitz   3001: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   3002:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   3003:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       3004:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   3005: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   3006: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  3007: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   3008:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   3009:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   3010:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   3011:         $aggtries.'" />'."\n";
1.582     raeburn  3012:     my $res_error;
                   3013:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   3014:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  3015:     if ($res_error) {
                   3016:         return &navmap_errormsg();
                   3017:     }
1.318     banghart 3018:     return $result;
                   3019: }
1.322     albertel 3020: 
                   3021: sub handback_box {
1.623     www      3022:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773     raeburn  3023:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   3024:     return unless ($numessay);
1.323     banghart 3025:     my (@respids);
1.652     raeburn  3026:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 3027:     foreach my $part_response_id (@part_response_id) {
                   3028:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 3029:         if ($part eq $partid) {
1.375     albertel 3030:             push(@respids,$resp);
1.323     banghart 3031:         }
                   3032:     }
1.318     banghart 3033:     my $result;
1.323     banghart 3034:     foreach my $respid (@respids) {
1.322     albertel 3035: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   3036: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3037: 	next if (!@$files);
1.654     raeburn  3038: 	my $file_counter = 0;
1.313     banghart 3039: 	foreach my $file (@$files) {
1.368     banghart 3040: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  3041:                 $file_counter++;
1.368     banghart 3042:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  3043:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 3044:     	        $file_disp = "$name.$ext";
                   3045:     	        $file = $file_path.$file_disp;
                   3046:     	        $result.=&mt('Return commented version of [_1] to student.',
                   3047:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   3048:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  3049:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 3050: 	    }
1.322     albertel 3051: 	}
1.654     raeburn  3052:         if ($file_counter) {
                   3053:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   3054:                        '<span class="LC_info">'.
                   3055:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   3056:         }
1.313     banghart 3057:     }
1.318     banghart 3058:     return $result;    
1.71      ng       3059: }
1.44      ng       3060: 
1.58      albertel 3061: sub show_problem {
1.382     albertel 3062:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 3063:     my $rendered;
1.382     albertel 3064:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 3065:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 3066:     if ($mode eq 'both' or $mode eq 'text') {
                   3067: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 3068: 						       $env{'request.course.id'},
                   3069: 						       undef,\%form);
1.144     albertel 3070:     }
1.58      albertel 3071:     if ($removeform) {
                   3072: 	$rendered=~s|<form(.*?)>||g;
                   3073: 	$rendered=~s|</form>||g;
1.374     albertel 3074: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 3075:     }
1.144     albertel 3076:     my $companswer;
                   3077:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 3078: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 3079: 	$companswer=
                   3080: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   3081: 						    $env{'request.course.id'},
                   3082: 						    %form);
1.144     albertel 3083:     }
1.58      albertel 3084:     if ($removeform) {
                   3085: 	$companswer=~s|<form(.*?)>||g;
                   3086: 	$companswer=~s|</form>||g;
1.144     albertel 3087: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 3088:     }
1.671     raeburn  3089:     my $renderheading = &mt('View of the problem');
                   3090:     my $answerheading = &mt('Correct answer');
                   3091:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   3092:         my $stu_fullname = $env{'form.fullname'};
                   3093:         if ($stu_fullname eq '') {
                   3094:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3095:         }
                   3096:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   3097:         if ($forwhom ne '') {
                   3098:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   3099:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   3100:         }
                   3101:     }
1.468     albertel 3102:     $rendered=
1.588     bisitz   3103:         '<div class="LC_Box">'
1.671     raeburn  3104:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   3105:        .$rendered
                   3106:        .'</div>';
1.468     albertel 3107:     $companswer=
1.588     bisitz   3108:         '<div class="LC_Box">'
1.671     raeburn  3109:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   3110:        .$companswer
                   3111:        .'</div>';
1.468     albertel 3112:     my $result;
1.144     albertel 3113:     if ($mode eq 'both') {
1.588     bisitz   3114:         $result=$rendered.$companswer;
1.144     albertel 3115:     } elsif ($mode eq 'text') {
1.588     bisitz   3116:         $result=$rendered;
1.144     albertel 3117:     } elsif ($mode eq 'answer') {
1.588     bisitz   3118:         $result=$companswer;
1.144     albertel 3119:     }
1.71      ng       3120:     return $result;
1.58      albertel 3121: }
1.397     albertel 3122: 
1.396     banghart 3123: sub files_exist {
                   3124:     my ($r, $symb) = @_;
                   3125:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   3126:     foreach my $student (@students) {
                   3127:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 3128:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3129: 					      $udom,$uname);
1.792     raeburn  3130:         my ($string)= &get_last_submission(\%record);
1.397     albertel 3131:         foreach my $submission (@$string) {
                   3132:             my ($partid,$respid) =
                   3133: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3134:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   3135: 					   \%record);
                   3136:             return 1 if (@$files);
1.396     banghart 3137:         }
                   3138:     }
1.397     albertel 3139:     return 0;
1.396     banghart 3140: }
1.397     albertel 3141: 
1.394     banghart 3142: sub download_all_link {
                   3143:     my ($r,$symb) = @_;
1.621     www      3144:     unless (&files_exist($r, $symb)) {
1.766     raeburn  3145:         $r->print(&mt('There are currently no submitted documents.'));
                   3146:         return;
1.621     www      3147:     }
1.395     albertel 3148:     my $all_students = 
                   3149: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   3150: 
                   3151:     my $parts =
                   3152: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   3153: 
1.394     banghart 3154:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  3155:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   3156:                              'cgi.'.$identifier.'.symb' => $symb,
                   3157:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 3158:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   3159: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      3160:     return;
                   3161: }
                   3162: 
                   3163: sub submit_download_link {
                   3164:     my ($request,$symb) = @_;
                   3165:     if (!$symb) { return ''; }
1.750     raeburn  3166:     my $res_error;
1.773     raeburn  3167:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   3168:         &response_type($symb,\$res_error);
                   3169:     if ($res_error) {
                   3170:         $request->print(&mt('An error occurred retrieving response types'));
                   3171:         return;
                   3172:     }
                   3173:     unless ($numessay) {
                   3174:         $request->print(&mt('No essayresponse items found'));
                   3175:         return;
1.750     raeburn  3176:     }
1.773     raeburn  3177:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3178:     if (@chosenparts) {
                   3179:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   3180:                                           undef,undef,1));
1.750     raeburn  3181:     }
1.773     raeburn  3182:     if ($numessay) {
1.750     raeburn  3183:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   3184:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3185:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   3186:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   3187:         if (ref($fullname) eq 'HASH') {
                   3188:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   3189:             if (@students) {
                   3190:                 @{$env{'form.stuinfo'}} = @students;
1.773     raeburn  3191:                 if ($numdropbox) {
1.750     raeburn  3192:                     &download_all_link($request,$symb);
1.773     raeburn  3193:                 } else {
                   3194:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  3195:                 }
1.773     raeburn  3196: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  3197: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   3198:             } else {
                   3199:                 $request->print(&mt('No students match the criteria you selected'));
                   3200:             }
                   3201:         } else {
                   3202:             $request->print(&mt('Could not retrieve student information'));
                   3203:         }
                   3204:     } else {
                   3205:         $request->print(&mt('No essayresponse items found'));
                   3206:     }
                   3207:     return;
1.394     banghart 3208: }
1.395     albertel 3209: 
1.432     banghart 3210: sub build_section_inputs {
                   3211:     my $section_inputs;
                   3212:     if ($env{'form.section'} eq '') {
                   3213:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   3214:     } else {
                   3215:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 3216:         foreach my $section (@sections) {
1.432     banghart 3217:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   3218:         }
                   3219:     }
                   3220:     return $section_inputs;
                   3221: }
                   3222: 
1.44      ng       3223: # --------------------------- show submissions of a student, option to grade 
                   3224: sub submission {
1.773     raeburn  3225:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 3226:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   3227:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   3228:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3229:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      3230: 
1.324     albertel 3231:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773     raeburn  3232:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  3233:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  3234:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 3235: 
                   3236:     if (!&canview($usec)) {
1.712     bisitz   3237:         $request->print(
                   3238:             '<span class="LC_warning">'.
1.713     bisitz   3239:             &mt('Unable to view requested student.').
1.712     bisitz   3240:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3241:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3242:             '</span>');
1.104     albertel 3243: 	return;
                   3244:     }
                   3245: 
1.773     raeburn  3246:     my $res_error;
                   3247:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   3248:         &response_type($symb,\$res_error);
                   3249:     if ($res_error) {
                   3250:         $request->print(&navmap_errormsg());
                   3251:         return;
                   3252:     }
                   3253: 
1.257     albertel 3254:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  3255:     unless ($is_tool) { 
                   3256:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   3257:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   3258:     }
1.773     raeburn  3259:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   3260:         $env{'form.compmsg'} = 1;
                   3261:     }
1.257     albertel 3262:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 3263:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   3264: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       3265: 	'/check.gif" height="16" border="0" />';
1.41      ng       3266: 
                   3267:     # header info
                   3268:     if ($counter == 0) {
1.773     raeburn  3269:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3270:         if (@chosenparts) {
                   3271:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   3272:         } elsif ($divforres) {
                   3273:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   3274:         } else {
                   3275:             $request->print('<br clear="all" />');
                   3276:         }
1.41      ng       3277: 	&sub_page_js($request);
1.773     raeburn  3278:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   3279: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       3280: 
1.44      ng       3281: 	# option to display problem, only once else it cause problems 
                   3282:         # with the form later since the problem has a form.
1.257     albertel 3283: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 3284: 	    my $mode;
1.257     albertel 3285: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 3286: 		$mode='both';
1.257     albertel 3287: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 3288: 		$mode='text';
1.257     albertel 3289: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 3290: 		$mode='answer';
                   3291: 	    }
1.329     albertel 3292: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 3293: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       3294: 	}
1.441     www      3295: 
1.41      ng       3296: 	my %keyhash = ();
1.773     raeburn  3297: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       3298: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 3299: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   3300: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773     raeburn  3301: 	}
                   3302: 	# kwclr is the only variable that is guaranteed not to be blank
                   3303: 	# if this subroutine has been called once.
                   3304: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 3305: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3306: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   3307: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   3308: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   3309: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773     raeburn  3310: 	}
                   3311: 	if ($env{'form.compmsg'}) {
                   3312: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      3313: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 3314: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       3315: 	}
1.773     raeburn  3316: 
1.257     albertel 3317: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 3318: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 3319: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       3320: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 3321: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       3322: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       3323: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       3324: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   3325: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 3326: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3327: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   3328: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   3329: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773     raeburn  3330: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 3331: 			&build_section_inputs().
1.326     albertel 3332: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       3333: 			'<input type="hidden" name="NCT"'.
1.257     albertel 3334: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773     raeburn  3335: 	if ($env{'form.compmsg'}) {
                   3336: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   3337: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   3338: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   3339: 	}
                   3340: 	if ($numessay) {
1.257     albertel 3341: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   3342: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   3343: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773     raeburn  3344: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       3345: 	}
1.773     raeburn  3346: 
1.41      ng       3347: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 3348: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       3349: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       3350: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 3351: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       3352: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       3353: 		'" />'."\n".
                   3354: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       3355: 	    $cts++;
                   3356: 	}
                   3357: 	$request->print($prnmsg);
1.32      ng       3358: 
1.773     raeburn  3359: 	if ($numessay) {
1.652     raeburn  3360: 
                   3361:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   3362:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  3363:                           keyw => 'Keyword Options',
1.655     raeburn  3364:                           list => 'List',
1.652     raeburn  3365:                           past => 'Paste Selection to List',
1.661     www      3366:                           high => 'Highlight Attribute',
1.773     raeburn  3367:                      );
1.88      www      3368: #
                   3369: # Print out the keyword options line
                   3370: #
1.718     bisitz   3371: 	    $request->print(
                   3372:                 '<div class="LC_columnSection">'
                   3373:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   3374:                .&Apache::lonhtmlcommon::funclist_from_array(
                   3375:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   3376:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   3377:  class="page">'.$lt{'past'}.'</a>',
                   3378:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   3379:                     {legend => $lt{'keyw'}})
                   3380:                .'</fieldset></div>'
                   3381:             );
                   3382: 
1.88      www      3383: #
                   3384: # Load the other essays for similarity check
                   3385: #
1.753     raeburn  3386:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   3387:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3388:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3389:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3390:                 if ($cdom ne '' && $cnum ne '') {
                   3391:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   3392:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   3393:                         my $apath = $1.'_'.$id;
                   3394:                         $apath=~s/\W/\_/gs;
                   3395:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   3396:                     }
                   3397:                 }
                   3398:             } else {
                   3399: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   3400: 	        $apath=&escape($apath);
                   3401: 	        $apath=~s/\W/\_/gs;
                   3402:                 &init_old_essays($symb,$apath,$adom,$aname);
                   3403:             }
1.41      ng       3404:         }
                   3405:     }
1.44      ng       3406: 
1.441     www      3407: # This is where output for one specific student would start
1.592     bisitz   3408:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   3409:     $request->print(
                   3410:         "\n\n"
                   3411:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   3412:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   3413:        ."\n"
                   3414:     );
1.441     www      3415: 
1.592     bisitz   3416:     # Show additional functions if allowed
                   3417:     if ($perm{'vgr'}) {
                   3418:         $request->print(
                   3419:             &Apache::loncommon::track_student_link(
1.708     bisitz   3420:                 'View recent activity',
1.592     bisitz   3421:                 $uname,$udom,'check')
                   3422:            .' '
                   3423:         );
                   3424:     }
                   3425:     if ($perm{'opa'}) {
                   3426:         $request->print(
                   3427:             &Apache::loncommon::pprmlink(
                   3428:                 &mt('Set/Change parameters'),
                   3429:                 $uname,$udom,$symb,'check'));
                   3430:     }
                   3431: 
                   3432:     # Show Problem
1.257     albertel 3433:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 3434: 	my $mode;
1.257     albertel 3435: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 3436: 	    $mode='both';
1.257     albertel 3437: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 3438: 	    $mode='text';
1.257     albertel 3439: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 3440: 	    $mode='answer';
                   3441: 	}
1.329     albertel 3442: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 3443: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 3444:     }
1.144     albertel 3445: 
1.257     albertel 3446:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       3447: 
1.44      ng       3448:     # Display student info
1.41      ng       3449:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   3450: 
1.745     raeburn  3451:     my $boxtitle = &mt('Submissions');
                   3452:     if ($is_tool) {
                   3453:         $boxtitle = &mt('Transactions')
                   3454:     }
1.590     bisitz   3455:     my $result='<div class="LC_Box">'
1.745     raeburn  3456:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       3457:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   3458:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773     raeburn  3459:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   3460:         $result.='<p class="LC_info">'
                   3461:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   3462:                 ."</p>\n";
1.469     albertel 3463:     }
                   3464: 
1.773     raeburn  3465:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 3466:     my $fullname;
                   3467:     my $col_fullnames = [];
1.773     raeburn  3468:     if ($numessay) {
1.464     albertel 3469: 	(my $sub_result,$fullname,$col_fullnames)=
                   3470: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   3471: 				 $counter);
                   3472: 	$result.=$sub_result;
1.41      ng       3473:     }
1.44      ng       3474:     $request->print($result."\n");
1.773     raeburn  3475: 
1.44      ng       3476:     # print student answer/submission
1.773     raeburn  3477:     # Options are (1) Last submission only
                   3478:     #             (2) Last submission (with detailed information for that submission)
                   3479:     #             (3) All transactions (by date)
                   3480:     #             (4) The whole record (with detailed information for all transactions)
                   3481: 
1.793     raeburn  3482:     my ($lastsubonly,$partinfo) =
                   3483:         &show_last_submission($uname,$udom,$symb,$essayurl,$responseType,$env{'form.lastSub'},
                   3484:                               $is_tool,$fullname,\%record,\%coursedesc_by_cid);
                   3485:     $request->print($partinfo);
                   3486:     $request->print($lastsubonly);
                   3487: 
                   3488:     if ($env{'form.lastSub'} eq 'datesub') {
                   3489:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3490: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
                   3491:     }
                   3492:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   3493:         my $identifier = (&canmodify($usec)? $counter : '');
                   3494:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
                   3495: 								 $env{'request.course.id'},
                   3496: 								 $last,'.submission',
                   3497: 								 'Apache::grades::keywords_highlight',
                   3498:                                                                  $usec,$identifier));
                   3499:     }
                   3500:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   3501: 	.$udom.'" />'."\n");
                   3502:     # return if view submission with no grading option
                   3503:     if (!&canmodify($usec)) {
                   3504: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   3505: 	return;
                   3506:     } else {
                   3507: 	$request->print('</div>'."\n");
                   3508:     }
                   3509: 
                   3510:     # grading message center
                   3511: 
                   3512:     if ($env{'form.compmsg'}) {
                   3513:         my $result='<div class="LC_Box">'.
                   3514:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   3515:                    '<div class="LC_grade_message_center_body">';
                   3516:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   3517:         my $msgfor = $givenn.' '.$lastname;
                   3518:         if (scalar(@$col_fullnames) > 0) {
                   3519:             my $lastone = pop(@$col_fullnames);
                   3520:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   3521:         }
                   3522:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   3523:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   3524:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   3525:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   3526:                  ',\''.$msgfor.'\');" target="_self">'.
                   3527:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   3528:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   3529:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   3530:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   3531:                  '<br />&nbsp;('.
                   3532:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   3533:                  '</div></div>';
                   3534:         $request->print($result);
                   3535:     }
                   3536: 
                   3537:     my %seen = ();
                   3538:     my @partlist;
                   3539:     my @gradePartRespid;
                   3540:     my @part_response_id;
                   3541:     if ($is_tool) {
                   3542:         @part_response_id = ([0,'']);
                   3543:     } else {
                   3544:         @part_response_id = &flatten_responseType($responseType);
                   3545:     }
                   3546:     $request->print(
                   3547:         '<div class="LC_Box">'
                   3548:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
                   3549:     );
                   3550:     $request->print(&gradeBox_start());
                   3551:     foreach my $part_response_id (@part_response_id) {
                   3552:     	my ($partid,$respid) = @{ $part_response_id };
                   3553: 	my $part_resp = join('_',@{ $part_response_id });
                   3554: 	next if ($seen{$partid} > 0);
                   3555: 	$seen{$partid}++;
                   3556: 	push(@partlist,$partid);
                   3557: 	push(@gradePartRespid,$partid.'.'.$respid);
                   3558: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
                   3559:     }
                   3560:     $request->print(&gradeBox_end()); # </div>
                   3561:     $request->print('</div>');
                   3562: 
                   3563:     $request->print('<div class="LC_grade_info_links">');
                   3564:     $request->print('</div>');
                   3565: 
                   3566:     $result='<input type="hidden" name="partlist'.$counter.
                   3567: 	'" value="'.(join ":",@partlist).'" />'."\n";
                   3568:     $result.='<input type="hidden" name="gradePartRespid'.
                   3569: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
                   3570:     my $ctr = 0;
                   3571:     while ($ctr < scalar(@partlist)) {
                   3572: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   3573: 	    $partlist[$ctr].'" />'."\n";
                   3574: 	$ctr++;
                   3575:     }
                   3576:     $request->print($result.''."\n");
                   3577: 
                   3578: # Done with printing info for one student
                   3579: 
                   3580:     $request->print('</div>');#LC_grade_show_user
                   3581: 
                   3582: 
                   3583:     # print end of form
                   3584:     if ($counter == $total) {
                   3585:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
                   3586: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
                   3587: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
                   3588: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
                   3589: 	my $ntstu ='<select name="NTSTU">'.
                   3590: 	    '<option>1</option><option>2</option>'.
                   3591: 	    '<option>3</option><option>5</option>'.
                   3592: 	    '<option>7</option><option>10</option></select>'."\n";
                   3593: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
                   3594: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
                   3595:         $endform.=&mt('[_1]student(s)',$ntstu);
                   3596: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
                   3597: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
                   3598: 	    '<input type="button" value="'.&mt('Next').'" '.
                   3599: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
                   3600:         $endform.='<span class="LC_warning">'.
                   3601:                   &mt('(Next and Previous (student) do not save the scores.)').
                   3602:                   '</span>'."\n" ;
                   3603:         $endform.="<input type='hidden' value='".&get_increment().
                   3604:             "' name='increment' />";
                   3605: 	$endform.='</td></tr></table></form>';
                   3606: 	$request->print($endform);
                   3607:     }
                   3608:     return '';
                   3609: }
                   3610: 
                   3611: sub show_last_submission {
                   3612:     my ($uname,$udom,$symb,$essayurl,$responseType,$viewtype,$is_tool,$fullname,
                   3613:         $record,$coursedesc_by_cid) = @_;
1.792     raeburn  3614:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
1.793     raeburn  3615:         &get_last_submission($record,$is_tool);
1.468     albertel 3616: 
1.793     raeburn  3617:     my ($lastsubonly,$partinfo);
1.792     raeburn  3618:     if ($timestamp eq '') {
1.793     raeburn  3619:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>';
1.745     raeburn  3620:     } elsif ($is_tool) {
                   3621:         $lastsubonly =
                   3622:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3623:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$timestamp."</div>\n";
1.702     kruse    3624:     } else {
1.792     raeburn  3625:         my ($shownsubmdate,$showngradedate);
                   3626:         if ($lastsubmittime && $lastgradetime) {
                   3627:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
                   3628:             if ($lastgradetime > $lastsubmittime) {
                   3629:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
                   3630:              }
                   3631:         } else {
                   3632:             $shownsubmdate = $timestamp;
                   3633:         }
1.702     kruse    3634:         $lastsubonly =
                   3635:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3636:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
                   3637:         if ($showngradedate) {
                   3638:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
                   3639:         }
1.702     kruse    3640: 
1.793     raeburn  3641:         my %seenparts;
                   3642:         my @part_response_id = &flatten_responseType($responseType);
                   3643:         foreach my $part (@part_response_id) {
                   3644:             my ($partid,$respid) = @{ $part };
                   3645:             my $display_part=&get_display_part($partid,$symb);
                   3646:             if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   3647:                 if (exists($seenparts{$partid})) { next; }
                   3648:                 $seenparts{$partid}=1;
                   3649:                 $partinfo .=
1.702     kruse    3650:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3651:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   3652:                                '<a href="javascript:viewSubmitter(\''.
                   3653:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   3654:                                '\');" target="_self">'.
                   3655:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
1.793     raeburn  3656:                     '<br />';
                   3657:                 next;
                   3658:             }
                   3659:             my $responsetype = $responseType->{$partid}->{$respid};
                   3660:             if (!exists($record->{"resource.$partid.$respid.submission"})) {
1.702     kruse    3661:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   3662:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3663:                     ' <span class="LC_internal_info">'.
                   3664:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   3665:                     '</span>&nbsp; &nbsp;'.
1.793     raeburn  3666:                     '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   3667:                 next;
                   3668:             }
                   3669:             foreach my $submission (@$string) {
                   3670:                 my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3671:                 if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   3672:                 my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   3673:                 # Similarity check
1.702     kruse    3674:                 my $similar='';
                   3675:                 my ($type,$trial,$rndseed);
                   3676:                 if ($hide eq 'rand') {
                   3677:                     $type = 'randomizetry';
1.793     raeburn  3678:                     $trial = $record->{"resource.$partid.tries"};
                   3679:                     $rndseed = $record->{"resource.$partid.rndseed"};
1.702     kruse    3680:                 }
1.793     raeburn  3681:                 if ($env{'form.checkPlag'}) {
                   3682:                     my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   3683:                     &most_similar($uname,$udom,$symb,$subval);
                   3684:                     if ($osim) {
                   3685:                         $osim=int($osim*100.0);
1.702     kruse    3686:                         if ($hide eq 'anon') {
                   3687:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   3688:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   3689:                         } else {
1.793     raeburn  3690:                             $similar='<hr />';
1.753     raeburn  3691:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3692:                                 $similar .= '<h3><span class="LC_warning">'.
                   3693:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   3694:                                                 $osim,
                   3695:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3696:                                             '</span></h3>';
                   3697:                             } else {
                   3698:                                 my %old_course_desc;
                   3699:                                 if ($ocrsid ne '') {
1.793     raeburn  3700:                                     if (ref($coursedesc_by_cid->{$ocrsid}) eq 'HASH') {
                   3701:                                         %old_course_desc = %{$coursedesc_by_cid->{$ocrsid}};
1.753     raeburn  3702:                                     } else {
                   3703:                                         my $args;
                   3704:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   3705:                                             $args = {'one_time' => 1};
                   3706:                                         }
                   3707:                                         %old_course_desc =
                   3708:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
1.793     raeburn  3709:                                         $coursedesc_by_cid->{$ocrsid} = \%old_course_desc;
1.753     raeburn  3710:                                     }
                   3711:                                     $similar .=
                   3712:                                         '<h3><span class="LC_warning">'.
                   3713:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   3714:                                             $osim,
                   3715:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   3716:                                             $old_course_desc{'description'},
                   3717:                                             $old_course_desc{'num'},
                   3718:                                             $old_course_desc{'domain'}).
                   3719:                                         '</span></h3>';
                   3720:                                 } else {
                   3721:                                     $similar .=
                   3722:                                         '<h3><span class="LC_warning">'.
                   3723:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   3724:                                             $osim,
                   3725:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3726:                                         '</span></h3>';
                   3727:                                 }
                   3728:                             }
                   3729:                             $similar .= '<blockquote><i>'.
                   3730:                                         &keywords_highlight($oessay).
                   3731:                                         '</i></blockquote><hr />';
1.702     kruse    3732:                         }
1.793     raeburn  3733:                     }
                   3734:                 }
                   3735:                 my $order=&get_order($partid,$respid,$symb,$uname,$udom,
1.702     kruse    3736:                                      undef,$type,$trial,$rndseed);
1.793     raeburn  3737:                 if (($viewtype eq 'lastonly') ||
                   3738:                     ($viewtype eq 'datesub')  ||
                   3739:                     ($viewtype =~ /^(last|all)$/)) {
                   3740:                     my $display_part=&get_display_part($partid,$symb);
1.702     kruse    3741:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   3742:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3743:                         ' <span class="LC_internal_info">'.
                   3744:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   3745:                         '</span>&nbsp; &nbsp;';
1.793     raeburn  3746:                     my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3747:                     if (@$files) {
1.702     kruse    3748:                         if ($hide eq 'anon') {
                   3749:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   3750:                         } else {
                   3751:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   3752:                                         .'<br /><span class="LC_warning">';
                   3753:                             if(@$files == 1) {
                   3754:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  3755:                             } else {
1.702     kruse    3756:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   3757:                             }
1.774     raeburn  3758:                             $lastsubonly .= '</span>';
1.702     kruse    3759:                             foreach my $file (@$files) {
                   3760:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   3761:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  3762:                             }
                   3763:                         }
1.793     raeburn  3764:                         $lastsubonly.='<br />';
1.702     kruse    3765:                     }
                   3766:                     if ($hide eq 'anon') {
1.793     raeburn  3767:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
1.702     kruse    3768:                     } else {
1.774     raeburn  3769:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  3770:                         if ($draft) {
                   3771:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   3772:                         }
                   3773:                         $subval =
1.793     raeburn  3774:                             &cleanRecord($subval,$responsetype,$symb,$partid,
                   3775:                                          $respid,$record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  3776:                         if ($responsetype eq 'essay') {
                   3777:                             $subval =~ s{\n}{<br />}g;
                   3778:                         }
                   3779:                         $lastsubonly.=$subval."\n";
1.702     kruse    3780:                     }
1.774     raeburn  3781:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.793     raeburn  3782:                     $lastsubonly.='</div>';
                   3783:                 }
1.702     kruse    3784:             }
1.773     raeburn  3785:         }
1.793     raeburn  3786:         $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.118     ng       3787:     }
1.793     raeburn  3788:     return ($lastsubonly,$partinfo);
1.38      ng       3789: }
                   3790: 
1.464     albertel 3791: sub check_collaborators {
                   3792:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   3793:     my ($result,@col_fullnames);
                   3794:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   3795:     foreach my $part (keys(%$handgrade)) {
                   3796: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   3797: 					'.maxcollaborators',
                   3798: 					$symb,$udom,$uname);
                   3799: 	next if ($ncol <= 0);
                   3800: 	$part =~ s/\_/\./g;
                   3801: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   3802: 	my (@good_collaborators, @bad_collaborators);
                   3803: 	foreach my $possible_collaborator
1.630     www      3804: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 3805: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   3806: 	    next if ($possible_collaborator eq '');
1.631     www      3807: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 3808: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   3809: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   3810: 	    # Doing this grep allows 'fuzzy' specification
                   3811: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   3812: 			       keys(%$classlist));
                   3813: 	    if (! scalar(@matches)) {
                   3814: 		push(@bad_collaborators, $possible_collaborator);
                   3815: 	    } else {
                   3816: 		push(@good_collaborators, @matches);
                   3817: 	    }
                   3818: 	}
                   3819: 	if (scalar(@good_collaborators) != 0) {
1.630     www      3820: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 3821: 	    foreach my $name (@good_collaborators) {
                   3822: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   3823: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      3824: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 3825: 	    }
1.630     www      3826: 	    $result.='</ol><br />'."\n";
1.466     albertel 3827: 	    my ($part)=split(/\./,$part);
1.464     albertel 3828: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   3829: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   3830: 		"\n";
                   3831: 	}
                   3832: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 3833: 	    $result.='<div class="LC_warning">';
1.464     albertel 3834: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   3835: 	    $result .= '</div>';
                   3836: 	}         
                   3837: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 3838: 	    $result .= '<div class="LC_warning">';
1.464     albertel 3839: 	    $result .= &mt('This student has submitted too many '.
                   3840: 		'collaborators.  Maximum is [_1].',$ncol);
                   3841: 	    $result .= '</div>';
                   3842: 	}
                   3843:     }
                   3844:     return ($result,$fullname,\@col_fullnames);
                   3845: }
                   3846: 
1.44      ng       3847: #--- Retrieve the last submission for all the parts
1.38      ng       3848: sub get_last_submission {
1.745     raeburn  3849:     my ($returnhash,$is_tool)=@_;
1.792     raeburn  3850:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
1.119     ng       3851:     if ($$returnhash{'version'}) {
1.46      ng       3852: 	my %lasthash=();
1.792     raeburn  3853:         my %prevsolved=();
                   3854:         my %solved=();
                   3855: 	my $version;
1.119     ng       3856: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.792     raeburn  3857:             my %handgraded = ();
1.397     albertel 3858: 	    foreach my $key (sort(split(/\:/,
                   3859: 					$$returnhash{$version.':keys'}))) {
                   3860: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
1.792     raeburn  3861:                 if ($key =~ /\.([^.]+)\.regrader$/) {
                   3862:                     $handgraded{$1} = 1;
                   3863:                 } elsif ($key =~ /\.portfiles$/) {
                   3864:                     if (($$returnhash{$version.':'.$key} ne '') &&
                   3865:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
                   3866:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3867:                     }
                   3868:                 } elsif ($key =~ /\.submission$/) {
                   3869:                     if ($$returnhash{$version.':'.$key} ne '') {
                   3870:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3871:                     }
                   3872:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
                   3873:                     $prevsolved{$1} = $solved{$1};
                   3874:                     $solved{$1} = $lasthash{$key};
                   3875:                 }
                   3876:             }
                   3877:             foreach my $partid (keys(%handgraded)) {
                   3878:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
                   3879:                     (($solved{$partid} eq 'incorrect_by_override') ||
                   3880:                      ($solved{$partid} eq 'correct_by_override'))) {
                   3881:                     $lastgradetime = $$returnhash{$version.':timestamp'};
                   3882:                 }
                   3883:                 if ($solved{$partid} ne '') {
                   3884:                     $prevsolved{$partid} = $solved{$partid};
                   3885:                 }
1.46      ng       3886: 	    }
                   3887: 	}
1.795     raeburn  3888: #
                   3889: # Timestamp is for last transaction for this resource, which does not
                   3890: # necessarily correspond to the time of last submission for problem (or part).
                   3891: #
                   3892:         if ($lasthash{'timestamp'} ne '') {
                   3893:             $timestamp = &Apache::lonlocal::locallocaltime($lasthash{'timestamp'});
                   3894:         }
1.640     raeburn  3895:         my (%typeparts,%randombytry);
1.596     raeburn  3896:         my $showsurv = 
                   3897:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   3898:         foreach my $key (sort(keys(%lasthash))) {
                   3899:             if ($key =~ /\.type$/) {
                   3900:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  3901:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   3902:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  3903:                     my ($ign,@parts) = split(/\./,$key);
                   3904:                     pop(@parts);
1.641     raeburn  3905:                     my $id = join('.',@parts);
1.640     raeburn  3906:                     if ($lasthash{$key} eq 'randomizetry') {
                   3907:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   3908:                     } else {
                   3909:                         unless ($showsurv) {
                   3910:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   3911:                         }
1.596     raeburn  3912:                     }
                   3913:                     delete($lasthash{$key});
                   3914:                 }
                   3915:             }
                   3916:         }
                   3917:         my @hidden = keys(%typeparts);
1.640     raeburn  3918:         my @randomize = keys(%randombytry);
1.397     albertel 3919: 	foreach my $key (keys(%lasthash)) {
                   3920: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  3921:             my $hide;
                   3922:             if (@hidden) {
                   3923:                 foreach my $id (@hidden) {
                   3924:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  3925:                         $hide = 'anon';
1.596     raeburn  3926:                         last;
                   3927:                     }
                   3928:                 }
                   3929:             }
1.640     raeburn  3930:             unless ($hide) {
                   3931:                 if (@randomize) {
1.732     raeburn  3932:                     foreach my $id (@randomize) {
1.640     raeburn  3933:                         if ($key =~ /^\Q$id\E/) {
                   3934:                             $hide = 'rand';
                   3935:                             last;
                   3936:                         }
                   3937:                     }
                   3938:                 }
                   3939:             }
1.397     albertel 3940: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  3941: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   3942:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   3943:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   3944:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       3945: 	}
                   3946:     }
1.397     albertel 3947:     if (!@string) {
1.745     raeburn  3948:         my $msg;
                   3949:         if ($is_tool) {
1.747     raeburn  3950:             $msg = &mt('No grade passed back.');
1.745     raeburn  3951:         } else {
                   3952:             $msg = &mt('Nothing submitted - no attempts.');
                   3953:         }
1.397     albertel 3954: 	$string[0] =
1.745     raeburn  3955: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 3956:     }
1.792     raeburn  3957:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       3958: }
1.35      ng       3959: 
1.44      ng       3960: #--- High light keywords, with style choosen by user.
1.38      ng       3961: sub keywords_highlight {
1.44      ng       3962:     my $string    = shift;
1.257     albertel 3963:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   3964:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       3965:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 3966:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 3967:     foreach my $keyword (@keylist) {
                   3968: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       3969:     }
                   3970:     return $string;
1.38      ng       3971: }
1.36      ng       3972: 
1.671     raeburn  3973: # For Tasks provide a mechanism to display previous version for one specific student
                   3974: 
                   3975: sub show_previous_task_version {
                   3976:     my ($request,$symb) = @_;
                   3977:     if ($symb eq '') {
1.717     bisitz   3978:         $request->print(
                   3979:             '<span class="LC_error">'.
                   3980:             &mt('Unable to handle ambiguous references.').
                   3981:             '</span>');
1.671     raeburn  3982:         return '';
                   3983:     }
                   3984:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3985:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3986:     if (!&canview($usec)) {
1.712     bisitz   3987:         $request->print(
                   3988:             '<span class="LC_warning">'.
1.713     bisitz   3989:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   3990:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3991:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3992:             '</span>');
1.671     raeburn  3993:         return;
                   3994:     }
                   3995:     my $mode = 'both';
                   3996:     my $isTask = ($symb =~/\.task$/);
                   3997:     if ($isTask) {
                   3998:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   3999:             if ($env{'form.fullname'} eq '') {
                   4000:                 $env{'form.fullname'} =
                   4001:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   4002:             }
                   4003:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   4004:             $request->print("\n\n".
                   4005:                             '<div class="LC_grade_show_user">'.
                   4006:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   4007:                             '</h2>'."\n");
                   4008:             &Apache::lonxml::clear_problem_counter();
                   4009:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   4010:                             {'previousversion' => $env{'form.previousversion'} }));
                   4011:             $request->print("\n</div>");
                   4012:         }
                   4013:     }
                   4014:     return;
                   4015: }
                   4016: 
                   4017: sub choose_task_version_form {
                   4018:     my ($symb,$uname,$udom,$nomenu) = @_;
                   4019:     my $isTask = ($symb =~/\.task$/);
                   4020:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   4021:     if ($isTask) {
                   4022:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4023:                                               $udom,$uname);
                   4024:         if (($record{'resource.0.version'} eq '') ||
                   4025:             ($record{'resource.0.version'} < 2)) {
                   4026:             return ($record{'resource.0.version'},
                   4027:                     $record{'resource.0.version'},$result,$js);
                   4028:         } else {
                   4029:             $current = $record{'resource.0.version'};
                   4030:         }
                   4031:         if ($env{'form.previousversion'}) {
                   4032:             $displayed = $env{'form.previousversion'};
                   4033:             $rowtitle = &mt('Choose another version:')
                   4034:         } else {
                   4035:             $displayed = $current;
                   4036:             $rowtitle = &mt('Show earlier version:');
                   4037:         }
                   4038:         $result = '<div class="LC_left_float">';
                   4039:         my $list;
                   4040:         my $numversions = 0;
                   4041:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   4042:             if ($i == $current) {
                   4043:                 if (!$env{'form.previousversion'} || $nomenu) {
                   4044:                     next;
                   4045:                 } else {
                   4046:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   4047:                     $numversions ++;
                   4048:                 }
                   4049:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   4050:                 unless ($i == $env{'form.previousversion'}) {
                   4051:                     $numversions ++;
                   4052:                 }
                   4053:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   4054:             }
                   4055:         }
                   4056:         if ($numversions) {
                   4057:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   4058:             $result .=
                   4059:                 '<form name="getprev" method="post" action=""'.
                   4060:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   4061:                 &Apache::loncommon::start_data_table().
                   4062:                 &Apache::loncommon::start_data_table_row().
                   4063:                 '<th align="left">'.$rowtitle.'</th>'.
                   4064:                 '<td><select name="version">'.
                   4065:                 '<option>'.&mt('Select').'</option>'.
                   4066:                 $list.
                   4067:                 '</select></td>'.
                   4068:                 &Apache::loncommon::end_data_table_row();
                   4069:             unless ($nomenu) {
                   4070:                 $result .= &Apache::loncommon::start_data_table_row().
                   4071:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   4072:                 '<td><span class="LC_nobreak">'.
                   4073:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   4074:                 &mt('Yes').'</label>'.
                   4075:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   4076:                 '</span></td>'.
                   4077:                 &Apache::loncommon::end_data_table_row();
                   4078:             }
                   4079:             $result .=
                   4080:                 &Apache::loncommon::start_data_table_row().
                   4081:                 '<th align="left">&nbsp;</th>'.
                   4082:                 '<td>'.
                   4083:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   4084:                 '</td>'.
                   4085:                 &Apache::loncommon::end_data_table_row().
                   4086:                 &Apache::loncommon::end_data_table().
                   4087:                 '</form>';
                   4088:             $js = &previous_display_javascript($nomenu,$current);
                   4089:         } elsif ($displayed && $nomenu) {
                   4090:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   4091:         } else {
                   4092:             $result .= &mt('No previous versions to show for this student');
                   4093:         }
                   4094:         $result .= '</div>';
                   4095:     }
                   4096:     return ($current,$displayed,$result,$js);
                   4097: }
                   4098: 
                   4099: sub previous_display_javascript {
                   4100:     my ($nomenu,$current) = @_;
                   4101:     my $js = <<"JSONE";
                   4102: <script type="text/javascript">
                   4103: // <![CDATA[
                   4104: function previousVersion(uname,udom,symb) {
                   4105:     var current = '$current';
                   4106:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   4107:     var prevstr = new RegExp("^\\\\d+\$");
                   4108:     if (!prevstr.test(version)) {
                   4109:         return false;
                   4110:     }
                   4111:     var url = '';
                   4112:     if (version == current) {
                   4113:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   4114:     } else {
                   4115:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   4116:     }
                   4117: JSONE
                   4118:     if ($nomenu) {
                   4119:         $js .= <<"JSTWO";
                   4120:     document.location.href = url;
                   4121: JSTWO
                   4122:     } else {
                   4123:         $js .= <<"JSTHREE";
                   4124:     var newwin = 0;
                   4125:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   4126:         if (document.getprev.prevwin[i].checked == true) {
                   4127:             newwin = document.getprev.prevwin[i].value;
                   4128:         }
                   4129:     }
                   4130:     if (newwin == 1) {
                   4131:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   4132:         url = url+'&inhibitmenu=yes';
                   4133:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   4134:             previousWin = window.open(url,'',options,1);
                   4135:         } else {
                   4136:             previousWin.location.href = url;
                   4137:         }
                   4138:         previousWin.focus();
                   4139:         return false;
                   4140:     } else {
                   4141:         document.location.href = url;
                   4142:         return false;
                   4143:     }
                   4144: JSTHREE
                   4145:     }
                   4146:     $js .= <<"ENDJS";
                   4147:     return false;
                   4148: }
                   4149: // ]]>
                   4150: </script>
                   4151: ENDJS
                   4152: 
                   4153: }
                   4154: 
1.44      ng       4155: #--- Called from submission routine
1.38      ng       4156: sub processHandGrade {
1.608     www      4157:     my ($request,$symb) = @_;
1.324     albertel 4158:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 4159:     my $button = $env{'form.gradeOpt'};
                   4160:     my $ngrade = $env{'form.NCT'};
                   4161:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 4162:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4163:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.786     raeburn  4164:     my ($res_error,%queueable);
                   4165:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   4166:     if ($res_error) {
                   4167:         $request->print(&navmap_errormsg());
                   4168:         return;
                   4169:     } else {
                   4170:         foreach my $part (@{$partlist}) {
                   4171:             if (ref($responseType->{$part}) eq 'HASH') {
                   4172:                 foreach my $id (keys(%{$responseType->{$part}})) {
                   4173:                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   4174:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   4175:                         $queueable{$part} = 1;
                   4176:                         last;
                   4177:                     }
                   4178:                 }
                   4179:             }
                   4180:         }
                   4181:     }
1.301     albertel 4182: 
1.44      ng       4183:     if ($button eq 'Save & Next') {
1.798   ! raeburn  4184:         my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
        !          4185:         my (%skip_passback,%pbsave,%pbcollab);
1.44      ng       4186: 	my $ctr = 0;
                   4187: 	while ($ctr < $ngrade) {
1.257     albertel 4188: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  4189: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
1.798   ! raeburn  4190:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable,\%needpb,\%skip_passback,\%pbsave);
1.71      ng       4191: 	    if ($errorflag eq 'no_score') {
                   4192: 		$ctr++;
                   4193: 		next;
                   4194: 	    }
1.104     albertel 4195: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   4196: 		$request->print(
                   4197:                     '<span class="LC_error">'
                   4198:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   4199:                    .'</span>');
1.104     albertel 4200: 		$ctr++;
                   4201: 		next;
                   4202: 	    }
1.726     raeburn  4203:             if ($numhidden) {
                   4204:                 $request->print(
                   4205:                     '<span class="LC_info">'
                   4206:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   4207:                    .'</span><br />');
                   4208:             }
1.257     albertel 4209: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       4210: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 4211: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   4212:             my ($feedurl,$showsymb) =
                   4213: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   4214: 	    my $messagetail;
1.62      albertel 4215: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      4216: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      4217: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  4218: 		$subject.=' ['.$restitle.']';
1.44      ng       4219: 		my (@msgnum) = split(/,/,$includemsg);
                   4220: 		foreach (@msgnum) {
1.257     albertel 4221: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       4222: 		}
1.80      ng       4223: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      4224: 		if ($env{'form.withgrades'.$ctr}) {
                   4225: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  4226: 		    $messagetail = " for <a href=\"".
1.605     www      4227: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  4228: 		}
                   4229: 		$msgstatus = 
                   4230:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   4231: 						     $message.$messagetail,
1.418     albertel 4232:                                                      undef,$feedurl,undef,
1.386     raeburn  4233:                                                      undef,undef,$showsymb,
                   4234:                                                      $restitle);
1.574     bisitz   4235: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  4236: 				$msgstatus.'<br />');
1.44      ng       4237: 	    }
1.257     albertel 4238: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 4239: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 4240: 		foreach my $collabstr (@collabstrs) {
                   4241: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 4242: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 4243: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 4244: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.798   ! raeburn  4245: 					   $env{'form.unamedom'.$ctr},$part,\%queueable,\%needpb,\%skip_passback,%pbsave);
1.150     albertel 4246: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 4247: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 4248: 			    next;
1.798   ! raeburn  4249: 			} else {
        !          4250:                             $pbcollab{$collaborator}{$part} = [$pts,$wgt];
        !          4251:                             if ($message ne '') {
1.418     albertel 4252: 			    my ($baseurl,$showsymb) = 
                   4253: 				&get_feedurl_and_symb($symb,$collaborator,
                   4254: 						      $udom);
                   4255: 			    if ($env{'form.withgrades'.$ctr}) {
                   4256: 				$messagetail = " for <a href=\"".
1.605     www      4257:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 4258: 			    }
1.418     albertel 4259: 			    $msgstatus = 
                   4260: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 4261: 			}
1.44      ng       4262: 		    }
                   4263: 		}
                   4264: 	    }
                   4265: 	    $ctr++;
                   4266: 	}
1.798   ! raeburn  4267:         if ((keys(%pbcollab)) && (keys(%needpb))) {
        !          4268:             # FIXME passback scores for collaborators
        !          4269:         }
1.44      ng       4270:     }
                   4271: 
1.773     raeburn  4272:     my %keyhash = ();
                   4273:     if ($numessay) {
1.119     ng       4274: 	# Keywords sorted in alphabatical order
1.257     albertel 4275: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   4276: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  4277: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 4278: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   4279: 	$env{'form.keywords'} = join(' ',@keywords);
                   4280: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   4281: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   4282: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   4283: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   4284: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  4285:     }
1.119     ng       4286: 
1.773     raeburn  4287:     if ($env{'form.compmsg'}) {
1.119     ng       4288: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 4289: 	# New messages are saved in env for the next student.
1.119     ng       4290: 	# All messages are saved in nohist_handgrade.db
                   4291: 	my ($ctr,$idx) = (1,1);
1.257     albertel 4292: 	while ($ctr <= $env{'form.savemsgN'}) {
                   4293: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   4294: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       4295: 		$idx++;
                   4296: 	    }
                   4297: 	    $ctr++;
1.41      ng       4298: 	}
1.119     ng       4299: 	$ctr = 0;
                   4300: 	while ($ctr < $ngrade) {
1.257     albertel 4301: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  4302: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4303: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4304: 	        $idx++;
1.119     ng       4305: 	    }
                   4306: 	    $ctr++;
1.41      ng       4307: 	}
1.257     albertel 4308: 	$env{'form.savemsgN'} = --$idx;
                   4309: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       4310:     }
1.773     raeburn  4311:     if (($numessay) || ($env{'form.compmsg'})) {
                   4312:         my $putresult = &Apache::lonnet::put
                   4313:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   4314:     }
                   4315: 
1.44      ng       4316:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 4317:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   4318:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       4319: 	my ($ctr,$total) = (0,0);
                   4320: 	while ($ctr < $ngrade) {
1.257     albertel 4321: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       4322: 	    $ctr++;
                   4323: 	}
1.257     albertel 4324: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       4325: 	$ctr = 0;
                   4326: 	while ($ctr < $total) {
1.257     albertel 4327: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   4328: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   4329: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      4330: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       4331: 	    $ctr++;
                   4332: 	}
                   4333: 	return '';
                   4334:     }
1.36      ng       4335: 
1.44      ng       4336:     # Get the next/previous one or group of students
1.257     albertel 4337:     my $firststu = $env{'form.unamedom0'};
                   4338:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       4339:     my $ctr = 2;
1.41      ng       4340:     while ($laststu eq '') {
1.257     albertel 4341: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       4342: 	$ctr++;
                   4343: 	$laststu = $firststu if ($ctr > $ngrade);
                   4344:     }
1.44      ng       4345: 
1.41      ng       4346:     my (@parsedlist,@nextlist);
                   4347:     my ($nextflg) = 0;
1.524     raeburn  4348:     foreach my $item (sort 
1.294     albertel 4349: 	     {
                   4350: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4351: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4352: 		 }
                   4353: 		 return $a cmp $b;
                   4354: 	     } (keys(%$fullname))) {
1.41      ng       4355: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  4356: 	    push(@parsedlist,$item);
1.41      ng       4357: 	}
1.524     raeburn  4358: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       4359: 	if ($button eq 'Previous') {
1.524     raeburn  4360: 	    last if ($item eq $firststu);
                   4361: 	    push(@parsedlist,$item);
1.41      ng       4362: 	}
                   4363:     }
                   4364:     $ctr = 0;
                   4365:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   4366:     foreach my $student (@parsedlist) {
1.257     albertel 4367: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       4368: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 4369: 	
                   4370: 	if ($submitonly eq 'queued') {
                   4371: 	    my %queue_status = 
                   4372: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4373: 							$udom,$uname);
                   4374: 	    next if (!defined($queue_status{'gradingqueue'}));
                   4375: 	}
                   4376: 
1.156     albertel 4377: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 4378: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 4379: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 4380: 	    my $submitted = 0;
1.248     albertel 4381: 	    my $ungraded = 0;
                   4382: 	    my $incorrect = 0;
1.524     raeburn  4383: 	    foreach my $item (keys(%status)) {
                   4384: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   4385: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   4386: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   4387: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 4388: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   4389: 		    $submitted = 0;
                   4390: 		}
1.41      ng       4391: 	    }
1.156     albertel 4392: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   4393: 				     $submitonly eq 'incorrect' ||
                   4394: 				     $submitonly eq 'graded'));
1.248     albertel 4395: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   4396: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       4397: 	}
1.524     raeburn  4398: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       4399: 	last if ($ctr == $ntstu);
1.41      ng       4400: 	$ctr++;
                   4401:     }
1.36      ng       4402: 
1.41      ng       4403:     $ctr = 0;
                   4404:     my $total = scalar(@nextlist)-1;
1.39      ng       4405: 
1.524     raeburn  4406:     foreach (sort(@nextlist)) {
1.41      ng       4407: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 4408: 	$env{'form.student'}  = $uname;
                   4409: 	$env{'form.userdom'}  = $udom;
                   4410: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      4411: 	&submission($request,$ctr,$total,$symb);
1.41      ng       4412: 	$ctr++;
                   4413:     }
                   4414:     if ($total < 0) {
1.653     raeburn  4415: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       4416: 	$request->print($the_end);
                   4417:     }
                   4418:     return '';
1.38      ng       4419: }
1.36      ng       4420: 
1.44      ng       4421: #---- Save the score and award for each student, if changed
1.38      ng       4422: sub saveHandGrade {
1.798   ! raeburn  4423:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable,$needpb,$skip_passback,$pbsave) = @_;
1.342     banghart 4424:     my @version_parts;
1.104     albertel 4425:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 4426: 					   $env{'request.course.id'});
1.104     albertel 4427:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 4428:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 4429:     my @parts_graded;
1.77      ng       4430:     my %newrecord  = ();
1.726     raeburn  4431:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  4432:     my %aggregate = ();
                   4433:     my $aggregateflag = 0;
1.798   ! raeburn  4434:     my $sendupdate;
1.726     raeburn  4435:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  4436:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  4437:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  4438:         $totchg += $numchgs;
1.798   ! raeburn  4439:         if ($numchgs) {
        !          4440:             $sendupdate = 1;
        !          4441:         }
1.726     raeburn  4442:     }
1.798   ! raeburn  4443:     my (%weights,%awardeds,%excuseds);
1.301     albertel 4444:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   4445:     foreach my $new_part (@parts) {
1.337     banghart 4446: 	#collaborator ($submi may vary for different parts
1.259     banghart 4447: 	if ($submitter && $new_part ne $part) { next; }
                   4448: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.798   ! raeburn  4449:         if ($env{'form.WGT'.$newflg.'_'.$new_part} eq '') {
        !          4450:             $weights{$symb}{$new_part} = 1;
        !          4451:         } else {
        !          4452:             $weights{$symb}{$new_part} = $env{'form.WGT'.$newflg.'_'.$new_part};
        !          4453:         }
1.125     ng       4454: 	if ($dropMenu eq 'excused') {
1.798   ! raeburn  4455:             $excuseds{$symb}{$new_part} = 1;
        !          4456:             $awardeds{$symb}{$new_part} = '';
1.259     banghart 4457: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   4458: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   4459: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   4460: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 4461: 		}
1.364     banghart 4462: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.798   ! raeburn  4463:                 $sendupdate = 1;
1.58      albertel 4464: 	    }
1.125     ng       4465: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 4466: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  4467: 	    foreach my $key (keys(%record)) {
1.259     banghart 4468: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 4469: 	    }
1.259     banghart 4470: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4471: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 4472:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   4473: 
                   4474:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   4475: 					       [$new_part]);
                   4476:             my $aggtries =$totaltries;
1.269     raeburn  4477:             if ($last_resets{$new_part}) {
1.270     albertel 4478:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   4479: 					   $new_part);
1.269     raeburn  4480:             }
1.270     albertel 4481: 
                   4482:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  4483:             if ($aggtries > 0) {
1.327     albertel 4484:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  4485:                 $aggregateflag = 1;
                   4486:             }
1.798   ! raeburn  4487:             $sendupdate = 1;
        !          4488:             $excuseds{$symb}{$new_part} = '';
        !          4489:             $awardeds{$symb}{$new_part} = '';
1.125     ng       4490: 	} elsif ($dropMenu eq '') {
1.259     banghart 4491: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   4492: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   4493: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   4494: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 4495: 		next;
                   4496: 	    }
1.259     banghart 4497: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   4498: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       4499: 	    my $partial= $pts/$wgt;
1.798   ! raeburn  4500:             $awardeds{$symb}{$new_part} = $partial;
        !          4501:             $excuseds{$symb}{$new_part} = '';
1.259     banghart 4502: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 4503: 		#do not update score for part if not changed.
1.346     banghart 4504:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 4505: 		next;
1.251     banghart 4506: 	    } else {
1.524     raeburn  4507: 	        push(@parts_graded,$new_part);
1.798   ! raeburn  4508:                 $sendupdate = 1;
1.153     albertel 4509: 	    }
1.259     banghart 4510: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   4511: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 4512: 	    }
1.259     banghart 4513: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       4514: 	    if ($partial == 0) {
1.153     albertel 4515: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   4516: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   4517: 		}
1.41      ng       4518: 	    } else {
1.153     albertel 4519: 		if ($record{$reckey} ne 'correct_by_override') {
                   4520: 		    $newrecord{$reckey} = 'correct_by_override';
                   4521: 		}
                   4522: 	    }	    
                   4523: 	    if ($submitter && 
1.259     banghart 4524: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   4525: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       4526: 	    }
1.259     banghart 4527: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4528: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       4529: 	}
1.259     banghart 4530: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 4531: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   4532: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   4533: 	        $dropMenu eq 'reset status')
                   4534: 	   {
1.524     raeburn  4535: 	    push(@version_parts,$new_part);
1.259     banghart 4536: 	}
1.41      ng       4537:     }
1.301     albertel 4538:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4539:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4540: 
1.344     albertel 4541:     if (%newrecord) {
                   4542:         if (@version_parts) {
1.364     banghart 4543:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   4544:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 4545: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 4546: 	    foreach my $new_part (@version_parts) {
                   4547: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   4548: 				$new_part,\%newrecord);
                   4549: 	    }
1.259     banghart 4550:         }
1.44      ng       4551: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 4552: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 4553: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.786     raeburn  4554: 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       4555:     }
1.269     raeburn  4556:     if ($aggregateflag) {
                   4557:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4558: 			      $cdom,$cnum);
1.269     raeburn  4559:     }
1.798   ! raeburn  4560:     if (($sendupdate) && (!$submitter)) {
        !          4561:         if ((ref($needpb) eq 'HASH') &&
        !          4562:             (keys(%{$needpb}))) {
        !          4563:             &process_passbacks('handgrade',[$symb],$cdom,$cnum,$domain,$stuname,\%weights,
        !          4564:                                \%awardeds,\%excuseds,$needpb,$skip_passback,$pbsave);
        !          4565:         }
        !          4566:     }
1.726     raeburn  4567:     return ('',$pts,$wgt,$totchg);
                   4568: }
                   4569: 
                   4570: sub makehidden {
1.728     raeburn  4571:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  4572:     return unless (ref($record) eq 'HASH');
                   4573:     my %modified;
                   4574:     my $numchanged = 0;
                   4575:     if (exists($record->{$version.':keys'})) {
                   4576:         my $partsregexp = $parts;
                   4577:         $partsregexp =~ s/,/|/g;
                   4578:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   4579:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   4580:                  my $item = $1;
                   4581:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   4582:                      $modified{$key} = $record->{$version.':'.$key};
                   4583:                  }
                   4584:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   4585:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   4586:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   4587:                 $modified{$key} = $record->{$version.':'.$key};
                   4588:             }
                   4589:         }
                   4590:         if (keys(%modified)) {
                   4591:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  4592:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  4593:                 $numchanged ++;
                   4594:             }
                   4595:         }
                   4596:     }
                   4597:     return $numchanged;
1.36      ng       4598: }
1.322     albertel 4599: 
1.380     albertel 4600: sub check_and_remove_from_queue {
1.786     raeburn  4601:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 4602:     my @ungraded_parts;
                   4603:     foreach my $part (@{$parts}) {
                   4604: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   4605: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   4606: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   4607: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   4608: 		) {
1.786     raeburn  4609:             if ($queueable->{$part}) {
                   4610: 	        push(@ungraded_parts, $part);
                   4611:             }
1.380     albertel 4612: 	}
                   4613:     }
                   4614:     if ( !@ungraded_parts ) {
                   4615: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   4616: 					       $cnum,$domain,$stuname);
                   4617:     }
                   4618: }
                   4619: 
1.337     banghart 4620: sub handback_files {
                   4621:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  4622:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  4623:     my $res_error;
                   4624:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4625:     if ($res_error) {
                   4626:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   4627:         return;
                   4628:     }
1.654     raeburn  4629:     my @handedback;
                   4630:     my $file_msg;
1.375     albertel 4631:     my @part_response_id = &flatten_responseType($responseType);
                   4632:     foreach my $part_response_id (@part_response_id) {
                   4633:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   4634: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  4635:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   4636:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   4637:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   4638:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   4639:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 4640:                     my ($directory,$answer_file) = 
1.654     raeburn  4641:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 4642:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  4643: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 4644: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  4645:                     my $getpropath = 1;
1.773     raeburn  4646:                     my ($dir_list,$listerror) =
1.662     raeburn  4647:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   4648:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  4649: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   4650:                     # fix filename
1.355     banghart 4651:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   4652:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  4653:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 4654:             	                                $save_file_name);
1.337     banghart 4655:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  4656:                         $request->print('<br /><span class="LC_error">'.
                   4657:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  4658:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  4659:                                         '</span>');
1.356     banghart 4660:                     } else {
1.360     banghart 4661:                         # mark the file as read only
1.654     raeburn  4662:                         push(@handedback,$save_file_name);
1.367     albertel 4663: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   4664: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   4665: 			}
                   4666:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  4667: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 4668:                     }
1.686     bisitz   4669:                     $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 4670:                 }
                   4671:             }
                   4672:         }
1.654     raeburn  4673:     }
                   4674:     if (@handedback > 0) {
                   4675:         $request->print('<br />');
                   4676:         my @what = ($symb,$env{'request.course.id'},'handback');
                   4677:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   4678:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   4679:         my ($subject,$message);
                   4680:         if (scalar(@handedback) == 1) {
                   4681:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   4682:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   4683:         } else {
                   4684:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   4685:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   4686:         }
                   4687:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   4688:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   4689:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   4690:         my ($feedurl,$showsymb) =
                   4691:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   4692:         my $restitle = &Apache::lonnet::gettitle($symb);
                   4693:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   4694:         my $msgstatus =
                   4695:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   4696:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   4697:                  $restitle);
                   4698:         if ($msgstatus) {
                   4699:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   4700:         }
                   4701:     }
1.338     banghart 4702:     return;
1.337     banghart 4703: }
                   4704: 
1.418     albertel 4705: sub get_feedurl_and_symb {
                   4706:     my ($symb,$uname,$udom) = @_;
                   4707:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   4708:     $url = &Apache::lonnet::clutter($url);
                   4709:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   4710: 					$symb,$udom,$uname);
                   4711:     if ($encrypturl =~ /^yes$/i) {
                   4712: 	&Apache::lonenc::encrypted(\$url,1);
                   4713: 	&Apache::lonenc::encrypted(\$symb,1);
                   4714:     }
                   4715:     return ($url,$symb);
                   4716: }
                   4717: 
1.313     banghart 4718: sub get_submitted_files {
                   4719:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   4720:     my @files;
                   4721:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   4722:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   4723:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   4724:     	    push(@files,$file_url.$file);
                   4725:         }
                   4726:     }
                   4727:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   4728:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   4729:     }
                   4730:     return (\@files);
                   4731: }
1.322     albertel 4732: 
1.269     raeburn  4733: # ----------- Provides number of tries since last reset.
                   4734: sub get_num_tries {
                   4735:     my ($record,$last_reset,$part) = @_;
                   4736:     my $timestamp = '';
                   4737:     my $num_tries = 0;
                   4738:     if ($$record{'version'}) {
                   4739:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   4740:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   4741:                 $timestamp = $$record{$version.':timestamp'};
                   4742:                 if ($timestamp > $last_reset) {
                   4743:                     $num_tries ++;
                   4744:                 } else {
                   4745:                     last;
                   4746:                 }
                   4747:             }
                   4748:         }
                   4749:     }
                   4750:     return $num_tries;
                   4751: }
                   4752: 
                   4753: # ----------- Determine decrements required in aggregate totals 
                   4754: sub decrement_aggs {
                   4755:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   4756:     my %decrement = (
                   4757:                         attempts => 0,
                   4758:                         users => 0,
                   4759:                         correct => 0
                   4760:                     );
                   4761:     $decrement{'attempts'} = $aggtries;
                   4762:     if ($solvedstatus =~ /^correct/) {
                   4763:         $decrement{'correct'} = 1;
                   4764:     }
                   4765:     if ($aggtries == $totaltries) {
                   4766:         $decrement{'users'} = 1;
                   4767:     }
1.524     raeburn  4768:     foreach my $type (keys(%decrement)) {
1.269     raeburn  4769:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   4770:     }
                   4771:     return;
                   4772: }
                   4773: 
                   4774: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   4775: sub get_last_resets {
1.270     albertel 4776:     my ($symb,$courseid,$partids) =@_;
                   4777:     my %last_resets;
1.269     raeburn  4778:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   4779:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 4780:     my @keys;
                   4781:     foreach my $part (@{$partids}) {
                   4782: 	push(@keys,"$symb\0$part\0resettime");
                   4783:     }
                   4784:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   4785: 				     $cdom,$cname);
                   4786:     foreach my $part (@{$partids}) {
                   4787: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  4788:     }
1.270     albertel 4789:     return %last_resets;
1.269     raeburn  4790: }
                   4791: 
1.251     banghart 4792: # ----------- Handles creating versions for portfolio files as answers
                   4793: sub version_portfiles {
1.343     banghart 4794:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 4795:     my $version_parts = join('|',@$v_flag);
1.343     banghart 4796:     my @returned_keys;
1.255     banghart 4797:     my $parts = join('|', @$parts_graded);
1.277     albertel 4798:     foreach my $key (keys(%$record)) {
1.259     banghart 4799:         my $new_portfiles;
1.263     banghart 4800:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 4801:             my @versioned_portfiles;
1.367     albertel 4802:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  4803:             if (@portfiles) {
                   4804:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   4805:                                                       \@versioned_portfiles);
1.252     banghart 4806:             }
1.343     banghart 4807:             $$record{$key} = join(',',@versioned_portfiles);
                   4808:             push(@returned_keys,$key);
1.251     banghart 4809:         }
1.794     raeburn  4810:     }
                   4811:     return (@returned_keys);
1.305     banghart 4812: }
                   4813: 
1.44      ng       4814: #--------------------------------------------------------------------------------------
                   4815: #
                   4816: #-------------------------- Next few routines handles grading by section or whole class
                   4817: #
                   4818: #--- Javascript to handle grading by section or whole class
1.42      ng       4819: sub viewgrades_js {
                   4820:     my ($request) = shift;
                   4821: 
1.539     riegler  4822:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  4823:     &js_escape(\$alertmsg);
1.597     wenzelju 4824:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       4825:    function writePoint(partid,weight,point) {
1.125     ng       4826: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   4827: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       4828: 	if (point == "textval") {
1.125     ng       4829: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  4830: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4831: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       4832: 		var resetbox = false;
                   4833: 		for (var i=0; i<radioButton.length; i++) {
                   4834: 		    if (radioButton[i].checked) {
                   4835: 			textbox.value = i;
                   4836: 			resetbox = true;
                   4837: 		    }
                   4838: 		}
                   4839: 		if (!resetbox) {
                   4840: 		    textbox.value = "";
                   4841: 		}
                   4842: 		return;
                   4843: 	    }
1.109     matthew  4844: 	    if (parseFloat(point) > parseFloat(weight)) {
                   4845: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4846: 				   ") greater than the weight for the part. Accept?");
                   4847: 		if (resp == false) {
                   4848: 		    textbox.value = "";
                   4849: 		    return;
                   4850: 		}
                   4851: 	    }
1.42      ng       4852: 	    for (var i=0; i<radioButton.length; i++) {
                   4853: 		radioButton[i].checked=false;
1.109     matthew  4854: 		if (parseFloat(point) == i) {
1.42      ng       4855: 		    radioButton[i].checked=true;
                   4856: 		}
                   4857: 	    }
1.41      ng       4858: 
1.42      ng       4859: 	} else {
1.125     ng       4860: 	    textbox.value = parseFloat(point);
1.42      ng       4861: 	}
1.41      ng       4862: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4863: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 4864: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4865: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4866: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4867: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4868: 	    if (saveval != "correct") {
                   4869: 		scorename.value = point;
1.43      ng       4870: 		if (selname[0].selected != true) {
                   4871: 		    selname[0].selected = true;
                   4872: 		}
1.42      ng       4873: 	    }
                   4874: 	}
1.125     ng       4875: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       4876:     }
                   4877: 
                   4878:     function writeRadText(partid,weight) {
1.125     ng       4879: 	var selval   = document.classgrade["SELVAL_"+partid];
                   4880: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      4881:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       4882: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   4883: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       4884: 	    for (var i=0; i<radioButton.length; i++) {
                   4885: 		radioButton[i].checked=false;
                   4886: 
                   4887: 	    }
                   4888: 	    textbox.value = "";
                   4889: 
                   4890: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4891: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4892: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4893: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4894: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4895: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4896: 		if ((saveval != "correct") || override) {
1.42      ng       4897: 		    scorename.value = "";
1.125     ng       4898: 		    if (selval[1].selected) {
                   4899: 			selname[1].selected = true;
                   4900: 		    } else {
                   4901: 			selname[2].selected = true;
                   4902: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   4903: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   4904: 		    }
1.42      ng       4905: 		}
                   4906: 	    }
1.43      ng       4907: 	} else {
                   4908: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4909: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4910: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4911: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4912: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4913: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4914: 		if ((saveval != "correct") || override) {
1.125     ng       4915: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       4916: 		    selname[0].selected = true;
                   4917: 		}
                   4918: 	    }
                   4919: 	}	    
1.42      ng       4920:     }
                   4921: 
                   4922:     function changeSelect(partid,user) {
1.125     ng       4923: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4924: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       4925: 	var point  = textbox.value;
1.125     ng       4926: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       4927: 
1.109     matthew  4928: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4929: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       4930: 	    textbox.value = "";
                   4931: 	    return;
                   4932: 	}
1.109     matthew  4933: 	if (parseFloat(point) > parseFloat(weight)) {
                   4934: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4935: 			       ") greater than the weight of the part. Accept?");
                   4936: 	    if (resp == false) {
                   4937: 		textbox.value = "";
                   4938: 		return;
                   4939: 	    }
                   4940: 	}
1.42      ng       4941: 	selval[0].selected = true;
                   4942:     }
                   4943: 
                   4944:     function changeOneScore(partid,user) {
1.125     ng       4945: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4946: 	if (selval[1].selected || selval[2].selected) {
                   4947: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   4948: 	    if (selval[2].selected) {
                   4949: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   4950: 	    }
1.269     raeburn  4951:         }
1.42      ng       4952:     }
                   4953: 
                   4954:     function resetEntry(numpart) {
                   4955: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       4956: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   4957: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   4958: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   4959: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       4960: 	    for (var i=0; i<radioButton.length; i++) {
                   4961: 		radioButton[i].checked=false;
                   4962: 
                   4963: 	    }
                   4964: 	    textbox.value = "";
                   4965: 	    selval[0].selected = true;
                   4966: 
                   4967: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4968: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4969: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4970: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4971: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   4972: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   4973: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   4974: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4975: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4976: 		if (saveselval == "excused") {
1.43      ng       4977: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       4978: 		} else {
1.43      ng       4979: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       4980: 		}
                   4981: 	    }
1.41      ng       4982: 	}
1.42      ng       4983:     }
                   4984: 
1.41      ng       4985: VIEWJAVASCRIPT
1.42      ng       4986: }
                   4987: 
1.44      ng       4988: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       4989: sub viewgrades {
1.608     www      4990:     my ($request,$symb) = @_;
1.745     raeburn  4991:     my ($is_tool,$toolsymb);
                   4992:     if ($symb =~ /ext\.tool$/) {
                   4993:         $is_tool = 1;
                   4994:         $toolsymb = $symb;
                   4995:     }
1.42      ng       4996:     &viewgrades_js($request);
1.41      ng       4997: 
1.168     albertel 4998:     #need to make sure we have the correct data for later EXT calls, 
                   4999:     #thus invalidate the cache
                   5000:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5001:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5002:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5003:     &Apache::lonnet::clear_EXT_cache_status();
                   5004: 
1.398     albertel 5005:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       5006: 
                   5007:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 5008:     $result.=&jscriptNform($symb);
1.41      ng       5009: 
1.44      ng       5010:     #beginning of class grading form
1.442     banghart 5011:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       5012:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 5013: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       5014: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 5015: 	&build_section_inputs().
1.442     banghart 5016: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       5017: 
1.738     raeburn  5018:     #retrieve selected groups
                   5019:     my (@groups,$group_display);
                   5020:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   5021:     if (grep(/^all$/,@groups)) {
                   5022:         @groups = ('all');
                   5023:     } elsif (grep(/^none$/,@groups)) {
                   5024:         @groups = ('none');
                   5025:     } elsif (@groups > 0) {
                   5026:         $group_display = join(', ',@groups);
                   5027:     }
                   5028: 
                   5029:     my ($common_header,$specific_header,@sections,$section_display);
1.780     raeburn  5030:     if ($env{'request.course.sec'} ne '') {
                   5031:         @sections = ($env{'request.course.sec'});
                   5032:     } else {
                   5033:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   5034:     }
                   5035: 
                   5036: # Check if Save button should be usable
                   5037:     my $disabled = ' disabled="disabled"';
                   5038:     if ($perm{'mgr'}) {
                   5039:         if (grep(/^all$/,@sections)) {
                   5040:             undef($disabled);
                   5041:         } else {
                   5042:             foreach my $sec (@sections) {
                   5043:                 if (&canmodify($sec)) {
                   5044:                     undef($disabled);
                   5045:                     last;
                   5046:                 }
                   5047:             }
                   5048:         }
                   5049:     }
1.738     raeburn  5050:     if (grep(/^all$/,@sections)) {
                   5051:         @sections = ('all');
                   5052:         if ($group_display) {
                   5053:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   5054:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   5055:         } elsif (grep(/^none$/,@groups)) {
                   5056:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   5057:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   5058:         } else {
                   5059: 	    $common_header = &mt('Assign Common Grade to Class');
                   5060:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   5061:         }
                   5062:     } elsif (grep(/^none$/,@sections)) {
                   5063:         @sections = ('none');
                   5064:         if ($group_display) {
                   5065:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   5066:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   5067:         } elsif (grep(/^none$/,@groups)) {
                   5068:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   5069:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   5070:         } else {
                   5071:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   5072: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   5073:         }
                   5074:     } else {
                   5075:         $section_display = join (", ",@sections);
                   5076:         if ($group_display) {
                   5077:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   5078:                                  $section_display,$group_display);
                   5079:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   5080:                                    $section_display,$group_display);
                   5081:         } elsif (grep(/^none$/,@groups)) {
                   5082:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   5083:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   5084:         } else {
                   5085:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   5086: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   5087:         }
                   5088:     }
                   5089:     my %submit_types = &substatus_options();
                   5090:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   5091: 
                   5092:     if ($env{'form.submitonly'} eq 'all') {
                   5093:         $result.= '<h3>'.$common_header.'</h3>';
                   5094:     } else {
1.745     raeburn  5095:         my $text;
                   5096:         if ($is_tool) {
                   5097:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5098:         } else {
                   5099:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5100:         }
                   5101:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 5102:     }
1.738     raeburn  5103:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       5104:     #radio buttons/text box for assigning points for a section or class.
                   5105:     #handles different parts of a problem
1.582     raeburn  5106:     my $res_error;
                   5107:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   5108:     if ($res_error) {
                   5109:         return &navmap_errormsg();
                   5110:     }
1.42      ng       5111:     my %weight = ();
                   5112:     my $ctsparts = 0;
1.45      ng       5113:     my %seen = ();
1.745     raeburn  5114:     my @part_response_id;
                   5115:     if ($is_tool) {
                   5116:         @part_response_id = ([0,'']);
                   5117:     } else {
                   5118:         @part_response_id = &flatten_responseType($responseType);
                   5119:     }
1.375     albertel 5120:     foreach my $part_response_id (@part_response_id) {
                   5121:     	my ($partid,$respid) = @{ $part_response_id };
                   5122: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       5123: 	next if $seen{$partid};
                   5124: 	$seen{$partid}++;
1.42      ng       5125: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   5126: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   5127: 
1.324     albertel 5128: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 5129: 	my $radio.='<table border="0"><tr>';  
1.41      ng       5130: 	my $ctr = 0;
1.42      ng       5131: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 5132: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 5133: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 5134: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       5135: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   5136: 	    $ctr++;
                   5137: 	}
1.485     albertel 5138: 	$radio.='</tr></table>';
                   5139: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   5140: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 5141: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  5142: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   5143:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   5144:             '<select name="SELVAL_'.$partid.'" '.
                   5145:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   5146:                 $weight{$partid}.')"> '.
1.401     albertel 5147: 	    '<option selected="selected"> </option>'.
1.485     albertel 5148: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   5149: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   5150: 	    '</select></td>'.
                   5151:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   5152: 	$line.='<input type="hidden" name="partid_'.
                   5153: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   5154: 	$line.='<input type="hidden" name="weight_'.
                   5155: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   5156: 
                   5157: 	$result.=
                   5158: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   5159: 	    '<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 5160: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       5161: 	$ctsparts++;
1.41      ng       5162:     }
1.474     albertel 5163:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 5164: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 5165:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   5166: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       5167: 
1.44      ng       5168:     #table listing all the students in a section/class
                   5169:     #header of table
1.738     raeburn  5170:     if ($env{'form.submitonly'} eq 'all') {
                   5171:         $result.= '<h3>'.$specific_header.'</h3>';
                   5172:     } else {
1.745     raeburn  5173:         my $text;
                   5174:         if ($is_tool) {
                   5175:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   5176:         } else {
                   5177:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   5178:         }
                   5179:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  5180:     }
                   5181:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  5182: 	      &Apache::loncommon::start_data_table_header_row().
                   5183: 	      '<th>'.&mt('No.').'</th>'.
                   5184: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  5185:     my $partserror;
                   5186:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5187:     if ($partserror) {
                   5188:         return &navmap_errormsg();
                   5189:     }
1.324     albertel 5190:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  5191:     my @partids = ();
1.41      ng       5192:     foreach my $part (@parts) {
1.745     raeburn  5193: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  5194:         my $narrowtext = &mt('Tries');
                   5195: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  5196: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 5197: 	my ($partid) = &split_part_type($part);
1.524     raeburn  5198:         push(@partids,$partid);
1.628     www      5199: #
                   5200: # FIXME: Looks like $display looks at English text
                   5201: #
1.324     albertel 5202: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       5203: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 5204: 	    $result.='<th>'.
1.697     bisitz   5205: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   5206: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       5207: 	    next;
1.485     albertel 5208: 	    
1.207     albertel 5209: 	} else {
1.485     albertel 5210: 	    if ($display =~ /Problem Status/) {
                   5211: 		my $grade_status_mt = &mt('Grade Status');
                   5212: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   5213: 	    }
                   5214: 	    my $part_mt = &mt('Part:');
                   5215: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       5216: 	}
1.485     albertel 5217: 
1.474     albertel 5218: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       5219:     }
1.474     albertel 5220:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       5221: 
1.270     albertel 5222:     my %last_resets = 
                   5223: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  5224: 
1.41      ng       5225:     #get info for each student
1.44      ng       5226:     #list all the students - with points and grade status
1.738     raeburn  5227:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       5228:     my $ctr = 0;
1.294     albertel 5229:     foreach (sort 
                   5230: 	     {
                   5231: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5232: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5233: 		 }
                   5234: 		 return $a cmp $b;
                   5235: 	     } (keys(%$fullname))) {
1.324     albertel 5236: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  5237: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       5238:     }
1.474     albertel 5239:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       5240:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.780     raeburn  5241:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5242: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  5243:     if ($ctr == 0) {
1.442     banghart 5244:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  5245:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   5246:                 '<span class="LC_warning">';
                   5247:         if ($env{'form.submitonly'} eq 'all') {
                   5248:             if (grep(/^all$/,@sections)) {
                   5249:                 if (grep(/^all$/,@groups)) {
                   5250:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   5251:                                    $stu_status);
                   5252:                 } elsif (grep(/^none$/,@groups)) {
                   5253:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   5254:                                    $stu_status); 
                   5255:                 } else {
                   5256:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5257:                                    $group_display,$stu_status);
                   5258:                 }
                   5259:             } elsif (grep(/^none$/,@sections)) {
                   5260:                 if (grep(/^all$/,@groups)) {
                   5261:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   5262:                                    $stu_status);
                   5263:                 } elsif (grep(/^none$/,@groups)) {
                   5264:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   5265:                                    $stu_status);
                   5266:                 } else {
                   5267:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   5268:                                    $group_display,$stu_status);
                   5269:                 }
                   5270:             } else {
                   5271:                 if (grep(/^all$/,@groups)) {
                   5272:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   5273:                                    $section_display,$stu_status);
                   5274:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  5275:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  5276:                                    $section_display,$stu_status);
                   5277:                 } else {
                   5278:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   5279:                                    $section_display,$group_display,$stu_status);
                   5280:                 }
                   5281:             }
                   5282:         } else {
                   5283:             if (grep(/^all$/,@sections)) {
                   5284:                 if (grep(/^all$/,@groups)) {
                   5285:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5286:                                    $stu_status,$submission_status);
                   5287:                 } elsif (grep(/^none$/,@groups)) {
                   5288:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5289:                                    $stu_status,$submission_status);
                   5290:                 } else {
                   5291:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5292:                                    $group_display,$stu_status,$submission_status);
                   5293:                 }
                   5294:             } elsif (grep(/^none$/,@sections)) {
                   5295:                 if (grep(/^all$/,@groups)) {
                   5296:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5297:                                    $stu_status,$submission_status);
                   5298:                 } elsif (grep(/^none$/,@groups)) {
                   5299:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5300:                                    $stu_status,$submission_status);
                   5301:                 } else {
                   5302:                     $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.',
                   5303:                                    $group_display,$stu_status,$submission_status);
                   5304:                 }
                   5305:             } else {
                   5306:                 if (grep(/^all$/,@groups)) {
                   5307: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5308: 	                           $section_display,$stu_status,$submission_status);
                   5309:                 } elsif (grep(/^none$/,@groups)) {
                   5310:                     $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.',
                   5311:                                    $section_display,$stu_status,$submission_status);
                   5312:                 } else {
                   5313:                     $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.',
                   5314:                                    $section_display,$group_display,$stu_status,$submission_status);
                   5315:                 }
                   5316:             }
                   5317:         }
                   5318: 	$result .= '</span><br />';
1.96      albertel 5319:     }
1.41      ng       5320:     return $result;
                   5321: }
                   5322: 
1.738     raeburn  5323: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       5324: sub viewstudentgrade {
1.745     raeburn  5325:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       5326:     my ($uname,$udom) = split(/:/,$student);
                   5327:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  5328:     my $submitonly = $env{'form.submitonly'};
                   5329:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   5330:         my %partstatus = ();
                   5331:         if (ref($parts) eq 'ARRAY') {
                   5332:             foreach my $apart (@{$parts}) {
                   5333:                 my ($part,$type) = &split_part_type($apart);
                   5334:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   5335:                 $status = 'nothing' if ($status eq '');
                   5336:                 $partstatus{$part}      = $status;
                   5337:                 my $subkey = "resource.$part.submitted_by";
                   5338:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   5339:             }
                   5340:             my $submitted = 0;
                   5341:             my $graded = 0;
                   5342:             my $incorrect = 0;
                   5343:             foreach my $key (keys(%partstatus)) {
                   5344:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   5345:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   5346:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   5347: 
                   5348:                 my $partid = (split(/\./,$key))[1];
                   5349:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   5350:                     $submitted = 0;
                   5351:                 }
                   5352:             }
                   5353:             return if (!$submitted && ($submitonly eq 'yes' ||
                   5354:                                        $submitonly eq 'incorrect' ||
                   5355:                                        $submitonly eq 'graded'));
                   5356:             return if (!$graded && ($submitonly eq 'graded'));
                   5357:             return if (!$incorrect && $submitonly eq 'incorrect');
                   5358:         }
                   5359:     }
                   5360:     if ($submitonly eq 'queued') {
                   5361:         my ($cdom,$cnum) = split(/_/,$courseid);
                   5362:         my %queue_status =
                   5363:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   5364:                                                     $udom,$uname);
                   5365:         return if (!defined($queue_status{'gradingqueue'}));
                   5366:     }
                   5367:     $$ctr++;
                   5368:     my %aggregates = ();
1.474     albertel 5369:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  5370: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   5371: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       5372: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 5373: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 5374: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 5375:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 5376:     foreach my $apart (@$parts) {
                   5377: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       5378: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 5379:         $result.='<td align="center">';
1.269     raeburn  5380:         my ($aggtries,$totaltries);
                   5381:         unless (exists($aggregates{$part})) {
1.270     albertel 5382: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   5383: 	    $aggtries = $totaltries;
1.269     raeburn  5384:             if ($$last_resets{$part}) {  
1.270     albertel 5385:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   5386: 					   $part);
                   5387:             }
1.269     raeburn  5388:             $result.='<input type="hidden" name="'.
                   5389:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   5390:             $result.='<input type="hidden" name="'.
                   5391:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   5392:             $aggregates{$part} = 1;
                   5393:         }
1.41      ng       5394: 	if ($type eq 'awarded') {
1.320     albertel 5395: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       5396: 	    $result.='<input type="hidden" name="'.
1.89      albertel 5397: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 5398: 	    $result.='<input type="text" name="'.
1.89      albertel 5399: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   5400:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       5401: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       5402: 	} elsif ($type eq 'solved') {
                   5403: 	    my ($status,$foo)=split(/_/,$score,2);
                   5404: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 5405: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 5406: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 5407: 	    $result.='&nbsp;<select name="'.
1.89      albertel 5408: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   5409:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 5410: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   5411: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   5412: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       5413: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       5414: 	} else {
                   5415: 	    $result.='<input type="hidden" name="'.
                   5416: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   5417: 		    "\n";
1.233     albertel 5418: 	    $result.='<input type="text" name="'.
1.122     ng       5419: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   5420: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       5421: 	}
                   5422:     }
1.474     albertel 5423:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       5424:     return $result;
1.38      ng       5425: }
                   5426: 
1.44      ng       5427: #--- change scores for all the students in a section/class
                   5428: #    record does not get update if unchanged
1.38      ng       5429: sub editgrades {
1.608     www      5430:     my ($request,$symb) = @_;
1.745     raeburn  5431:     my $toolsymb;
                   5432:     if ($symb =~ /ext\.tool$/) {
                   5433:         $toolsymb = $symb;
                   5434:     }
1.41      ng       5435: 
1.433     banghart 5436:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 5437:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  5438:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       5439: 
1.477     albertel 5440:     my $result= &Apache::loncommon::start_data_table().
                   5441: 	&Apache::loncommon::start_data_table_header_row().
                   5442: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   5443: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       5444:     my %scoreptr = (
                   5445: 		    'correct'  =>'correct_by_override',
                   5446: 		    'incorrect'=>'incorrect_by_override',
                   5447: 		    'excused'  =>'excused',
                   5448: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  5449:                     'credited' =>'credit_attempted',
1.43      ng       5450: 		    'nothing'  => '',
                   5451: 		    );
1.257     albertel 5452:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       5453: 
1.798   ! raeburn  5454:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          5455:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        !          5456:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
        !          5457: 
1.44      ng       5458:     my (@partid);
                   5459:     my %weight = ();
1.54      albertel 5460:     my %columns = ();
1.44      ng       5461:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 5462: 
1.582     raeburn  5463:     my $partserror;
                   5464:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5465:     if ($partserror) {
                   5466:         return &navmap_errormsg();
                   5467:     }
1.54      albertel 5468:     my $header;
1.257     albertel 5469:     while ($ctr < $env{'form.totalparts'}) {
                   5470: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  5471: 	push(@partid,$partid);
1.257     albertel 5472: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       5473: 	$ctr++;
1.54      albertel 5474:     }
1.324     albertel 5475:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  5476:     my $totcolspan = 0;
1.54      albertel 5477:     foreach my $partid (@partid) {
1.478     albertel 5478: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   5479: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 5480: 	$columns{$partid}=2;
                   5481: 	foreach my $stores (@parts) {
                   5482: 	    my ($part,$type) = &split_part_type($stores);
                   5483: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   5484: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  5485: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  5486: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  5487:             my $narrowtext = &mt('Tries');
                   5488: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   5489: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   5490: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 5491: 	    $columns{$partid}+=2;
                   5492: 	}
1.748     raeburn  5493:         $totcolspan += $columns{$partid};
1.54      albertel 5494:     }
                   5495:     foreach my $partid (@partid) {
1.324     albertel 5496: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 5497: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   5498: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   5499: 	    '</th>';
1.54      albertel 5500: 
1.44      ng       5501:     }
1.477     albertel 5502:     $result .= &Apache::loncommon::end_data_table_header_row().
                   5503: 	&Apache::loncommon::start_data_table_header_row().
                   5504: 	$header.
                   5505: 	&Apache::loncommon::end_data_table_header_row();
                   5506:     my @noupdate;
1.126     ng       5507:     my ($updateCtr,$noupdateCtr) = (1,1);
1.798   ! raeburn  5508:     my ($got_types,%queueable,%pbsave,%skip_passback);
1.257     albertel 5509:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   5510: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 5511: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       5512: 	my %newrecord;
                   5513: 	my $updateflag = 0;
1.108     albertel 5514: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  5515: 	my $canmodify = &canmodify($usec);
                   5516: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   5517: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   5518: 	if (!$canmodify) {
1.477     albertel 5519: 	    push(@noupdate,
1.748     raeburn  5520: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   5521: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 5522: 	    next;
                   5523: 	}
1.269     raeburn  5524:         my %aggregate = ();
                   5525:         my $aggregateflag = 0;
1.281     albertel 5526: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.798   ! raeburn  5527:         my (%weights,%awardeds,%excuseds);
1.44      ng       5528: 	foreach (@partid) {
1.257     albertel 5529: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 5530: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   5531: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 5532: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   5533: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 5534: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   5535: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.798   ! raeburn  5536:             $awardeds{$symb}{$_} = $partial;
1.44      ng       5537: 	    my $score;
                   5538: 	    if ($partial eq '') {
1.257     albertel 5539: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       5540: 	    } elsif ($partial > 0) {
                   5541: 		$score = 'correct_by_override';
                   5542: 	    } elsif ($partial == 0) {
                   5543: 		$score = 'incorrect_by_override';
                   5544: 	    }
1.257     albertel 5545: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       5546: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   5547: 
1.292     albertel 5548: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   5549: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5550: 	    if ($dropMenu eq 'reset status' &&
                   5551: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 5552: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       5553: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   5554: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 5555: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       5556: 		$updateflag = 1;
1.269     raeburn  5557:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   5558:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   5559:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   5560:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   5561:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5562:                     $aggregateflag = 1;
                   5563:                 }
1.139     albertel 5564: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   5565: 		$updateflag = 1;
                   5566: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   5567: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   5568: 		$rec_update++;
1.125     ng       5569: 	    }
                   5570: 
1.93      albertel 5571: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       5572: 		'<td align="center">'.$awarded.
                   5573: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 5574: 
1.54      albertel 5575: 
                   5576: 	    my $partid=$_;
1.798   ! raeburn  5577:             if ($score eq 'excused') {
        !          5578:                 $excuseds{$symb}{$partid} = 1;
        !          5579:             } else {
        !          5580:                 $excuseds{$symb}{$partid} = '';
        !          5581:             }
1.54      albertel 5582: 	    foreach my $stores (@parts) {
                   5583: 		my ($part,$type) = &split_part_type($stores);
                   5584: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   5585: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 5586: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   5587: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 5588: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   5589: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 5590: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 5591: 		    $updateflag=1;
                   5592: 		}
1.93      albertel 5593: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 5594: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   5595: 	    }
1.44      ng       5596: 	}
1.477     albertel 5597: 	$line.="\n";
1.301     albertel 5598: 
1.44      ng       5599: 	if ($updateflag) {
                   5600: 	    $count++;
1.257     albertel 5601: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 5602: 				    $udom,$uname);
1.301     albertel 5603: 
                   5604: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   5605: 					      $cnum,$udom,$uname)) {
                   5606: 		# need to figure out if should be in queue.
                   5607: 		my %record =  
                   5608: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   5609: 					     $udom,$uname);
                   5610: 		my $all_graded = 1;
                   5611: 		my $none_graded = 1;
1.786     raeburn  5612:                 unless ($got_types) {
                   5613:                     my $error;
                   5614:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   5615:                     unless ($error) {
                   5616:                         foreach my $part (@parts) {
                   5617:                             if (ref($resptype->{$part}) eq 'HASH') {
                   5618:                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   5619:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   5620:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   5621:                                         $queueable{$part} = 1;
                   5622:                                         last;
                   5623:                                     }
                   5624:                                 }
                   5625:                             }
                   5626:                         }
                   5627:                     }
                   5628:                     $got_types = 1;
                   5629:                 }
1.301     albertel 5630: 		foreach my $part (@parts) {
1.786     raeburn  5631:                     if ($queueable{$part}) {
                   5632: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   5633: 			    $all_graded = 0;
                   5634: 		        } else {
                   5635: 			    $none_graded = 0;
                   5636: 		        }
1.301     albertel 5637: 		    }
1.786     raeburn  5638:                 }
1.301     albertel 5639: 		if ($all_graded || $none_graded) {
                   5640: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   5641: 							   $symb,$cdom,$cnum,
                   5642: 							   $udom,$uname);
                   5643: 		}
                   5644: 	    }
                   5645: 
1.477     albertel 5646: 	    $result.=&Apache::loncommon::start_data_table_row().
                   5647: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   5648: 		&Apache::loncommon::end_data_table_row();
1.126     ng       5649: 	    $updateCtr++;
1.798   ! raeburn  5650:             if (keys(%needpb)) {
        !          5651:                 $weights{$symb} = \%weight;
        !          5652:                 &process_passbacks('editgrades',[$symb],$cdom,$cnum,$udom,$uname,\%weights,
        !          5653:                                    \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
        !          5654:             }
1.93      albertel 5655: 	} else {
1.477     albertel 5656: 	    push(@noupdate,
                   5657: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       5658: 	    $noupdateCtr++;
1.44      ng       5659: 	}
1.269     raeburn  5660:         if ($aggregateflag) {
                   5661:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 5662: 				  $cdom,$cnum);
1.269     raeburn  5663:         }
1.93      albertel 5664:     }
1.477     albertel 5665:     if (@noupdate) {
1.748     raeburn  5666:         my $numcols=$totcolspan+2;
1.477     albertel 5667: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 5668: 	    '<td align="center" colspan="'.$numcols.'">'.
                   5669: 	    &mt('No Changes Occurred For the Students Below').
                   5670: 	    '</td>'.
1.477     albertel 5671: 	    &Apache::loncommon::end_data_table_row();
                   5672: 	foreach my $line (@noupdate) {
                   5673: 	    $result.=
                   5674: 		&Apache::loncommon::start_data_table_row().
                   5675: 		$line.
                   5676: 		&Apache::loncommon::end_data_table_row();
                   5677: 	}
1.44      ng       5678:     }
1.614     www      5679:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 5680:     my $msg = '<p><b>'.
                   5681: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   5682: 	    $rec_update,$count).'</b><br />'.
                   5683: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   5684: 	'</b></p>';
1.44      ng       5685:     return $title.$msg.$result;
1.5       albertel 5686: }
1.54      albertel 5687: 
                   5688: sub split_part_type {
                   5689:     my ($partstr) = @_;
                   5690:     my ($temp,@allparts)=split(/_/,$partstr);
                   5691:     my $type=pop(@allparts);
1.439     albertel 5692:     my $part=join('_',@allparts);
1.54      albertel 5693:     return ($part,$type);
                   5694: }
                   5695: 
1.44      ng       5696: #------------- end of section for handling grading by section/class ---------
                   5697: #
                   5698: #----------------------------------------------------------------------------
                   5699: 
1.5       albertel 5700: 
1.44      ng       5701: #----------------------------------------------------------------------------
                   5702: #
                   5703: #-------------------------- Next few routines handles grading by csv upload
                   5704: #
                   5705: #--- Javascript to handle csv upload
1.27      albertel 5706: sub csvupload_javascript_reverse_associate {
1.743     raeburn  5707:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5708:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5709:   &js_escape(\$error1);
                   5710:   &js_escape(\$error2);
1.27      albertel 5711:   return(<<ENDPICK);
                   5712:   function verify(vf) {
                   5713:     var foundsomething=0;
                   5714:     var founduname=0;
1.243     albertel 5715:     var foundID=0;
1.743     raeburn  5716:     var foundclicker=0;
1.27      albertel 5717:     for (i=0;i<=vf.nfields.value;i++) {
                   5718:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5719:       if (i==0 && tw!=0) { foundID=1; }
                   5720:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  5721:       if (i==2 && tw!=0) { foundclicker=1; }
                   5722:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 5723:     }
1.743     raeburn  5724:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 5725: 	alert('$error1');
                   5726: 	return;
1.27      albertel 5727:     }
                   5728:     if (foundsomething==0) {
1.246     albertel 5729: 	alert('$error2');
                   5730: 	return;
1.27      albertel 5731:     }
                   5732:     vf.submit();
                   5733:   }
                   5734:   function flip(vf,tf) {
                   5735:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5736:     var i;
                   5737:     for (i=0;i<=vf.nfields.value;i++) {
                   5738:       //can not pick the same destination field for both name and domain
                   5739:       if (((i ==0)||(i ==1)) && 
                   5740:           ((tf==0)||(tf==1)) && 
                   5741:           (i!=tf) &&
                   5742:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5743:         eval('vf.f'+i+'.selectedIndex=0;')
                   5744:       }
                   5745:     }
                   5746:   }
                   5747: ENDPICK
                   5748: }
                   5749: 
                   5750: sub csvupload_javascript_forward_associate {
1.743     raeburn  5751:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5752:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5753:   &js_escape(\$error1);
                   5754:   &js_escape(\$error2);
1.27      albertel 5755:   return(<<ENDPICK);
                   5756:   function verify(vf) {
                   5757:     var foundsomething=0;
                   5758:     var founduname=0;
1.243     albertel 5759:     var foundID=0;
1.743     raeburn  5760:     var foundclicker=0;
1.27      albertel 5761:     for (i=0;i<=vf.nfields.value;i++) {
                   5762:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5763:       if (tw==1) { foundID=1; }
                   5764:       if (tw==2) { founduname=1; }
1.745     raeburn  5765:       if (tw==3) { foundclicker=1; }
1.743     raeburn  5766:       if (tw>4) { foundsomething=1; }
1.27      albertel 5767:     }
1.743     raeburn  5768:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 5769: 	alert('$error1');
                   5770: 	return;
1.27      albertel 5771:     }
                   5772:     if (foundsomething==0) {
1.246     albertel 5773: 	alert('$error2');
                   5774: 	return;
1.27      albertel 5775:     }
                   5776:     vf.submit();
                   5777:   }
                   5778:   function flip(vf,tf) {
                   5779:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5780:     var i;
                   5781:     //can not pick the same destination field twice
                   5782:     for (i=0;i<=vf.nfields.value;i++) {
                   5783:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5784:         eval('vf.f'+i+'.selectedIndex=0;')
                   5785:       }
                   5786:     }
                   5787:   }
                   5788: ENDPICK
                   5789: }
                   5790: 
1.26      albertel 5791: sub csvuploadmap_header {
1.324     albertel 5792:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       5793:     my $javascript;
1.257     albertel 5794:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       5795: 	$javascript=&csvupload_javascript_reverse_associate();
                   5796:     } else {
                   5797: 	$javascript=&csvupload_javascript_forward_associate();
                   5798:     }
1.45      ng       5799: 
1.418     albertel 5800:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      5801:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   5802:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   5803:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   5804:     my $reverse=&mt("Reverse Association");
1.41      ng       5805:     $request->print(<<ENDPICK);
1.632     www      5806: <br />
                   5807: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 5808: <input type="hidden" name="associate"  value="" />
                   5809: <input type="hidden" name="phase"      value="three" />
                   5810: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 5811: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   5812: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 5813: <input type="hidden" name="upfile_associate" 
1.257     albertel 5814:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 5815: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 5816: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 5817: <hr />
                   5818: ENDPICK
1.597     wenzelju 5819:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       5820:     return '';
1.26      albertel 5821: 
                   5822: }
                   5823: 
                   5824: sub csvupload_fields {
1.582     raeburn  5825:     my ($symb,$errorref) = @_;
1.745     raeburn  5826:     my $toolsymb;
                   5827:     if ($symb =~ /ext\.tool$/) {
                   5828:         $toolsymb = $symb;
                   5829:     }
1.582     raeburn  5830:     my (@parts) = &getpartlist($symb,$errorref);
                   5831:     if (ref($errorref)) {
                   5832:         if ($$errorref) {
                   5833:             return;
                   5834:         }
                   5835:     }
                   5836: 
1.556     weissno  5837:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 5838: 		['username','Student Username'],
1.743     raeburn  5839: 		['clicker','Clicker ID'],
1.243     albertel 5840: 		['domain','Student Domain']);
1.324     albertel 5841:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       5842:     foreach my $part (sort(@parts)) {
                   5843: 	my @datum;
1.745     raeburn  5844: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       5845: 	my $name=$part;
1.745     raeburn  5846: 	if (!$display) { $display = $name; }
1.41      ng       5847: 	@datum=($name,$display);
1.244     albertel 5848: 	if ($name=~/^stores_(.*)_awarded/) {
                   5849: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   5850: 	}
1.41      ng       5851: 	push(@fields,\@datum);
                   5852:     }
                   5853:     return (@fields);
1.26      albertel 5854: }
                   5855: 
                   5856: sub csvuploadmap_footer {
1.41      ng       5857:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   5858:     my $buttontext = &mt('Assign Grades');
1.41      ng       5859:     $request->print(<<ENDPICK);
1.26      albertel 5860: </table>
                   5861: <input type="hidden" name="nfields" value="$i" />
                   5862: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   5863: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 5864: </form>
                   5865: ENDPICK
                   5866: }
                   5867: 
1.283     albertel 5868: sub checkforfile_js {
1.638     www      5869:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  5870:     &js_escape(\$alertmsg);
1.597     wenzelju 5871:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       5872:     function checkUpload(formname) {
                   5873: 	if (formname.upfile.value == "") {
1.539     riegler  5874: 	    alert("$alertmsg");
1.86      ng       5875: 	    return false;
                   5876: 	}
                   5877: 	formname.submit();
                   5878:     }
                   5879: CSVFORMJS
1.283     albertel 5880:     return $result;
                   5881: }
                   5882: 
                   5883: sub upcsvScores_form {
1.608     www      5884:     my ($request,$symb) = @_;
1.283     albertel 5885:     if (!$symb) {return '';}
                   5886:     my $result=&checkforfile_js();
1.632     www      5887:     $result.=&Apache::loncommon::start_data_table().
                   5888:              &Apache::loncommon::start_data_table_header_row().
                   5889:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   5890:              &Apache::loncommon::end_data_table_header_row().
                   5891:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      5892:     my $upload=&mt("Upload Scores");
1.86      ng       5893:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 5894:     my $ignore=&mt('Ignore First Line');
1.418     albertel 5895:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       5896:     $result.=<<ENDUPFORM;
1.106     albertel 5897: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       5898: <input type="hidden" name="symb" value="$symb" />
                   5899: <input type="hidden" name="command" value="csvuploadmap" />
                   5900: $upfile_select
1.589     bisitz   5901: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       5902: </form>
                   5903: ENDUPFORM
1.370     www      5904:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      5905:                            &mt("How do I create a CSV file from a spreadsheet")).
                   5906:              '</td>'.
                   5907:             &Apache::loncommon::end_data_table_row().
                   5908:             &Apache::loncommon::end_data_table();
1.86      ng       5909:     return $result;
                   5910: }
                   5911: 
                   5912: 
1.26      albertel 5913: sub csvuploadmap {
1.768     raeburn  5914:     my ($request,$symb) = @_;
1.41      ng       5915:     if (!$symb) {return '';}
1.72      ng       5916: 
1.41      ng       5917:     my $datatoken;
1.257     albertel 5918:     if (!$env{'form.datatoken'}) {
1.41      ng       5919: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 5920:     } else {
1.742     raeburn  5921: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5922:         if ($datatoken ne '') {
                   5923: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5924:         }
1.26      albertel 5925:     }
1.41      ng       5926:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 5927:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       5928:     my ($i,$keyfields);
                   5929:     if (@records) {
1.582     raeburn  5930:         my $fieldserror;
                   5931: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   5932:         if ($fieldserror) {
                   5933:             $request->print(&navmap_errormsg());
                   5934:             return;
                   5935:         }
1.257     albertel 5936: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       5937: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   5938: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   5939: 							  \@fields);
                   5940: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   5941: 	    chop($keyfields);
                   5942: 	} else {
                   5943: 	    unshift(@fields,['none','']);
                   5944: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   5945: 							    \@fields);
1.311     banghart 5946:             foreach my $rec (@records) {
                   5947:                 my %temp = &Apache::loncommon::record_sep($rec);
                   5948:                 if (%temp) {
                   5949:                     $keyfields=join(',',sort(keys(%temp)));
                   5950:                     last;
                   5951:                 }
                   5952:             }
1.41      ng       5953: 	}
                   5954:     }
                   5955:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       5956: 
1.41      ng       5957:     return '';
1.27      albertel 5958: }
                   5959: 
1.246     albertel 5960: sub csvuploadoptions {
1.608     www      5961:     my ($request,$symb)= @_;
1.632     www      5962:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 5963:     $request->print(<<ENDPICK);
                   5964: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   5965: <input type="hidden" name="command"    value="csvuploadassign" />
                   5966: <p>
                   5967: <label>
                   5968:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      5969:    $overwrite
1.246     albertel 5970: </label>
                   5971: </p>
                   5972: ENDPICK
                   5973:     my %fields=&get_fields();
                   5974:     if (!defined($fields{'domain'})) {
1.257     albertel 5975: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      5976: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 5977:     }
1.257     albertel 5978:     foreach my $key (sort(keys(%env))) {
1.246     albertel 5979: 	if ($key !~ /^form\.(.*)$/) { next; }
                   5980: 	my $cleankey=$1;
                   5981: 	if ($cleankey eq 'command') { next; }
                   5982: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 5983: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 5984:     }
                   5985:     # FIXME do a check for any duplicated user ids...
                   5986:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   5987:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 5988: <hr /></form>'."\n");
1.246     albertel 5989:     return '';
                   5990: }
                   5991: 
                   5992: sub get_fields {
                   5993:     my %fields;
1.257     albertel 5994:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   5995:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   5996: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   5997: 	    if ($env{'form.f'.$i} ne 'none') {
                   5998: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       5999: 	    }
                   6000: 	} else {
1.257     albertel 6001: 	    if ($env{'form.f'.$i} ne 'none') {
                   6002: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       6003: 	    }
                   6004: 	}
1.27      albertel 6005:     }
1.246     albertel 6006:     return %fields;
                   6007: }
                   6008: 
                   6009: sub csvuploadassign {
1.766     raeburn  6010:     my ($request,$symb) = @_;
1.246     albertel 6011:     if (!$symb) {return '';}
1.345     bowersj2 6012:     my $error_msg = '';
1.742     raeburn  6013:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   6014:     if ($datatoken ne '') { 
                   6015:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   6016:     }
1.246     albertel 6017:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   6018:     my %fields=&get_fields();
1.257     albertel 6019:     my $courseid=$env{'request.course.id'};
1.798   ! raeburn  6020:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          6021:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.97      albertel 6022:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 6023:     my @notallowed;
1.41      ng       6024:     my @skipped;
1.657     raeburn  6025:     my @warnings;
1.41      ng       6026:     my $countdone=0;
1.798   ! raeburn  6027:     my @parts;
        !          6028:     my %needpb = &passbacks_for_symb($cdom,$cnum,$symb);
        !          6029:     my $passback;
        !          6030:     if (keys(%needpb)) {
        !          6031:         $passback = 1;
        !          6032:         my $navmap = Apache::lonnavmaps::navmap->new();
        !          6033:         if (ref($navmap)) {
        !          6034:             my $res = $navmap->getBySymb($symb);
        !          6035:             if (ref($res)) {
        !          6036:                 my $partlist = $res->parts();
        !          6037:                 if (ref($partlist) eq 'ARRAY') {
        !          6038:                     @parts = sort(@{$partlist});
        !          6039:                 }
        !          6040:             }
        !          6041:         } else {
        !          6042:             return &navmap_errormsg();
        !          6043:         }
        !          6044:     }
        !          6045:     my (%skip_passback,%pbsave,%weights,%awardeds,%excuseds);
        !          6046: 
1.41      ng       6047:     foreach my $grade (@gradedata) {
                   6048: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 6049: 	my $domain;
                   6050: 	if ($entries{$fields{'domain'}}) {
                   6051: 	    $domain=$entries{$fields{'domain'}};
                   6052: 	} else {
1.257     albertel 6053: 	    $domain=$env{'form.default_domain'};
1.246     albertel 6054: 	}
1.243     albertel 6055: 	$domain=~s/\s//g;
1.41      ng       6056: 	my $username=$entries{$fields{'username'}};
1.160     albertel 6057: 	$username=~s/\s//g;
1.243     albertel 6058: 	if (!$username) {
                   6059: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 6060: 	    $id=~s/\s//g;
1.737     raeburn  6061:             if ($id ne '') {
                   6062: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   6063: 	        $username=$ids{$id};
                   6064:             } else {
                   6065:                 if ($entries{$fields{'clicker'}}) {
                   6066:                     my $clicker = $entries{$fields{'clicker'}};
                   6067:                     $clicker=~s/\s//g;
                   6068:                     if ($clicker ne '') {
                   6069:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   6070:                         if ($clickers{$clicker} ne '') {  
                   6071:                             my $match = 0;
                   6072:                             my @inclass;
                   6073:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   6074:                                 if (exists($$classlist{"$poss:$domain"})) {
                   6075:                                     $username = $poss;
                   6076:                                     push(@inclass,$poss);
                   6077:                                     $match ++;
                   6078:                                     
                   6079:                                 }
                   6080:                             }
                   6081:                             if ($match > 1) {
                   6082:                                 undef($username); 
                   6083:                                 $request->print('<p class="LC_warning">'.
                   6084:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   6085:                                                 $clicker,join(', ',@inclass)).'</p>');
                   6086:                             }
                   6087:                         }
                   6088:                     }
                   6089:                 }
                   6090:             }
1.243     albertel 6091: 	}
1.41      ng       6092: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 6093: 	    my $id=$entries{$fields{'ID'}};
                   6094: 	    $id=~s/\s//g;
1.737     raeburn  6095:             my $clicker = $entries{$fields{'clicker'}};
                   6096:             $clicker=~s/\s//g;
                   6097:             if ($clicker) {
                   6098:                 push(@skipped,"$clicker:$domain");
                   6099: 	    } elsif ($id) {
1.247     albertel 6100: 		push(@skipped,"$id:$domain");
                   6101: 	    } else {
                   6102: 		push(@skipped,"$username:$domain");
                   6103: 	    }
1.41      ng       6104: 	    next;
                   6105: 	}
1.108     albertel 6106: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 6107: 	if (!&canmodify($usec)) {
                   6108: 	    push(@notallowed,"$username:$domain");
                   6109: 	    next;
                   6110: 	}
1.244     albertel 6111: 	my %points;
1.41      ng       6112: 	my %grades;
                   6113: 	foreach my $dest (keys(%fields)) {
1.244     albertel 6114: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   6115: 		$dest eq 'domain') { next; }
                   6116: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   6117: 	    if ($dest=~/stores_(.*)_points/) {
                   6118: 		my $part=$1;
                   6119: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   6120: 					      $symb,$domain,$username);
1.798   ! raeburn  6121:                 $weights{$symb}{$part} = $wgt;
1.345     bowersj2 6122:                 if ($wgt) {
                   6123:                     $entries{$fields{$dest}}=~s/\s//g;
                   6124:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.798   ! raeburn  6125:                     if ($passback) {
        !          6126:                         $awardeds{$symb}{$part} = $pcr;
        !          6127:                         $excuseds{$symb}{$part} = '';
        !          6128:                     }
1.463     albertel 6129:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   6130:                                           : 'correct_by_override';
1.638     www      6131:                     if ($pcr>1) {
1.657     raeburn  6132:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      6133:                     }
1.345     bowersj2 6134:                     $grades{"resource.$part.awarded"}=$pcr;
                   6135:                     $grades{"resource.$part.solved"}=$award;
                   6136:                     $points{$part}=1;
                   6137:                 } else {
                   6138:                     $error_msg = "<br />" .
                   6139:                         &mt("Some point values were assigned"
                   6140:                             ." for problems with a weight "
                   6141:                             ."of zero. These values were "
                   6142:                             ."ignored.");
                   6143:                 }
1.244     albertel 6144: 	    } else {
                   6145: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   6146: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   6147: 		my $store_key=$dest;
1.798   ! raeburn  6148:                 if ($passback) {
        !          6149:                     if ($store_key=~/stores_(.*)_(awarded|solved)/) {
        !          6150:                         my ($part,$key) = ($1,$2);
        !          6151:                         unless ((ref($weights{$symb}) eq 'HASH') && (exists($weights{$symb}{$part}))) {
        !          6152:                             $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
        !          6153:                                                                           $symb,$domain,$username);
        !          6154:                         }
        !          6155:                         if ($key eq 'awarded') {
        !          6156:                             $awardeds{$symb}{$part} = $entries{$fields{$dest}};
        !          6157:                         } elsif ($key eq 'solved') {
        !          6158:                             if ($entries{$fields{$dest}} =~ /^excused/) {
        !          6159:                                 $excuseds{$symb}{$part} = 1;
        !          6160:                             }
        !          6161:                         }
        !          6162:                     }
        !          6163:                 }
1.244     albertel 6164: 		$store_key=~s/^stores/resource/;
                   6165: 		$store_key=~s/_/\./g;
                   6166: 		$grades{$store_key}=$entries{$fields{$dest}};
                   6167: 	    }
1.41      ng       6168: 	}
1.766     raeburn  6169: 	if (! %grades) {
1.508     www      6170:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   6171:         } else {
                   6172: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   6173: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 6174: 					   $env{'request.course.id'},
                   6175: 					   $domain,$username);
1.508     www      6176: 	   if ($result eq 'ok') {
1.627     www      6177: # Successfully stored
1.508     www      6178: 	      $request->print('.');
1.627     www      6179: # Remove from grading queue
1.798   ! raeburn  6180:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,$cnum,
1.627     www      6181:                                              $domain,$username);
                   6182:               $countdone++;
1.798   ! raeburn  6183:               if ($passback) {
        !          6184:                   my @parts_in_upload;
        !          6185:                   if (ref($weights{$symb}) eq 'HASH') {
        !          6186:                       @parts_in_upload = sort(keys(%{$weights{$symb}}));
        !          6187:                   }
        !          6188:                   my @diffs = &Apache::loncommon::compare_arrays(\@parts_in_upload,\@parts);
        !          6189:                   if (@diffs > 0) {
        !          6190:                       my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$username);
        !          6191:                       foreach my $part (@parts) {
        !          6192:                           next if (grep(/^\Q$part\E$/,@parts_in_upload));
        !          6193:                           $weights{$symb}{$part} = &Apache::lonnet::EXT('resource.'.$part.'.weight',
        !          6194:                                                                         $symb,$domain,$username);
        !          6195:                           if ($record{"resource.$part.solved"} =~/^excused/) {
        !          6196:                               $excuseds{$symb}{$part} = 1;
        !          6197:                           } else {
        !          6198:                               $excuseds{$symb}{$part} = '';
        !          6199:                           }
        !          6200:                           $awardeds{$symb}{$part} = $record{"resource.$part.awarded"};
        !          6201:                       }
        !          6202:                   }
        !          6203:                   &process_passbacks('csvupload',[$symb],$cdom,$cnum,$domain,$username,\%weights,
        !          6204:                                      \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave);
        !          6205:               }
1.627     www      6206:            } else {
1.508     www      6207: 	      $request->print("<p><span class=\"LC_error\">".
                   6208:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   6209:                                   "$username:$domain",$result)."</span></p>");
                   6210: 	   }
                   6211: 	   $request->rflush();
                   6212:         }
1.41      ng       6213:     }
1.570     www      6214:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  6215:     if (@warnings) {
                   6216:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   6217:         $request->print(join(', ',@warnings));
                   6218:     }
1.41      ng       6219:     if (@skipped) {
1.571     www      6220: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   6221:         $request->print(join(', ',@skipped));
1.106     albertel 6222:     }
                   6223:     if (@notallowed) {
1.571     www      6224: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   6225: 	$request->print(join(', ',@notallowed));
1.41      ng       6226:     }
1.106     albertel 6227:     $request->print("<br />\n");
1.345     bowersj2 6228:     return $error_msg;
1.26      albertel 6229: }
1.44      ng       6230: #------------- end of section for handling csv file upload ---------
                   6231: #
                   6232: #-------------------------------------------------------------------
                   6233: #
1.122     ng       6234: #-------------- Next few routines handle grading by page/sequence
1.72      ng       6235: #
                   6236: #--- Select a page/sequence and a student to grade
1.68      ng       6237: sub pickStudentPage {
1.608     www      6238:     my ($request,$symb) = @_;
1.68      ng       6239: 
1.539     riegler  6240:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  6241:     &js_escape(\$alertmsg);
1.597     wenzelju 6242:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       6243: 
                   6244: function checkPickOne(formname) {
1.76      ng       6245:     if (radioSelection(formname.student) == null) {
1.539     riegler  6246: 	alert("$alertmsg");
1.68      ng       6247: 	return;
                   6248:     }
1.125     ng       6249:     ptr = pullDownSelection(formname.selectpage);
                   6250:     formname.page.value = formname["page"+ptr].value;
                   6251:     formname.title.value = formname["title"+ptr].value;
1.68      ng       6252:     formname.submit();
                   6253: }
                   6254: 
                   6255: LISTJAVASCRIPT
1.118     ng       6256:     &commonJSfunctions($request);
1.608     www      6257: 
1.257     albertel 6258:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6259:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6260:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  6261:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       6262: 
1.398     albertel 6263:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 6264: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       6265: 
1.80      ng       6266:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  6267:     my $map_error;
                   6268:     my ($titles,$symbx) = &getSymbMap($map_error);
                   6269:     if ($map_error) {
                   6270:         $request->print(&navmap_errormsg());
                   6271:         return; 
                   6272:     }
1.137     albertel 6273:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   6274: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   6275: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   6276: 
                   6277:     # Collection of hidden fields
1.70      ng       6278:     my $ctr=0;
1.68      ng       6279:     foreach (@$titles) {
1.700     bisitz   6280:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   6281:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   6282:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   6283:         $ctr++;
1.68      ng       6284:     }
1.700     bisitz   6285:     $result.='<input type="hidden" name="page" />'."\n".
                   6286:         '<input type="hidden" name="title" />'."\n";
                   6287: 
                   6288:     $result.=&build_section_inputs();
                   6289:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   6290:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   6291: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   6292: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 6293: 
1.700     bisitz   6294:     # Show grading options
                   6295:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   6296:     my $select = '<select name="selectpage">'."\n";
1.70      ng       6297:     $ctr=0;
                   6298:     foreach (@$titles) {
                   6299: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   6300: 	$select.='<option value="'.$ctr.'"'.
                   6301: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   6302: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       6303: 	$ctr++;
                   6304:     }
1.700     bisitz   6305:     $select.= '</select>';
1.68      ng       6306: 
1.700     bisitz   6307:     $result.=
                   6308:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   6309:        .$select
                   6310:        .&Apache::lonhtmlcommon::row_closure();
                   6311: 
                   6312:     $result.=
                   6313:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   6314:        .'<label><input type="radio" name="vProb" value="no"'
                   6315:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   6316:        .'<label><input type="radio" name="vProb" value="yes" />'
                   6317:            .&mt('yes').'</label>'."\n"
                   6318:        .&Apache::lonhtmlcommon::row_closure();
                   6319: 
                   6320:     $result.=
                   6321:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   6322:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   6323:            .&mt('none').' </label>'."\n"
                   6324:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   6325:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   6326:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   6327:            .&mt('all submissions with details').' </label>'
                   6328:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 6329:     
1.700     bisitz   6330:     $result.=
                   6331:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   6332:        .'<input type="text" name="CODE" value="" />'
                   6333:        .&Apache::lonhtmlcommon::row_closure(1)
                   6334:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 6335: 
1.700     bisitz   6336:     # Show list of students to select for grading
                   6337:     $result.='<br /><input type="button" '.
1.589     bisitz   6338:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       6339: 
1.68      ng       6340:     $request->print($result);
                   6341: 
1.485     albertel 6342:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 6343: 	&Apache::loncommon::start_data_table().
                   6344: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6345: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6346: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 6347: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 6348: 	'<th>'.&nameUserString('header').'</th>'.
                   6349: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       6350:  
1.761     raeburn  6351:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       6352:     my $ptr = 1;
1.294     albertel 6353:     foreach my $student (sort 
                   6354: 			 {
                   6355: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   6356: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   6357: 			     }
                   6358: 			     return $a cmp $b;
                   6359: 			 } (keys(%$fullname))) {
1.68      ng       6360: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 6361: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   6362:                                   : '</td>');
1.126     ng       6363: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 6364: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   6365: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 6366: 	$studentTable.=
                   6367: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   6368:                          : '');
1.68      ng       6369: 	$ptr++;
                   6370:     }
1.484     albertel 6371:     if ($ptr%2 == 0) {
                   6372: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   6373: 	    &Apache::loncommon::end_data_table_row();
                   6374:     }
                   6375:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       6376:     $studentTable.='<input type="button" '.
1.589     bisitz   6377:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       6378: 
                   6379:     $request->print($studentTable);
                   6380: 
                   6381:     return '';
                   6382: }
                   6383: 
                   6384: sub getSymbMap {
1.582     raeburn  6385:     my ($map_error) = @_;
1.132     bowersj2 6386:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6387:     unless (ref($navmap)) {
                   6388:         if (ref($map_error)) {
                   6389:             $$map_error = 'navmap';
                   6390:         }
                   6391:         return;
                   6392:     }
1.68      ng       6393:     my %symbx = ();
                   6394:     my @titles = ();
1.117     bowersj2 6395:     my $minder = 0;
                   6396: 
                   6397:     # Gather every sequence that has problems.
1.240     albertel 6398:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   6399: 					       1,0,1);
1.117     bowersj2 6400:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  6401: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 6402: 	    my $title = $minder.'.'.
                   6403: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   6404: 	    push(@titles, $title); # minder in case two titles are identical
                   6405: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 6406: 	    $minder++;
1.241     albertel 6407: 	}
1.68      ng       6408:     }
                   6409:     return \@titles,\%symbx;
                   6410: }
                   6411: 
1.72      ng       6412: #
                   6413: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       6414: sub displayPage {
1.608     www      6415:     my ($request,$symb) = @_;
1.257     albertel 6416:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6417:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6418:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6419:     my $pageTitle = $env{'form.page'};
1.103     albertel 6420:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6421:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6422:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 6423: 
                   6424:     #need to make sure we have the correct data for later EXT calls, 
                   6425:     #thus invalidate the cache
                   6426:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 6427:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   6428:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 6429:     &Apache::lonnet::clear_EXT_cache_status();
                   6430: 
1.103     albertel 6431:     if (!&canview($usec)) {
1.712     bisitz   6432:         $request->print(
                   6433:             '<span class="LC_warning">'.
                   6434:             &mt('Unable to view requested student. ([_1])',
                   6435:                     $env{'form.student'}).
                   6436:             '</span>');
                   6437:         return;
1.103     albertel 6438:     }
1.398     albertel 6439:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 6440:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       6441: 	'</h3>'."\n";
1.500     albertel 6442:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     6443:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 6444: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 6445:     } else {
                   6446: 	delete($env{'form.CODE'});
                   6447:     }
1.71      ng       6448:     &sub_page_js($request);
                   6449:     $request->print($result);
                   6450: 
1.132     bowersj2 6451:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6452:     unless (ref($navmap)) {
                   6453:         $request->print(&navmap_errormsg());
                   6454:         return;
                   6455:     }
1.257     albertel 6456:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       6457:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6458:     if (!$map) {
1.485     albertel 6459: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 6460: 	return; 
                   6461:     }
1.68      ng       6462:     my $iterator = $navmap->getIterator($map->map_start(),
                   6463: 					$map->map_finish());
                   6464: 
1.71      ng       6465:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       6466: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 6467: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   6468: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       6469: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 6470: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 6471: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      6472: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       6473: 
1.382     albertel 6474:     if (defined($env{'form.CODE'})) {
                   6475: 	$studentTable.=
                   6476: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   6477:     }
1.381     albertel 6478:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 6479: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       6480: 
1.594     bisitz   6481:     $studentTable.='&nbsp;<span class="LC_info">'.
                   6482:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   6483:         '</span>'."\n".
1.484     albertel 6484: 	&Apache::loncommon::start_data_table().
                   6485: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   6486: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 6487: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 6488: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6489: 
1.329     albertel 6490:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 6491:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       6492:     $iterator->next(); # skip the first BEGIN_MAP
                   6493:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 6494:     while ($depth > 0) {
1.68      ng       6495:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6496:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       6497: 
1.745     raeburn  6498:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 6499: 	    my $parts = $curRes->parts();
1.68      ng       6500:             my $title = $curRes->compTitle();
1.71      ng       6501: 	    my $symbx = $curRes->symb();
1.746     raeburn  6502:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 6503: 	    $studentTable.=
                   6504: 		&Apache::loncommon::start_data_table_row().
                   6505: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6506: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  6507: 		                        : '<br />('.&mt('[_1]parts',
                   6508: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 6509: 		 ).
                   6510: 		 '</td>';
1.71      ng       6511: 	    $studentTable.='<td valign="top">';
1.382     albertel 6512: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  6513:             if ($is_tool) {
                   6514:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   6515:             } else {
1.745     raeburn  6516: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   6517: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   6518: 					         undef,'both',\%form);
                   6519: 	        } else {
                   6520: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   6521: 		    $companswer =~ s|<form(.*?)>||g;
                   6522: 		    $companswer =~ s|</form>||g;
                   6523: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   6524: #		        $companswer =~ s/$1/ /ms;
                   6525: #		        $request->print('match='.$1."<br />\n");
                   6526: #		    }
                   6527: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   6528: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   6529: 		}
1.71      ng       6530: 	    }
                   6531: 
1.257     albertel 6532: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       6533: 
1.257     albertel 6534: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       6535: 		if ($record{'version'} eq '') {
1.745     raeburn  6536:                     my $msg = &mt('No recorded submission for this problem.');
                   6537:                     if ($is_tool) {
                   6538:                         $msg = &mt('No recorded transactions for this external tool');
                   6539:                     }
                   6540: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       6541: 		} else {
1.116     ng       6542: 		    my %responseType = ();
                   6543: 		    foreach my $partid (@{$parts}) {
1.147     albertel 6544: 			my @responseIds =$curRes->responseIds($partid);
                   6545: 			my @responseType =$curRes->responseType($partid);
                   6546: 			my %responseIds;
                   6547: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   6548: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   6549: 			}
                   6550: 			$responseType{$partid} = \%responseIds;
1.116     ng       6551: 		    }
1.148     albertel 6552: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       6553: 		}
1.257     albertel 6554: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   6555: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  6556:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       6557: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 6558: 									$env{'request.course.id'},
1.726     raeburn  6559: 									'','.submission',undef,
                   6560:                                                                         $usec,$identifier);
1.71      ng       6561:  
                   6562: 	    }
1.103     albertel 6563: 	    if (&canmodify($usec)) {
1.585     bisitz   6564:             $studentTable.=&gradeBox_start();
1.103     albertel 6565: 		foreach my $partid (@{$parts}) {
                   6566: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   6567: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   6568: 		    $question++;
                   6569: 		}
1.585     bisitz   6570:             $studentTable.=&gradeBox_end();
1.196     albertel 6571: 		$prob++;
1.71      ng       6572: 	    }
                   6573: 	    $studentTable.='</td></tr>';
1.68      ng       6574: 
1.103     albertel 6575: 	}
1.68      ng       6576:         $curRes = $iterator->next();
                   6577:     }
1.780     raeburn  6578:     my $disabled;
                   6579:     unless (&canmodify($usec)) {
                   6580:         $disabled = ' disabled="disabled"';
                   6581:     }
1.68      ng       6582: 
1.589     bisitz   6583:     $studentTable.=
                   6584:         '</table>'."\n".
1.780     raeburn  6585:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   6586:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   6587:         '</form>'."\n";
1.71      ng       6588:     $request->print($studentTable);
                   6589: 
                   6590:     return '';
1.119     ng       6591: }
                   6592: 
                   6593: sub displaySubByDates {
1.148     albertel 6594:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 6595:     my $isCODE=0;
1.335     albertel 6596:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  6597:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 6598:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 6599:     my $studentTable=&Apache::loncommon::start_data_table().
                   6600: 	&Apache::loncommon::start_data_table_header_row().
                   6601: 	'<th>'.&mt('Date/Time').'</th>'.
                   6602: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  6603:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  6604: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 6605: 	'<th>'.&mt('Status').'</th>'.
                   6606: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       6607:     my ($version);
                   6608:     my %mark;
1.148     albertel 6609:     my %orders;
1.119     ng       6610:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 6611:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  6612:         if ($is_tool) {
                   6613:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   6614:         } else {
                   6615:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   6616:         }
1.147     albertel 6617:     }
1.335     albertel 6618: 
                   6619:     my $interaction;
1.525     raeburn  6620:     my $no_increment = 1;
1.735     raeburn  6621:     my (%lastrndseed,%lasttype);
1.119     ng       6622:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 6623: 	my $timestamp = 
                   6624: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 6625: 	if (exists($$record{$version.':resource.0.version'})) {
                   6626: 	    $interaction = $$record{$version.':resource.0.version'};
                   6627: 	}
1.671     raeburn  6628:         if ($isTask && $env{'form.previousversion'}) {
                   6629:             next unless ($interaction == $env{'form.previousversion'});
                   6630:         }
1.335     albertel 6631: 	my $where = ($isTask ? "$version:resource.$interaction"
                   6632: 		             : "$version:resource");
1.467     albertel 6633: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   6634: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 6635: 	if ($isCODE) {
                   6636: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   6637: 	}
1.671     raeburn  6638:         if ($isTask) {
                   6639:             $studentTable.='<td>'.$interaction.'</td>';
                   6640:         }
1.119     ng       6641: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   6642: 	my @displaySub = ();
                   6643: 	foreach my $partid (@{$parts}) {
1.640     raeburn  6644:             my ($hidden,$type);
                   6645:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   6646:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  6647:                 $hidden = 1;
                   6648:             }
1.749     raeburn  6649:             my @matchKey;
                   6650:             if ($isTask) {
1.769     raeburn  6651:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  6652:             } elsif ($is_tool) {
1.769     raeburn  6653:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  6654:             } else {
1.769     raeburn  6655:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  6656:             }
1.122     ng       6657: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 6658: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 6659: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 6660: 		if (exists($$record{$version.':'.$matchKey}) &&
                   6661: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  6662:                     if ($is_tool) {
                   6663:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  6664:                     } else {
1.749     raeburn  6665: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   6666: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   6667:                         $displaySub[0].='<span class="LC_nobreak">';
                   6668:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   6669:                                        .' <span class="LC_internal_info">'
                   6670:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   6671:                                        .'</span>'
                   6672:                                        .' <b>';
                   6673:                         if ($hidden) {
                   6674:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   6675:                         } else {
                   6676:                             my ($trial,$rndseed,$newvariation);
                   6677:                             if ($type eq 'randomizetry') {
                   6678:                                 $trial = $$record{"$where.$partid.tries"};
                   6679:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   6680:                             }
                   6681: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   6682: 			        $displaySub[0].=&mt('Trial not counted');
                   6683: 		            } else {
                   6684: 			        $displaySub[0].=&mt('Trial: [_1]',
                   6685: 					        $$record{"$where.$partid.tries"});
                   6686:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   6687:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   6688:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   6689:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   6690:                                     }
1.640     raeburn  6691:                                 }
1.749     raeburn  6692:                                 $lastrndseed{$partid} = $rndseed;
                   6693:                                 $lasttype{$partid} = $type;
                   6694: 		            }
                   6695: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 6696:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  6697: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   6698: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   6699: 			        $orders{$partid}->{$responseId}=
                   6700: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   6701:                                                $no_increment,$type,$trial,$rndseed);
                   6702: 		            }
                   6703: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   6704: 		            $displaySub[0].='&nbsp; '.
                   6705: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   6706:                         }
1.596     raeburn  6707:                     }
1.147     albertel 6708: 		}
                   6709: 	    }
1.335     albertel 6710: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 6711: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   6712: 				    $$record{"$where.$partid.checkedin"},
                   6713: 				    $$record{"$where.$partid.checkedin.slot"}).
                   6714: 					'<br />';
1.335     albertel 6715: 	    }
                   6716: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 6717: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 6718: 		    lc($$record{"$where.$partid.award"}).' '.
                   6719: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 6720: 		    '<br />';
1.749     raeburn  6721: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   6722: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   6723: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   6724: 		}
1.147     albertel 6725: 	    }
1.335     albertel 6726: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  6727: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   6728: 		unless ($is_tool) {
                   6729: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6730: 		}
1.335     albertel 6731: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   6732: 		$displaySub[2].=
1.749     raeburn  6733: 		    $$record{"$version:resource.$partid.regrader"};
                   6734:                 unless ($is_tool) {
                   6735: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6736:                 }
1.147     albertel 6737: 	    }
                   6738: 	}
                   6739: 	# needed because old essay regrader has not parts info
                   6740: 	if (exists $$record{"$version:resource.regrader"}) {
                   6741: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   6742: 	}
                   6743: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   6744: 	if ($displaySub[2]) {
1.467     albertel 6745: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 6746: 	}
1.467     albertel 6747: 	$studentTable.='&nbsp;</td>'.
                   6748: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       6749:     }
1.467     albertel 6750:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       6751:     return $studentTable;
1.71      ng       6752: }
                   6753: 
                   6754: sub updateGradeByPage {
1.608     www      6755:     my ($request,$symb) = @_;
1.71      ng       6756: 
1.257     albertel 6757:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6758:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6759:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6760:     my $pageTitle = $env{'form.page'};
1.103     albertel 6761:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6762:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6763:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 6764:     if (!&canmodify($usec)) {
1.526     raeburn  6765: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 6766: 	return;
                   6767:     }
1.398     albertel 6768:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  6769:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       6770: 	'</h3>'."\n";
1.70      ng       6771: 
1.68      ng       6772:     $request->print($result);
                   6773: 
1.582     raeburn  6774: 
1.132     bowersj2 6775:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6776:     unless (ref($navmap)) {
                   6777:         $request->print(&navmap_errormsg());
                   6778:         return;
                   6779:     }
1.257     albertel 6780:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       6781:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6782:     if (!$map) {
1.527     raeburn  6783: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 6784: 	return; 
                   6785:     }
1.71      ng       6786:     my $iterator = $navmap->getIterator($map->map_start(),
                   6787: 					$map->map_finish());
1.70      ng       6788: 
1.484     albertel 6789:     my $studentTable=
                   6790: 	&Apache::loncommon::start_data_table().
                   6791: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6792: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   6793: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   6794: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   6795: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 6796: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6797: 
                   6798:     $iterator->next(); # skip the first BEGIN_MAP
                   6799:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  6800:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.798   ! raeburn  6801:     my (@updates,%weights,%excuseds,%awardeds,@symbs_in_map);
1.101     albertel 6802:     while ($depth > 0) {
1.71      ng       6803:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6804:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       6805: 
1.385     albertel 6806:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 6807: 	    my $parts = $curRes->parts();
1.71      ng       6808:             my $title = $curRes->compTitle();
                   6809: 	    my $symbx = $curRes->symb();
1.798   ! raeburn  6810:             push(@symbs_in_map,$symbx);
1.484     albertel 6811: 	    $studentTable.=
                   6812: 		&Apache::loncommon::start_data_table_row().
                   6813: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6814: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  6815:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  6816: 		.')').'</td>';
1.71      ng       6817: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   6818: 
                   6819: 	    my %newrecord=();
                   6820: 	    my @displayPts=();
1.269     raeburn  6821:             my %aggregate = ();
                   6822:             my $aggregateflag = 0;
1.787     raeburn  6823:             my %queueable;
1.726     raeburn  6824:             if ($env{'form.HIDE'.$prob}) {
                   6825:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  6826:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  6827:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.798   ! raeburn  6828:                 if ($numchgs) {
        !          6829:                     push(@updates,$symbx);
        !          6830:                 }
1.726     raeburn  6831:                 $hideflag += $numchgs;
                   6832:             }
1.71      ng       6833: 	    foreach my $partid (@{$parts}) {
1.257     albertel 6834: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   6835: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.787     raeburn  6836:                 my @types = $curRes->responseType($partid);
1.786     raeburn  6837:                 if (grep(/^essay$/,@types)) {
                   6838:                     $queueable{$partid} = 1;
                   6839:                 } else {
1.787     raeburn  6840:                     my @ids = $curRes->responseIds($partid);
1.786     raeburn  6841:                     for (my $i=0; $i < scalar(@ids); $i++) {
1.787     raeburn  6842:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
1.786     raeburn  6843:                                                           '.handgrade',$symb);
                   6844:                         if (lc($hndgrd) eq 'yes') {
                   6845:                             $queueable{$partid} = 1;
                   6846:                             last;
                   6847:                         }
                   6848:                     }
                   6849:                 }
1.257     albertel 6850: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   6851: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.798   ! raeburn  6852:                 $weights{$symbx}{$partid} = $wgt;
        !          6853:                 $excuseds{$symbx}{$partid} = '';
1.71      ng       6854: 		my $partial = $newpts/$wgt;
                   6855: 		my $score;
                   6856: 		if ($partial > 0) {
                   6857: 		    $score = 'correct_by_override';
1.125     ng       6858: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       6859: 		    $score = 'incorrect_by_override';
                   6860: 		}
1.257     albertel 6861: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       6862: 		if ($dropMenu eq 'excused') {
1.71      ng       6863: 		    $partial = '';
                   6864: 		    $score = 'excused';
1.798   ! raeburn  6865:                     $excuseds{$symbx}{$partid} = 1;
1.125     ng       6866: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 6867: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       6868: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   6869: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   6870: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   6871: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 6872: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       6873: 		    $changeflag++;
                   6874: 		    $newpts = '';
1.269     raeburn  6875:                     
                   6876:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   6877:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   6878:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   6879:                     if ($aggtries > 0) {
                   6880:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   6881:                         $aggregateflag = 1;
                   6882:                     }
1.71      ng       6883: 		}
1.324     albertel 6884: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 6885: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  6886: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       6887: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 6888: 		    '&nbsp;<br />';
1.526     raeburn  6889: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       6890: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 6891: 		    '&nbsp;<br />';
1.71      ng       6892: 		$question++;
1.798   ! raeburn  6893:                 if (($newpts eq '') || ($partial eq '')) {
        !          6894:                     $awardeds{$symbx}{$partid} = 0;
        !          6895:                 } else {
        !          6896:                     $awardeds{$symbx}{$partid} = $partial;
        !          6897:                 }
1.380     albertel 6898: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       6899: 
1.71      ng       6900: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       6901: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 6902: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       6903: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       6904: 
                   6905: 		$changeflag++;
                   6906: 	    }
                   6907: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 6908: 		my %record = 
                   6909: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   6910: 					     $udom,$uname);
                   6911: 
                   6912: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   6913: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   6914: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   6915: 		    $newrecord{'resource.CODE'} = '';
                   6916: 		}
1.257     albertel 6917: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       6918: 					$udom,$uname);
1.382     albertel 6919: 		%record = &Apache::lonnet::restore($symbx,
                   6920: 						   $env{'request.course.id'},
                   6921: 						   $udom,$uname);
1.380     albertel 6922: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.786     raeburn  6923: 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       6924: 	    }
1.380     albertel 6925: 	    
1.269     raeburn  6926:             if ($aggregateflag) {
                   6927:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   6928:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   6929:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   6930:             }
1.125     ng       6931: 
1.71      ng       6932: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   6933: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 6934: 		&Apache::loncommon::end_data_table_row();
1.68      ng       6935: 
1.196     albertel 6936: 	    $prob++;
1.798   ! raeburn  6937:             if ($changeflag) {
        !          6938:                 push(@updates,$symbx);
        !          6939:             }
1.68      ng       6940: 	}
1.71      ng       6941:         $curRes = $iterator->next();
1.68      ng       6942:     }
1.98      albertel 6943: 
1.484     albertel 6944:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  6945:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   6946: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  6947: 		  $changeflag).'<br />');
                   6948:     my $hidemsg=($hideflag == 0 ? '' :
                   6949:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   6950:                      $hideflag).'<br />');
                   6951:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       6952: 
1.798   ! raeburn  6953:     if (@updates) {
        !          6954:         undef(@Apache::lonhomework::ltipassback);
        !          6955:         my (@allsymbs,$mapsymb,@recurseup,%parentmapsymbs,%possmappb,%possrespb);
        !          6956:         @allsymbs = @updates;
        !          6957:         if (ref($map)) {
        !          6958:             $mapsymb = $map->symb();
        !          6959:             push(@allsymbs,$mapsymb);
        !          6960:             @recurseup = $navmap->recurseup_maps($map->src,1);
        !          6961:         }
        !          6962:         if (@recurseup) {
        !          6963:             push(@allsymbs,@recurseup);
        !          6964:             map { $parentmapsymbs{$_} = 1; } @recurseup;
        !          6965:         }
        !          6966:         my %passback = &Apache::lonnet::get('nohist_linkprot_passback',\@allsymbs,$cdom,$cnum);
        !          6967:         my (%uniqsymbs,$use_symbs_in_map);
        !          6968:         if (keys(%passback)) {
        !          6969:             foreach my $possible (keys(%passback)) {
        !          6970:                 if (ref($passback{$possible}) eq 'HASH') {
        !          6971:                     if ($possible eq $mapsymb) {
        !          6972:                         foreach my $launcher (keys(%{$passback{$possible}})) {
        !          6973:                             $possmappb{$launcher} = 1;
        !          6974:                         }
        !          6975:                         $use_symbs_in_map = 1;
        !          6976:                     } elsif (exists($parentmapsymbs{$possible})) {
        !          6977:                         foreach my $launcher (keys(%{$passback{$possible}})) {
        !          6978:                             my ($linkuri,$linkprotector,$scope) = split(/\0/,$launcher);
        !          6979:                             if ($scope eq 'rec') {
        !          6980:                                 $possmappb{$launcher} = 1;
        !          6981:                                 $use_symbs_in_map = 1;
        !          6982:                             }
        !          6983:                         }
        !          6984:                     } elsif (grep(/^\Q$possible$\E$/,@updates)) {
        !          6985:                         foreach my $launcher (keys(%{$passback{$possible}})) {
        !          6986:                             $possrespb{$launcher} = 1;
        !          6987:                         }
        !          6988:                         $uniqsymbs{$possible} = 1;
        !          6989:                     }
        !          6990:                 }
        !          6991:             }
        !          6992:         }
        !          6993:         if ($use_symbs_in_map) {
        !          6994:             map { $uniqsymbs{$_} = 1; } @symbs_in_map;
        !          6995:         }
        !          6996:         my @posslaunchers;
        !          6997:         if (keys(%possmappb)) {
        !          6998:             push(@posslaunchers,keys(%possmappb));
        !          6999:         }
        !          7000:         if (keys(%possrespb)) {
        !          7001:             push(@posslaunchers,keys(%possrespb));
        !          7002:         }
        !          7003:         if (@posslaunchers) {
        !          7004:             my (%pbsave,%skip_passback,%needpb);
        !          7005:             my %pbids = &Apache::lonnet::get('nohist_'.$cdom.'_'.$cnum.'_linkprot_pb',\@posslaunchers,$udom,$uname);
        !          7006:             foreach my $key (keys(%pbids)) {
        !          7007:                 if (ref($pbids{$key}) eq 'ARRAY') {
        !          7008:                     $needpb{$key} = 1;
        !          7009:                 }
        !          7010:             }
        !          7011:             my @symbs = keys(%uniqsymbs);
        !          7012:             &process_passbacks('updatebypage',\@symbs,$cdom,$cnum,$udom,$uname,\%weights,
        !          7013:                                \%awardeds,\%excuseds,\%needpb,\%skip_passback,\%pbsave,\%pbids);
        !          7014:             if (@Apache::lonhomework::ltipassback) {
        !          7015:                 unless ($registered_cleanup) {
        !          7016:                     my $handlers = $request->get_handlers('PerlCleanupHandler');
        !          7017:                     $request->set_handlers('PerlCleanupHandler' =>
        !          7018:                                            [\&Apache::lonhomework::do_ltipassback,@{$handlers}]);
        !          7019:                 }
        !          7020:             }
        !          7021:         }
        !          7022:     }
1.70      ng       7023:     return '';
                   7024: }
                   7025: 
1.72      ng       7026: #-------- end of section for handling grading by page/sequence ---------
                   7027: #
                   7028: #-------------------------------------------------------------------
                   7029: 
1.581     www      7030: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 7031: #
                   7032: #------ start of section for handling grading by page/sequence ---------
                   7033: 
1.423     albertel 7034: =pod
                   7035: 
                   7036: =head1 Bubble sheet grading routines
                   7037: 
1.424     albertel 7038:   For this documentation:
                   7039: 
                   7040:    'scanline' refers to the full line of characters
                   7041:    from the file that we are parsing that represents one entire sheet
                   7042: 
                   7043:    'bubble line' refers to the data
1.659     raeburn  7044:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 7045: 
                   7046: 
1.659     raeburn  7047: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 7048: into a course. When a user wants to grade, they select a
1.659     raeburn  7049: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 7050: one of the predefined configurations for what each scanline looks
                   7051: like.
                   7052: 
                   7053: Next each scanline is checked for any errors of either 'missing
1.435     foxr     7054: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 7055: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   7056: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  7057: invalid student/employee ID
1.424     albertel 7058: 
                   7059: If the CODE option is used that determines the randomization of the
1.556     weissno  7060: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 7061: username:domain.
                   7062: 
                   7063: During the validation phase the instructor can choose to skip scanlines. 
                   7064: 
1.659     raeburn  7065: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 7066: 
                   7067:   scantron_original_filename (unmodified original file)
                   7068:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   7069:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   7070: 
                   7071: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  7072: correction information that isn't representable in the bubblesheet
1.424     albertel 7073: file (see &scantron_getfile() for more information)
                   7074: 
                   7075: After all scanlines are either valid, marked as valid or skipped, then
                   7076: foreach line foreach problem in the picked sequence, an ssi request is
                   7077: made that simulates a user submitting their selected letter(s) against
                   7078: the homework problem.
1.423     albertel 7079: 
                   7080: =over 4
                   7081: 
                   7082: 
                   7083: 
                   7084: =item defaultFormData
                   7085: 
                   7086:   Returns html hidden inputs used to hold context/default values.
                   7087: 
                   7088:  Arguments:
                   7089:   $symb - $symb of the current resource 
                   7090: 
                   7091: =cut
1.422     foxr     7092: 
1.81      albertel 7093: sub defaultFormData {
1.324     albertel 7094:     my ($symb)=@_;
1.766     raeburn  7095:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 7096: }
                   7097: 
1.447     foxr     7098: 
1.423     albertel 7099: =pod 
                   7100: 
                   7101: =item getSequenceDropDown
                   7102: 
                   7103:    Return html dropdown of possible sequences to grade
                   7104:  
                   7105:  Arguments:
1.582     raeburn  7106:    $symb - $symb of the current resource
                   7107:    $map_error - ref to scalar which will container error if
                   7108:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 7109: 
                   7110: =cut
1.422     foxr     7111: 
1.75      albertel 7112: sub getSequenceDropDown {
1.582     raeburn  7113:     my ($symb,$map_error)=@_;
1.75      albertel 7114:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  7115:     my ($titles,$symbx) = &getSymbMap($map_error);
                   7116:     if (ref($map_error)) {
                   7117:         return if ($$map_error);
                   7118:     }
1.137     albertel 7119:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 7120:     my $ctr=0;
                   7121:     foreach (@$titles) {
                   7122: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   7123: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 7124: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 7125: 	    '>'.$showtitle.'</option>'."\n";
                   7126: 	$ctr++;
                   7127:     }
                   7128:     $result.= '</select>';
                   7129:     return $result;
                   7130: }
                   7131: 
1.495     albertel 7132: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  7133:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 7134: 
                   7135: my %first_bubble_line;             # First bubble line no. for each bubble.
                   7136: 
1.509     raeburn  7137: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   7138:                                    # matchresponse or rankresponse, where 
                   7139:                                    # an individual response can have multiple 
                   7140:                                    # lines
1.503     raeburn  7141: 
                   7142: my %responsetype_per_response;     # responsetype for each response
                   7143: 
1.691     raeburn  7144: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   7145:                                    # numbered response. Needed when randomorder
                   7146:                                    # or randompick are in use. Key is ID, value 
                   7147:                                    # is response number.
                   7148: 
1.495     albertel 7149: # Save and restore the bubble lines array to the form env.
                   7150: 
                   7151: 
                   7152: sub save_bubble_lines {
                   7153:     foreach my $line (keys(%bubble_lines_per_response)) {
                   7154: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   7155: 	$env{"form.scantron.first_bubble_line.$line"} =
                   7156: 	    $first_bubble_line{$line};
1.503     raeburn  7157:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   7158:             $subdivided_bubble_lines{$line};
                   7159:         $env{"form.scantron.responsetype.$line"} =
                   7160:             $responsetype_per_response{$line};
1.495     albertel 7161:     }
1.691     raeburn  7162:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   7163:         my $line = $masterseq_id_responsenum{$resid};
                   7164:         $env{"form.scantron.residpart.$line"} = $resid;
                   7165:     }
1.495     albertel 7166: }
                   7167: 
                   7168: 
                   7169: sub restore_bubble_lines {
                   7170:     my $line = 0;
                   7171:     %bubble_lines_per_response = ();
1.691     raeburn  7172:     %masterseq_id_responsenum = ();
1.495     albertel 7173:     while ($env{"form.scantron.bubblelines.$line"}) {
                   7174: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   7175: 	$bubble_lines_per_response{$line} = $value;
                   7176: 	$first_bubble_line{$line}  =
                   7177: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  7178:         $subdivided_bubble_lines{$line} =
                   7179:             $env{"form.scantron.sub_bubblelines.$line"};
                   7180:         $responsetype_per_response{$line} =
                   7181:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  7182:         my $id = $env{"form.scantron.residpart.$line"};
                   7183:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 7184: 	$line++;
                   7185:     }
                   7186: }
                   7187: 
1.423     albertel 7188: =pod 
                   7189: 
                   7190: =item scantron_filenames
                   7191: 
                   7192:    Returns a list of the scantron files in the current course 
                   7193: 
                   7194: =cut
1.422     foxr     7195: 
1.202     albertel 7196: sub scantron_filenames {
1.257     albertel 7197:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7198:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  7199:     my $getpropath = 1;
1.662     raeburn  7200:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   7201:                                                         $cname,$getpropath);
1.202     albertel 7202:     my @possiblenames;
1.662     raeburn  7203:     if (ref($dirlist) eq 'ARRAY') {
                   7204:         foreach my $filename (sort(@{$dirlist})) {
                   7205: 	    ($filename)=split(/&/,$filename);
                   7206: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   7207: 	    $filename=~s/^scantron_orig_//;
                   7208: 	    push(@possiblenames,$filename);
                   7209:         }
1.202     albertel 7210:     }
                   7211:     return @possiblenames;
                   7212: }
                   7213: 
1.423     albertel 7214: =pod 
                   7215: 
                   7216: =item scantron_uploads
                   7217: 
                   7218:    Returns  html drop-down list of scantron files in current course.
                   7219: 
                   7220:  Arguments:
                   7221:    $file2grade - filename to set as selected in the dropdown
                   7222: 
                   7223: =cut
1.422     foxr     7224: 
1.202     albertel 7225: sub scantron_uploads {
1.209     ng       7226:     my ($file2grade) = @_;
1.202     albertel 7227:     my $result=	'<select name="scantron_selectfile">';
                   7228:     $result.="<option></option>";
                   7229:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 7230: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 7231:     }
                   7232:     $result.="</select>";
                   7233:     return $result;
                   7234: }
                   7235: 
1.423     albertel 7236: =pod 
                   7237: 
                   7238: =item scantron_scantab
                   7239: 
                   7240:   Returns html drop down of the scantron formats in the scantronformat.tab
                   7241:   file.
                   7242: 
                   7243: =cut
1.422     foxr     7244: 
1.82      albertel 7245: sub scantron_scantab {
                   7246:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 7247:     $result.='<option></option>'."\n";
1.754     raeburn  7248:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  7249:     if (@lines > 0) {
                   7250:         foreach my $line (@lines) {
                   7251:             next if (($line =~ /^\#/) || ($line eq ''));
                   7252: 	    my ($name,$descrip)=split(/:/,$line);
                   7253: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   7254:         }
1.82      albertel 7255:     }
                   7256:     $result.='</select>'."\n";
1.518     raeburn  7257:     return $result;
                   7258: }
                   7259: 
1.423     albertel 7260: =pod 
                   7261: 
                   7262: =item scantron_CODElist
                   7263: 
                   7264:   Returns html drop down of the saved CODE lists from current course,
                   7265:   generated from earlier printings.
                   7266: 
                   7267: =cut
1.422     foxr     7268: 
1.186     albertel 7269: sub scantron_CODElist {
1.257     albertel 7270:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7271:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 7272:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   7273:     my $namechoice='<option></option>';
1.225     albertel 7274:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 7275: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 7276: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 7277: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   7278:     }
                   7279:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   7280:     return $namechoice;
                   7281: }
                   7282: 
1.423     albertel 7283: =pod 
                   7284: 
                   7285: =item scantron_CODEunique
                   7286: 
                   7287:   Returns the html for "Each CODE to be used once" radio.
                   7288: 
                   7289: =cut
1.422     foxr     7290: 
1.186     albertel 7291: sub scantron_CODEunique {
1.532     bisitz   7292:     my $result='<span class="LC_nobreak">
1.272     albertel 7293:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7294:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 7295:                 </span>
1.532     bisitz   7296:                 <span class="LC_nobreak">
1.272     albertel 7297:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 7298:                         value="no" />'.&mt('No').' </label>
1.381     albertel 7299:                 </span>';
1.186     albertel 7300:     return $result;
                   7301: }
1.423     albertel 7302: 
                   7303: =pod 
                   7304: 
                   7305: =item scantron_selectphase
                   7306: 
1.659     raeburn  7307:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 7308:   Allows for - starting a grading run.
1.424     albertel 7309:              - downloading existing scan data (original, corrected
1.423     albertel 7310:                                                 or skipped info)
                   7311: 
                   7312:              - uploading new scan data
                   7313: 
                   7314:  Arguments:
                   7315:   $r          - The Apache request object
                   7316:   $file2grade - name of the file that contain the scanned data to score
                   7317: 
                   7318: =cut
1.186     albertel 7319: 
1.75      albertel 7320: sub scantron_selectphase {
1.608     www      7321:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 7322:     if (!$symb) {return '';}
1.582     raeburn  7323:     my $map_error;
                   7324:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   7325:     if ($map_error) {
                   7326:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   7327:         return;
                   7328:     }
1.324     albertel 7329:     my $default_form_data=&defaultFormData($symb);
1.209     ng       7330:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 7331:     my $format_selector=&scantron_scantab();
1.186     albertel 7332:     my $CODE_selector=&scantron_CODElist();
                   7333:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 7334:     my $result;
1.422     foxr     7335: 
1.513     foxr     7336:     $ssi_error = 0;
                   7337: 
1.770     raeburn  7338:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 7339: 
                   7340: 	# Chunk of form to prompt for a scantron file upload.
                   7341: 
                   7342:         $r->print('
1.754     raeburn  7343:     <br />');
1.606     wenzelju 7344:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7345:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  7346:     my $csec= $env{'request.course.sec'};
1.736     damieng  7347:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   7348:     &js_escape(\$alertmsg);
1.754     raeburn  7349:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 7350:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   7351:     function checkUpload(formname) {
                   7352: 	if (formname.upfile.value == "") {
1.736     damieng  7353: 	    alert("'.$alertmsg.'");
1.606     wenzelju 7354: 	    return false;
                   7355: 	}
                   7356: 	formname.submit();
1.756     raeburn  7357:     }'."\n".$formatjs));
1.606     wenzelju 7358:     $r->print('
                   7359:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7360:                 '.$default_form_data.'
                   7361:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  7362:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 7363:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   7364:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  7365:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7366:               '.&Apache::loncommon::start_data_table_header_row().'
                   7367:                 <th>
                   7368:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   7369:                 </th>
                   7370:               '.&Apache::loncommon::end_data_table_header_row().'
                   7371:               '.&Apache::loncommon::start_data_table_row().'
                   7372:             <td>
                   7373:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   7374:     if ($formatoptions) {
                   7375:         $r->print('</td>
                   7376:                  '.&Apache::loncommon::end_data_table_row().'
                   7377:                  '.&Apache::loncommon::start_data_table_row().'
                   7378:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   7379:                  </td>
                   7380:                  '.&Apache::loncommon::end_data_table_row().'
                   7381:                  '.&Apache::loncommon::start_data_table_row().'
                   7382:                  <td>'
                   7383:         );
                   7384:     } else {
                   7385:         $r->print(' <br />');
                   7386:     }
                   7387:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   7388:               </td>
                   7389:              '.&Apache::loncommon::end_data_table_row().'
                   7390:              '.&Apache::loncommon::end_data_table().'
                   7391:              </form>'
                   7392:     );
1.606     wenzelju 7393: 
                   7394:     }
                   7395: 
1.422     foxr     7396:     # Chunk of form to prompt for a file to grade and how:
                   7397: 
1.489     albertel 7398:     $result.= '
                   7399:     <br />
                   7400:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   7401:     <input type="hidden" name="command" value="scantron_warning" />
                   7402:     '.$default_form_data.'
                   7403:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7404:        '.&Apache::loncommon::start_data_table_header_row().'
                   7405:             <th colspan="2">
1.492     albertel 7406:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 7407:             </th>
                   7408:        '.&Apache::loncommon::end_data_table_header_row().'
                   7409:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7410:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 7411:        '.&Apache::loncommon::end_data_table_row().'
                   7412:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      7413:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 7414:        '.&Apache::loncommon::end_data_table_row().'
                   7415:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      7416:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 7417:        '.&Apache::loncommon::end_data_table_row().'
                   7418:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7419:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 7420:        '.&Apache::loncommon::end_data_table_row().'
                   7421:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7422:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 7423:        '.&Apache::loncommon::end_data_table_row().'
                   7424:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7425: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 7426:             <td>
1.492     albertel 7427: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   7428:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   7429:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 7430: 	    </td>
1.489     albertel 7431:        '.&Apache::loncommon::end_data_table_row().'
                   7432:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 7433:             <td colspan="2">
1.572     www      7434:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 7435:             </td>
1.489     albertel 7436:        '.&Apache::loncommon::end_data_table_row().'
                   7437:     '.&Apache::loncommon::end_data_table().'
                   7438:     </form>
                   7439: ';
1.162     albertel 7440:    
                   7441:     $r->print($result);
                   7442: 
1.422     foxr     7443:     # Chunk of the form that prompts to view a scoring office file,
                   7444:     # corrected file, skipped records in a file.
                   7445: 
1.489     albertel 7446:     $r->print('
                   7447:    <br />
                   7448:    <form action="/adm/grades" name="scantron_download">
                   7449:      '.$default_form_data.'
                   7450:      <input type="hidden" name="command" value="scantron_download" />
                   7451:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   7452:        '.&Apache::loncommon::start_data_table_header_row().'
                   7453:               <th>
1.492     albertel 7454:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 7455:               </th>
                   7456:        '.&Apache::loncommon::end_data_table_header_row().'
                   7457:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 7458:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 7459:                 <br />
1.492     albertel 7460:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 7461:        '.&Apache::loncommon::end_data_table_row().'
                   7462:      '.&Apache::loncommon::end_data_table().'
                   7463:    </form>
                   7464:    <br />
                   7465: ');
1.162     albertel 7466: 
1.457     banghart 7467:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  7468: 
1.694     bisitz   7469:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  7470:              $default_form_data."\n".
                   7471:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   7472:              &Apache::loncommon::start_data_table_header_row()."\n".
                   7473:              '<th colspan="2">
1.572     www      7474:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  7475:              '</th>'."\n".
                   7476:               &Apache::loncommon::end_data_table_header_row()."\n".
                   7477:               &Apache::loncommon::start_data_table_row()."\n".
                   7478:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   7479:               '<td> '.$sequence_selector.' </td>'.
                   7480:               &Apache::loncommon::end_data_table_row()."\n".
                   7481:               &Apache::loncommon::start_data_table_row()."\n".
                   7482:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   7483:               '<td> '.$file_selector.' </td>'."\n".
                   7484:               &Apache::loncommon::end_data_table_row()."\n".
                   7485:               &Apache::loncommon::start_data_table_row()."\n".
                   7486:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   7487:               '<td> '.$format_selector.' </td>'."\n".
                   7488:               &Apache::loncommon::end_data_table_row()."\n".
                   7489:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  7490:               '<td> '.&mt('Options').' </td>'."\n".
                   7491:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   7492:               &Apache::loncommon::end_data_table_row()."\n".
                   7493:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  7494:               '<td colspan="2">'."\n".
                   7495:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      7496:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  7497:               '</td>'."\n".
                   7498:               &Apache::loncommon::end_data_table_row()."\n".
                   7499:               &Apache::loncommon::end_data_table()."\n".
                   7500:               '</form><br />');
                   7501:     return;
1.75      albertel 7502: }
                   7503: 
1.423     albertel 7504: =pod 
                   7505: 
                   7506: =item username_to_idmap
                   7507: 
1.556     weissno  7508:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  7509:     student username:domain. If a single ID occurs for more than one student,
                   7510:     the status of the student is checked, and if Active, the value in the hash
                   7511:     will be set to the Active student.
1.423     albertel 7512: 
                   7513:   Arguments:
                   7514: 
                   7515:     $classlist - reference to the class list hash. This is a hash
                   7516:                  keyed by student name:domain  whose elements are references
1.424     albertel 7517:                  to arrays containing various chunks of information
1.423     albertel 7518:                  about the student. (See loncoursedata for more info).
                   7519: 
                   7520:   Returns
                   7521:     %idmap - the constructed hash
                   7522: 
                   7523: =cut
                   7524: 
1.82      albertel 7525: sub username_to_idmap {
                   7526:     my ($classlist)= @_;
                   7527:     my %idmap;
                   7528:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  7529:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   7530:         unless ($id eq '') {
                   7531:             if (!exists($idmap{$id})) {
                   7532:                 $idmap{$id} = $student;
                   7533:             } else {
                   7534:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   7535:                 if ($status eq 'Active') {
                   7536:                     $idmap{$id} = $student;
                   7537:                 }
                   7538:             }
                   7539:         }
1.82      albertel 7540:     }
                   7541:     return %idmap;
                   7542: }
1.423     albertel 7543: 
                   7544: =pod
                   7545: 
1.424     albertel 7546: =item scantron_fixup_scanline
1.423     albertel 7547: 
                   7548:    Process a requested correction to a scanline.
                   7549: 
                   7550:   Arguments:
1.754     raeburn  7551:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 7552:     $scan_data         - hash of correction information 
                   7553:                           (see &scantron_getfile())
                   7554:     $line              - existing scanline
                   7555:     $whichline         - line number of the passed in scanline
                   7556:     $field             - type of change to process 
                   7557:                          (either 
1.573     bisitz   7558:                           'ID'     -> correct the student/employee ID
1.423     albertel 7559:                           'CODE'   -> correct the CODE
                   7560:                           'answer' -> fixup the submitted answers)
                   7561:     
                   7562:    $args               - hash of additional info,
                   7563:                           - 'ID' 
                   7564:                                'newid' -> studentID to use in replacement
1.424     albertel 7565:                                           of existing one
1.423     albertel 7566:                           - 'CODE' 
                   7567:                                'CODE_ignore_dup' - set to true if duplicates
                   7568:                                                    should be ignored.
                   7569: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 7570:                                         if the existing unfound code should
1.423     albertel 7571:                                         be used as is
                   7572:                           - 'answer'
                   7573:                                'response' - new answer or 'none' if blank
                   7574:                                'question' - the bubble line to change
1.503     raeburn  7575:                                'questionnum' - the question identifier,
                   7576:                                                may include subquestion. 
1.423     albertel 7577: 
                   7578:   Returns:
                   7579:     $line - the modified scanline
                   7580: 
                   7581:   Side effects: 
                   7582:     $scan_data - may be updated
                   7583: 
                   7584: =cut
                   7585: 
1.82      albertel 7586: 
1.157     albertel 7587: sub scantron_fixup_scanline {
                   7588:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   7589:     if ($field eq 'ID') {
                   7590: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 7591: 	    return ($line,1,'New value too large');
1.157     albertel 7592: 	}
                   7593: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   7594: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   7595: 				     $args->{'newid'});
                   7596: 	}
                   7597: 	substr($line,$$scantron_config{'IDstart'}-1,
                   7598: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   7599: 	if ($args->{'newid'}=~/^\s*$/) {
                   7600: 	    &scan_data($scan_data,"$whichline.user",
                   7601: 		       $args->{'username'}.':'.$args->{'domain'});
                   7602: 	}
1.186     albertel 7603:     } elsif ($field eq 'CODE') {
1.192     albertel 7604: 	if ($args->{'CODE_ignore_dup'}) {
                   7605: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   7606: 	}
                   7607: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   7608: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 7609: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   7610: 		return ($line,1,'New CODE value too large');
                   7611: 	    }
                   7612: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   7613: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   7614: 	    }
                   7615: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   7616: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 7617: 	}
1.157     albertel 7618:     } elsif ($field eq 'answer') {
1.497     foxr     7619: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 7620: 	my $off=$scantron_config->{'Qoff'};
                   7621: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     7622: 	my $answer=${off}x$length;
                   7623: 	if ($args->{'response'} eq 'none') {
                   7624: 	    &scan_data($scan_data,
1.503     raeburn  7625: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     7626: 	} else {
                   7627: 	    if ($on eq 'letter') {
                   7628: 		my @alphabet=('A'..'Z');
                   7629: 		$answer=$alphabet[$args->{'response'}];
                   7630: 	    } elsif ($on eq 'number') {
                   7631: 		$answer=$args->{'response'}+1;
                   7632: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 7633: 	    } else {
1.497     foxr     7634: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 7635: 	    }
1.497     foxr     7636: 	    &scan_data($scan_data,
1.503     raeburn  7637: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 7638: 	}
1.497     foxr     7639: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   7640: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 7641:     }
                   7642:     return $line;
                   7643: }
1.423     albertel 7644: 
                   7645: =pod
                   7646: 
                   7647: =item scan_data
                   7648: 
                   7649:     Edit or look up  an item in the scan_data hash.
                   7650: 
                   7651:   Arguments:
                   7652:     $scan_data  - The hash (see scantron_getfile)
                   7653:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 7654:                   scantronfilename_key).
1.423     albertel 7655:     $data        - New value of the hash entry.
                   7656:     $delete      - If true, the entry is removed from the hash.
                   7657: 
                   7658:   Returns:
                   7659:     The new value of the hash table field (undefined if deleted).
                   7660: 
                   7661: =cut
                   7662: 
                   7663: 
1.157     albertel 7664: sub scan_data {
                   7665:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 7666:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 7667:     if (defined($value)) {
                   7668: 	$scan_data->{$filename.'_'.$key} = $value;
                   7669:     }
                   7670:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   7671:     return $scan_data->{$filename.'_'.$key};
                   7672: }
1.423     albertel 7673: 
1.495     albertel 7674: # ----- These first few routines are general use routines.----
                   7675: 
                   7676: # Return the number of occurences of a pattern in a string.
                   7677: 
                   7678: sub occurence_count {
                   7679:     my ($string, $pattern) = @_;
                   7680: 
                   7681:     my @matches = ($string =~ /$pattern/g);
                   7682: 
                   7683:     return scalar(@matches);
                   7684: }
                   7685: 
                   7686: 
                   7687: # Take a string known to have digits and convert all the
                   7688: # digits into letters in the range J,A..I.
                   7689: 
                   7690: sub digits_to_letters {
                   7691:     my ($input) = @_;
                   7692: 
                   7693:     my @alphabet = ('J', 'A'..'I');
                   7694: 
                   7695:     my @input    = split(//, $input);
                   7696:     my $output ='';
                   7697:     for (my $i = 0; $i < scalar(@input); $i++) {
                   7698: 	if ($input[$i] =~ /\d/) {
                   7699: 	    $output .= $alphabet[$input[$i]];
                   7700: 	} else {
                   7701: 	    $output .= $input[$i];
                   7702: 	}
                   7703:     }
                   7704:     return $output;
                   7705: }
                   7706: 
1.423     albertel 7707: =pod 
                   7708: 
                   7709: =item scantron_parse_scanline
                   7710: 
1.711     bisitz   7711:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 7712: 
                   7713:  Arguments:
1.711     bisitz   7714:     line             - The text of the bubblesheet file line to process
1.423     albertel 7715:     whichline        - Line number
1.711     bisitz   7716:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 7717:     scan_data        - Hash of extra information about the scanline
                   7718:                        (see scantron_getfile for more information)
                   7719:     just_header      - True if should not process question answers but only
                   7720:                        the stuff to the left of the answers.
1.691     raeburn  7721:     randomorder      - True if randomorder in use
                   7722:     randompick       - True if randompick in use
                   7723:     sequence         - Exam folder URL
                   7724:     master_seq       - Ref to array containing symbs in exam folder
                   7725:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   7726:                        (corresponding values are resource objects)
                   7727:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   7728:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   7729:                        are refs to an array of resource objects, ordered
                   7730:                        according to order used for CODE, when randomorder
                   7731:                        and or randompick are in use.
                   7732:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   7733:                        for current line to question number used for same question
                   7734:                         in "Master Sequence" (as seen by Course Coordinator).
                   7735:     startline        - Ref to hash where key is question number (0 is first)
                   7736:                        and value is number of first bubble line for current 
                   7737:                        student or code-based randompick and/or randomorder.
                   7738:     totalref         - Ref of scalar used to score total number of bubble
                   7739:                        lines needed for responses in a scan line (used when
                   7740:                        randompick in use. 
                   7741:     
1.423     albertel 7742:  Returns:
                   7743:    Hash containing the result of parsing the scanline
                   7744: 
                   7745:    Keys are all proceeded by the string 'scantron.'
                   7746: 
                   7747:        CODE    - the CODE in use for this scanline
                   7748:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   7749:                  by the operator
                   7750:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   7751:                             CODEs were selected, but the usage has been
                   7752:                             forced by the operator
1.556     weissno  7753:        ID  - student/employee ID
1.423     albertel 7754:        PaperID - if used, the ID number printed on the sheet when the 
                   7755:                  paper was scanned
                   7756:        FirstName - first name from the sheet
                   7757:        LastName  - last name from the sheet
                   7758: 
                   7759:      if just_header was not true these key may also exist
                   7760: 
1.447     foxr     7761:        missingerror - a list of bubble ranges that are considered to be answers
                   7762:                       to a single question that don't have any bubbles filled in.
                   7763:                       Of the form questionnumber:firstbubblenumber:count.
                   7764:        doubleerror  - a list of bubble ranges that are considered to be answers
                   7765:                       to a single question that have more than one bubble filled in.
                   7766:                       Of the form questionnumber::firstbubblenumber:count
                   7767:    
                   7768:                 In the above, count is the number of bubble responses in the
                   7769:                 input line needed to represent the possible answers to the question.
                   7770:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   7771:                 per line would have count = 2.
                   7772: 
1.423     albertel 7773:        maxquest     - the number of the last bubble line that was parsed
                   7774: 
                   7775:        (<number> starts at 1)
                   7776:        <number>.answer - zero or more letters representing the selected
                   7777:                          letters from the scanline for the bubble line 
                   7778:                          <number>.
                   7779:                          if blank there was either no bubble or there where
                   7780:                          multiple bubbles, (consult the keys missingerror and
                   7781:                          doubleerror if this is an error condition)
                   7782: 
                   7783: =cut
                   7784: 
1.82      albertel 7785: sub scantron_parse_scanline {
1.691     raeburn  7786:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   7787:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   7788:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     7789: 
1.82      albertel 7790:     my %record;
1.691     raeburn  7791:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 7792:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   7793: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   7794: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   7795: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   7796: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 7797: 	    $record{'scantron.CODE'}=substr($data,
                   7798: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 7799: 					    $$scantron_config{'CODElength'});
1.191     albertel 7800: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   7801: 		$record{'scantron.useCODE'}=1;
                   7802: 	    }
1.192     albertel 7803: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   7804: 		$record{'scantron.CODE_ignore_dup'}=1;
                   7805: 	    }
1.82      albertel 7806: 	} else {
                   7807: 	    #FIXME interpret first N questions
                   7808: 	}
                   7809:     }
1.83      albertel 7810:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   7811: 				  $$scantron_config{'IDlength'});
1.157     albertel 7812:     $record{'scantron.PaperID'}=
                   7813: 	substr($data,$$scantron_config{'PaperID'}-1,
                   7814: 	       $$scantron_config{'PaperIDlength'});
                   7815:     $record{'scantron.FirstName'}=
                   7816: 	substr($data,$$scantron_config{'FirstName'}-1,
                   7817: 	       $$scantron_config{'FirstNamelength'});
                   7818:     $record{'scantron.LastName'}=
                   7819: 	substr($data,$$scantron_config{'LastName'}-1,
                   7820: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 7821:     if ($just_header) { return \%record; }
1.194     albertel 7822: 
1.82      albertel 7823:     my @alphabet=('A'..'Z');
                   7824:     my $questnum=0;
1.447     foxr     7825:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   7826: 
1.691     raeburn  7827:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   7828:     if ($randompick || $randomorder) {
                   7829:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   7830:                                          $master_seq,$symb_to_resource,
                   7831:                                          $partids_by_symb,$orderedforcode,
                   7832:                                          $respnumlookup,$startline);
                   7833:         if ($total) {
                   7834:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   7835:         }
                   7836:         if (ref($totalref)) {
                   7837:             $$totalref = $total;
                   7838:         }
                   7839:     }
                   7840:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     7841:     chomp($questions);		# Get rid of any trailing \n.
                   7842:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   7843:     while (length($questions)) {
1.691     raeburn  7844:         my $answers_needed;
                   7845:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7846:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   7847:         } else {
                   7848: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   7849:         }
1.503     raeburn  7850:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   7851:                              || 1;
                   7852:         $questnum++;
                   7853:         my $quest_id = $questnum;
                   7854:         my $currentquest = substr($questions,0,$answer_length);
                   7855:         $questions       = substr($questions,$answer_length);
                   7856:         if (length($currentquest) < $answer_length) { next; }
                   7857: 
1.691     raeburn  7858:         my $subdivided;
                   7859:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7860:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   7861:         } else {
                   7862:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   7863:         }
                   7864:         if ($subdivided =~ /,/) {
1.503     raeburn  7865:             my $subquestnum = 1;
                   7866:             my $subquestions = $currentquest;
1.691     raeburn  7867:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  7868:             foreach my $subans (@subanswers_needed) {
                   7869:                 my $subans_length =
                   7870:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   7871:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   7872:                 $subquestions   = substr($subquestions,$subans_length);
                   7873:                 $quest_id = "$questnum.$subquestnum";
                   7874:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   7875:                     ($$scantron_config{'Qon'} eq 'number')) {
                   7876:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   7877:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  7878:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7879:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7880:                 } else {
                   7881:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  7882:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   7883:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7884:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7885:                 }
                   7886:                 $subquestnum ++;
                   7887:             }
                   7888:         } else {
                   7889:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   7890:                 ($$scantron_config{'Qon'} eq 'number')) {
                   7891:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   7892:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7893:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7894:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7895:             } else {
                   7896:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   7897:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7898:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7899:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7900:             }
                   7901:         }
                   7902:     }
                   7903:     $record{'scantron.maxquest'}=$questnum;
                   7904:     return \%record;
                   7905: }
1.447     foxr     7906: 
1.691     raeburn  7907: sub get_master_seq {
1.788     raeburn  7908:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
1.691     raeburn  7909:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   7910:                    (ref($symb_to_resource) eq 'HASH'));
1.788     raeburn  7911:     if ($need_symb_in_map) {
                   7912:         return unless (ref($symb_for_examcode) eq 'HASH');
                   7913:     }
1.691     raeburn  7914:     my $resource_error;
                   7915:     foreach my $resource (@{$resources}) {
                   7916:         my $ressymb;
                   7917:         if (ref($resource)) {
                   7918:             $ressymb = $resource->symb();
                   7919:             push(@{$master_seq},$ressymb);
                   7920:             $symb_to_resource->{$ressymb} = $resource;
1.788     raeburn  7921:             if ($need_symb_in_map) {
                   7922:                 unless ($resource->is_map()) {
                   7923:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   7924:                     unless (exists($symb_for_examcode->{$map})) {
                   7925:                         $symb_for_examcode->{$map} = $ressymb;
                   7926:                     }
                   7927:                 }
                   7928:             }
1.691     raeburn  7929:         } else {
                   7930:             $resource_error = 1;
                   7931:             last;
                   7932:         }
                   7933:     }
                   7934:     return $resource_error;
                   7935: }
                   7936: 
                   7937: sub get_respnum_lookups {
                   7938:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   7939:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   7940:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   7941:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   7942:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   7943:                    (ref($startline) eq 'HASH'));
                   7944:     my ($user,$scancode);
                   7945:     if ((exists($record->{'scantron.CODE'})) &&
                   7946:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   7947:         $scancode = $record->{'scantron.CODE'};
                   7948:     } else {
                   7949:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   7950:     }
                   7951:     my @mapresources =
                   7952:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   7953:                      $orderedforcode);
                   7954:     my $total = 0;
                   7955:     my $count = 0;
                   7956:     foreach my $resource (@mapresources) {
                   7957:         my $id = $resource->id();
                   7958:         my $symb = $resource->symb();
                   7959:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   7960:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   7961:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   7962:                 if ($respnum ne '') {
                   7963:                     $respnumlookup->{$count} = $respnum;
                   7964:                     $startline->{$count} = $total;
                   7965:                     $total += $bubble_lines_per_response{$respnum};
                   7966:                     $count ++;
                   7967:                 }
                   7968:             }
                   7969:         }
                   7970:     }
                   7971:     return $total;
                   7972: }
                   7973: 
1.503     raeburn  7974: sub scantron_validator_lettnum {
                   7975:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  7976:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   7977:         $randompick,$respnumlookup) = @_;
1.503     raeburn  7978: 
                   7979:     # Qon 'letter' implies for each slot in currquest we have:
                   7980:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   7981:     #    about anything else (esp. a value of Qoff) for missing
                   7982:     #    bubbles.
                   7983:     #
                   7984:     # Qon 'number' implies each slot gives a digit that indexes the
                   7985:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   7986:     #    and * or ? for double bubbles on a single line.
                   7987:     #
1.447     foxr     7988: 
1.503     raeburn  7989:     my $matchon;
                   7990:     if ($$scantron_config{'Qon'} eq 'letter') {
                   7991:         $matchon = '[A-Z]';
                   7992:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   7993:         $matchon = '\d';
                   7994:     }
                   7995:     my $occurrences = 0;
1.691     raeburn  7996:     my $responsenum = $questnum-1;
                   7997:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7998:        $responsenum = $respnumlookup->{$questnum-1} 
                   7999:     }
                   8000:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8001:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8002:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8003:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8004:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8005:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8006:         my @singlelines = split('',$currquest);
                   8007:         foreach my $entry (@singlelines) {
                   8008:             $occurrences = &occurence_count($entry,$matchon);
                   8009:             if ($occurrences > 1) {
                   8010:                 last;
                   8011:             }
1.691     raeburn  8012:         }
1.503     raeburn  8013:     } else {
                   8014:         $occurrences = &occurence_count($currquest,$matchon); 
                   8015:     }
                   8016:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   8017:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8018:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8019:             my $bubble = substr($currquest,$ans,1);
                   8020:             if ($bubble =~ /$matchon/ ) {
                   8021:                 if ($$scantron_config{'Qon'} eq 'number') {
                   8022:                     if ($bubble == 0) {
                   8023:                         $bubble = 10; 
                   8024:                     }
                   8025:                     $record->{"scantron.$ansnum.answer"} = 
                   8026:                         $alphabet->[$bubble-1];
                   8027:                 } else {
                   8028:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   8029:                 }
                   8030:             } else {
                   8031:                 $record->{"scantron.$ansnum.answer"}='';
                   8032:             }
                   8033:             $ansnum++;
                   8034:         }
                   8035:     } elsif (!defined($currquest)
                   8036:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   8037:             || (&occurence_count($currquest,$matchon) == 0)) {
                   8038:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8039:             $record->{"scantron.$ansnum.answer"}='';
                   8040:             $ansnum++;
                   8041:         }
                   8042:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8043:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   8044:         }
                   8045:     } else {
                   8046:         if ($$scantron_config{'Qon'} eq 'number') {
                   8047:             $currquest = &digits_to_letters($currquest);            
                   8048:         }
                   8049:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8050:             my $bubble = substr($currquest,$ans,1);
                   8051:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   8052:             $ansnum++;
                   8053:         }
                   8054:     }
                   8055:     return $ansnum;
                   8056: }
1.447     foxr     8057: 
1.503     raeburn  8058: sub scantron_validator_positional {
                   8059:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  8060:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   8061:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     8062: 
1.503     raeburn  8063:     # Otherwise there's a positional notation;
                   8064:     # each bubble line requires Qlength items, and there are filled in
                   8065:     # bubbles for each case where there 'Qon' characters.
                   8066:     #
1.447     foxr     8067: 
1.503     raeburn  8068:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     8069: 
1.503     raeburn  8070:     # If the split only gives us one element.. the full length of the
                   8071:     # answer string, no bubbles are filled in:
1.447     foxr     8072: 
1.507     raeburn  8073:     if ($answers_needed eq '') {
                   8074:         return;
                   8075:     }
                   8076: 
1.503     raeburn  8077:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   8078:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   8079:             $record->{"scantron.$ansnum.answer"}='';
                   8080:             $ansnum++;
                   8081:         }
                   8082:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   8083:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   8084:         }
                   8085:     } elsif (scalar(@array) == 2) {
                   8086:         my $location = length($array[0]);
                   8087:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   8088:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   8089:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8090:             if ($ans eq $line_num) {
                   8091:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   8092:             } else {
                   8093:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   8094:             }
                   8095:             $ansnum++;
                   8096:          }
                   8097:     } else {
                   8098:         #  If there's more than one instance of a bubble character
                   8099:         #  That's a double bubble; with positional notation we can
                   8100:         #  record all the bubbles filled in as well as the
                   8101:         #  fact this response consists of multiple bubbles.
                   8102:         #
1.691     raeburn  8103:         my $responsenum = $questnum-1;
                   8104:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   8105:             $responsenum = $respnumlookup->{$questnum-1}
                   8106:         }
                   8107:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8108:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8109:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8110:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8111:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8112:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  8113:             my $doubleerror = 0;
                   8114:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   8115:                    (!$doubleerror)) {
                   8116:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   8117:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   8118:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   8119:                if (length(@currarray) > 2) {
                   8120:                    $doubleerror = 1;
                   8121:                } 
                   8122:             }
                   8123:             if ($doubleerror) {
                   8124:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8125:             }
                   8126:         } else {
                   8127:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   8128:         }
                   8129:         my $item = $ansnum;
                   8130:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   8131:             $record->{"scantron.$item.answer"} = '';
                   8132:             $item ++;
                   8133:         }
1.447     foxr     8134: 
1.503     raeburn  8135:         my @ans=@array;
                   8136:         my $i=0;
                   8137:         my $increment = 0;
                   8138:         while ($#ans) {
                   8139:             $i+=length($ans[0]) + $increment;
                   8140:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   8141:             my $bubble = $i%$$scantron_config{'Qlength'};
                   8142:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   8143:             shift(@ans);
                   8144:             $increment = 1;
                   8145:         }
                   8146:         $ansnum += $answers_needed;
1.82      albertel 8147:     }
1.503     raeburn  8148:     return $ansnum;
1.82      albertel 8149: }
                   8150: 
1.423     albertel 8151: =pod
                   8152: 
                   8153: =item scantron_add_delay
                   8154: 
                   8155:    Adds an error message that occurred during the grading phase to a
                   8156:    queue of messages to be shown after grading pass is complete
                   8157: 
                   8158:  Arguments:
1.424     albertel 8159:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 8160:    $scanline    - the scanline that caused the error
                   8161:    $errormesage - the error message
                   8162:    $errorcode   - a numeric code for the error
                   8163: 
                   8164:  Side Effects:
1.424     albertel 8165:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 8166: 
                   8167: =cut
                   8168: 
1.82      albertel 8169: sub scantron_add_delay {
1.140     albertel 8170:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   8171:     push(@$delayqueue,
                   8172: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   8173: 	  'ecode' => $errorcode }
                   8174: 	 );
1.82      albertel 8175: }
                   8176: 
1.423     albertel 8177: =pod
                   8178: 
                   8179: =item scantron_find_student
                   8180: 
1.424     albertel 8181:    Finds the username for the current scanline
                   8182: 
                   8183:   Arguments:
                   8184:    $scantron_record - hash result from scantron_parse_scanline
                   8185:    $scan_data       - hash of correction information 
                   8186:                       (see &scantron_getfile() form more information)
                   8187:    $idmap           - hash from &username_to_idmap()
                   8188:    $line            - number of current scanline
                   8189:  
                   8190:   Returns:
                   8191:    Either 'username:domain' or undef if unknown
                   8192: 
1.423     albertel 8193: =cut
                   8194: 
1.82      albertel 8195: sub scantron_find_student {
1.157     albertel 8196:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 8197:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 8198:     if ($scanID =~ /^\s*$/) {
                   8199:  	return &scan_data($scan_data,"$line.user");
                   8200:     }
1.83      albertel 8201:     foreach my $id (keys(%$idmap)) {
1.157     albertel 8202:  	if (lc($id) eq lc($scanID)) {
                   8203:  	    return $$idmap{$id};
                   8204:  	}
1.83      albertel 8205:     }
                   8206:     return undef;
                   8207: }
                   8208: 
1.423     albertel 8209: =pod
                   8210: 
                   8211: =item scantron_filter
                   8212: 
1.424     albertel 8213:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   8214:    hidden resources was selected
                   8215: 
1.423     albertel 8216: =cut
                   8217: 
1.83      albertel 8218: sub scantron_filter {
                   8219:     my ($curres)=@_;
1.331     albertel 8220: 
                   8221:     if (ref($curres) && $curres->is_problem()) {
                   8222: 	# if the user has asked to not have either hidden
                   8223: 	# or 'randomout' controlled resources to be graded
                   8224: 	# don't include them
                   8225: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   8226: 	    && $curres->randomout) {
                   8227: 	    return 0;
                   8228: 	}
1.83      albertel 8229: 	return 1;
                   8230:     }
                   8231:     return 0;
1.82      albertel 8232: }
                   8233: 
1.423     albertel 8234: =pod
                   8235: 
                   8236: =item scantron_process_corrections
                   8237: 
1.424     albertel 8238:    Gets correction information out of submitted form data and corrects
                   8239:    the scanline
                   8240: 
1.423     albertel 8241: =cut
                   8242: 
1.157     albertel 8243: sub scantron_process_corrections {
                   8244:     my ($r) = @_;
1.754     raeburn  8245:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8246:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8247:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 8248:     my $which=$env{'form.scantron_line'};
1.200     albertel 8249:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 8250:     my ($skip,$err,$errmsg);
1.257     albertel 8251:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 8252: 	$skip=1;
1.257     albertel 8253:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   8254: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   8255: 	    $env{'form.scantron_domain'};
1.157     albertel 8256: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   8257: 	($line,$err,$errmsg)=
                   8258: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   8259: 				     'ID',{'newid'=>$newid,
1.257     albertel 8260: 				    'username'=>$env{'form.scantron_username'},
                   8261: 				    'domain'=>$env{'form.scantron_domain'}});
                   8262:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   8263: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 8264: 	my $newCODE;
1.192     albertel 8265: 	my %args;
1.190     albertel 8266: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 8267: 	    $newCODE='use_unfound';
1.190     albertel 8268: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 8269: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 8270: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 8271: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 8272: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 8273: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 8274: 	}
1.257     albertel 8275: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 8276: 	    $args{'CODE_ignore_dup'}=1;
                   8277: 	}
                   8278: 	$args{'CODE'}=$newCODE;
1.186     albertel 8279: 	($line,$err,$errmsg)=
                   8280: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 8281: 				     'CODE',\%args);
1.257     albertel 8282:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   8283: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 8284: 	    ($line,$err,$errmsg)=
                   8285: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   8286: 					 $which,'answer',
                   8287: 					 { 'question'=>$question,
1.503     raeburn  8288: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   8289:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 8290: 	    if ($err) { last; }
                   8291: 	}
                   8292:     }
                   8293:     if ($err) {
1.703     bisitz   8294:         $r->print(
                   8295:             '<p class="LC_error">'
                   8296:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   8297:                 $errmsg)
1.704     raeburn  8298:            .'</p>');
1.157     albertel 8299:     } else {
1.200     albertel 8300: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 8301: 	&scantron_putfile($scanlines,$scan_data);
                   8302:     }
                   8303: }
                   8304: 
1.423     albertel 8305: =pod
                   8306: 
                   8307: =item reset_skipping_status
                   8308: 
1.424     albertel 8309:    Forgets the current set of remember skipped scanlines (and thus
                   8310:    reverts back to considering all lines in the
                   8311:    scantron_skipped_<filename> file)
                   8312: 
1.423     albertel 8313: =cut
                   8314: 
1.200     albertel 8315: sub reset_skipping_status {
                   8316:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8317:     &scan_data($scan_data,'remember_skipping',undef,1);
                   8318:     &scantron_putfile(undef,$scan_data);
                   8319: }
                   8320: 
1.423     albertel 8321: =pod
                   8322: 
                   8323: =item start_skipping
                   8324: 
1.424     albertel 8325:    Marks a scanline to be skipped. 
                   8326: 
1.423     albertel 8327: =cut
                   8328: 
1.376     albertel 8329: sub start_skipping {
1.200     albertel 8330:     my ($scan_data,$i)=@_;
                   8331:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8332:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   8333: 	$remembered{$i}=2;
                   8334:     } else {
                   8335: 	$remembered{$i}=1;
                   8336:     }
1.200     albertel 8337:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   8338: }
                   8339: 
1.423     albertel 8340: =pod
                   8341: 
                   8342: =item should_be_skipped
                   8343: 
1.424     albertel 8344:    Checks whether a scanline should be skipped.
                   8345: 
1.423     albertel 8346: =cut
                   8347: 
1.200     albertel 8348: sub should_be_skipped {
1.376     albertel 8349:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 8350:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 8351: 	# not redoing old skips
1.376     albertel 8352: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 8353: 	return 0;
                   8354:     }
                   8355:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 8356: 
                   8357:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   8358: 	return 0;
                   8359:     }
1.200     albertel 8360:     return 1;
                   8361: }
                   8362: 
1.423     albertel 8363: =pod
                   8364: 
                   8365: =item remember_current_skipped
                   8366: 
1.424     albertel 8367:    Discovers what scanlines are in the scantron_skipped_<filename>
                   8368:    file and remembers them into scan_data for later use.
                   8369: 
1.423     albertel 8370: =cut
                   8371: 
1.200     albertel 8372: sub remember_current_skipped {
                   8373:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8374:     my %to_remember;
                   8375:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8376: 	if ($scanlines->{'skipped'}[$i]) {
                   8377: 	    $to_remember{$i}=1;
                   8378: 	}
                   8379:     }
1.376     albertel 8380: 
1.200     albertel 8381:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   8382:     &scantron_putfile(undef,$scan_data);
                   8383: }
                   8384: 
1.423     albertel 8385: =pod
                   8386: 
                   8387: =item check_for_error
                   8388: 
1.424     albertel 8389:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  8390:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 8391:     something went wrong.
                   8392: 
1.423     albertel 8393: =cut
                   8394: 
1.200     albertel 8395: sub check_for_error {
                   8396:     my ($r,$result)=@_;
                   8397:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 8398: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 8399:     }
                   8400: }
1.157     albertel 8401: 
1.423     albertel 8402: =pod
                   8403: 
                   8404: =item scantron_warning_screen
                   8405: 
1.424     albertel 8406:    Interstitial screen to make sure the operator has selected the
                   8407:    correct options before we start the validation phase.
                   8408: 
1.423     albertel 8409: =cut
                   8410: 
1.203     albertel 8411: sub scantron_warning_screen {
1.650     raeburn  8412:     my ($button_text,$symb)=@_;
1.257     albertel 8413:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  8414:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 8415:     my $CODElist;
1.284     albertel 8416:     if ($scantron_config{'CODElocation'} &&
                   8417: 	$scantron_config{'CODEstart'} &&
                   8418: 	$scantron_config{'CODElength'}) {
                   8419: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   8420: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 8421: 	$CODElist=
1.492     albertel 8422: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 8423: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 8424:     }
1.663     raeburn  8425:     my $lastbubblepoints;
                   8426:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8427:         $lastbubblepoints =
                   8428:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   8429:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   8430:     }
1.770     raeburn  8431:     return '
1.203     albertel 8432: <p>
1.492     albertel 8433: <span class="LC_warning">
1.705     raeburn  8434: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 8435: </p>
                   8436: <table>
1.492     albertel 8437: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   8438: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  8439: '.$CODElist.$lastbubblepoints.'
1.203     albertel 8440: </table>
1.680     raeburn  8441: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  8442: '.&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  8443: ';
1.203     albertel 8444: }
                   8445: 
1.423     albertel 8446: =pod
                   8447: 
                   8448: =item scantron_do_warning
                   8449: 
1.424     albertel 8450:    Check if the operator has picked something for all required
                   8451:    fields. Error out if something is missing.
                   8452: 
1.423     albertel 8453: =cut
                   8454: 
1.203     albertel 8455: sub scantron_do_warning {
1.608     www      8456:     my ($r,$symb)=@_;
1.203     albertel 8457:     if (!$symb) {return '';}
1.324     albertel 8458:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 8459:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 8460:     if ( $env{'form.selectpage'} eq '' ||
                   8461: 	 $env{'form.scantron_selectfile'} eq '' ||
                   8462: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  8463: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 8464: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 8465: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 8466: 	} 
1.257     albertel 8467: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  8468: 	    $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  8469: 	}
1.257     albertel 8470: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  8471: 	    $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  8472: 	}
1.237     albertel 8473:     } else {
1.650     raeburn  8474: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  8475:         my ($checksec,@possibles) = &gradable_sections();
                   8476:         my $gradesections;
                   8477:         if ($checksec) {
                   8478:             my $file=$env{'form.scantron_selectfile'};
                   8479:             if (&valid_file($file)) {
                   8480:                 my %bysec = &scantron_get_sections();
                   8481:                 my $table;
                   8482:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   8483:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   8484:                     $table = &Apache::loncommon::start_data_table()."\n".
                   8485:                              &Apache::loncommon::start_data_table_header_row().
                   8486:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   8487:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   8488:                     if ($bysec{'none'}) {
                   8489:                         $table .= &Apache::loncommon::start_data_table_row().
                   8490:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   8491:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8492:                     }
                   8493:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   8494:                         next if ($sec eq 'none');
                   8495:                         $table .= &Apache::loncommon::start_data_table_row().
                   8496:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   8497:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8498:                     }
                   8499:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   8500:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   8501:                                       '<p>'.$table.'</p>';
                   8502:                     if (@possibles) {
                   8503:                         $gradesections .= '<p>'.
                   8504:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   8505:                                               scalar(@possibles)).'<br />'.
                   8506:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   8507:                                               '<i>'.$checksec.'</i>').' ';
                   8508:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   8509:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   8510:                         }
                   8511:                         $gradesections .= '</p>';
                   8512:                     }
                   8513:                 }
                   8514:             } else {
                   8515:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   8516:             }
                   8517:         }
1.663     raeburn  8518:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 8519: 	$r->print('
1.770     raeburn  8520: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 8521: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 8522: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 8523: ');
1.237     albertel 8524:     }
1.614     www      8525:     $r->print("</form><br />");
1.203     albertel 8526:     return '';
                   8527: }
                   8528: 
1.423     albertel 8529: =pod
                   8530: 
                   8531: =item scantron_form_start
                   8532: 
1.424     albertel 8533:     html hidden input for remembering all selected grading options
                   8534: 
1.423     albertel 8535: =cut
                   8536: 
1.203     albertel 8537: sub scantron_form_start {
                   8538:     my ($max_bubble)=@_;
                   8539:     my $result= <<SCANTRONFORM;
                   8540: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 8541:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   8542:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   8543:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 8544:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 8545:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   8546:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   8547:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   8548:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 8549:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 8550: SCANTRONFORM
1.447     foxr     8551: 
                   8552:   my $line = 0;
                   8553:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   8554:        my $chunk =
                   8555: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     8556:        $chunk .=
                   8557: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  8558:        $chunk .= 
                   8559:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  8560:        $chunk .=
                   8561:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  8562:        $chunk .=
                   8563:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     8564:        $result .= $chunk;
                   8565:        $line++;
1.691     raeburn  8566:     }
1.203     albertel 8567:     return $result;
                   8568: }
                   8569: 
1.423     albertel 8570: =pod
                   8571: 
                   8572: =item scantron_validate_file
                   8573: 
1.659     raeburn  8574:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 8575: 
                   8576:     Also processes any necessary information resets that need to
                   8577:     occur before validation begins (ignore previous corrections,
                   8578:     restarting the skipped records processing)
                   8579: 
1.423     albertel 8580: =cut
                   8581: 
1.157     albertel 8582: sub scantron_validate_file {
1.608     www      8583:     my ($r,$symb) = @_;
1.157     albertel 8584:     if (!$symb) {return '';}
1.324     albertel 8585:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 8586:     
1.703     bisitz   8587:     # do the detection of only doing skipped records first before we delete
1.424     albertel 8588:     # them when doing the corrections reset
1.257     albertel 8589:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 8590: 	&reset_skipping_status();
                   8591:     }
1.257     albertel 8592:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 8593: 	&remember_current_skipped();
1.257     albertel 8594: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 8595:     }
                   8596: 
1.257     albertel 8597:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 8598: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   8599: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   8600: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 8601: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 8602:     }
1.200     albertel 8603: 
1.257     albertel 8604:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 8605: 	&scantron_process_corrections($r);
                   8606:     }
1.770     raeburn  8607: 
                   8608:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   8609:     my ($checksec,@gradable);
                   8610:     if ($env{'request.course.sec'}) {
                   8611:         ($checksec,my @possibles) = &gradable_sections();
                   8612:         if ($checksec) {
                   8613:             if (@possibles) {
                   8614:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   8615:                 if (@chosensecs) {
                   8616:                     foreach my $sec (@chosensecs) {
                   8617:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   8618:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   8619:                                 push(@gradable,$sec);
                   8620:                             }
                   8621:                         }
                   8622:                     }
                   8623:                 }
                   8624:             }
                   8625:             $r->print('<p><table>');
                   8626:             if (@gradable) {
                   8627:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   8628:                 $r->print(
                   8629:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   8630:             } else {
                   8631:                 $r->print(
                   8632:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   8633:             }
                   8634:             $r->print('</table></p>');
                   8635:         }
                   8636:     }
                   8637:     $r->rflush();
                   8638: 
1.157     albertel 8639:     #get the student pick code ready
                   8640:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  8641:     my $nav_error;
1.754     raeburn  8642:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8643:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8644:     if ($nav_error) {
                   8645:         $r->print(&navmap_errormsg());
                   8646:         return '';
                   8647:     }
1.203     albertel 8648:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  8649:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8650:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   8651:     }
1.157     albertel 8652:     $r->print($result);
                   8653:     
1.334     albertel 8654:     my @validate_phases=( 'sequence',
                   8655: 			  'ID',
1.157     albertel 8656: 			  'CODE',
                   8657: 			  'doublebubble',
                   8658: 			  'missingbubbles');
1.257     albertel 8659:     if (!$env{'form.validatepass'}) {
                   8660: 	$env{'form.validatepass'} = 0;
1.157     albertel 8661:     }
1.257     albertel 8662:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  8663:     my %skipbysec=();
1.448     foxr     8664: 
1.157     albertel 8665:     my $stop=0;
                   8666:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  8667: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 8668: 	$r->rflush();
1.691     raeburn  8669:      
1.157     albertel 8670: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   8671: 	{
                   8672: 	    no strict 'refs';
1.770     raeburn  8673:             my @extras=();
                   8674:             if ($validate_phases[$currentphase] eq 'ID') {
                   8675:                 @extras = (\%skipbysec,$checksec,@gradable);
                   8676:             }
                   8677: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 8678: 	}
                   8679:     }
                   8680:     if (!$stop) {
1.650     raeburn  8681: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  8682:         my $secinfo;
                   8683:         if (keys(%skipbysec) > 0) {
                   8684:             my $seclist = '<ul>';
                   8685:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   8686:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   8687:             }
                   8688:             $seclist .= '</ul>';
                   8689:             $secinfo = '<p class="LC_info">'.
                   8690:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   8691:                            $seclist).
                   8692:                        '</p>';
                   8693:         }
1.542     raeburn  8694: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  8695:                   $secinfo.$warning.
1.542     raeburn  8696:                   &mt('Perform verification for each student after storage of submissions?').
                   8697:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   8698:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   8699:                   ('&nbsp;'x3).'<label>'.
                   8700:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   8701:                   '</label></span><br />'.
                   8702:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  8703:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  8704:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   8705:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 8706:     } else {
                   8707: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   8708: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   8709:     }
                   8710:     if ($stop) {
1.334     albertel 8711: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  8712: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 8713: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 8714: 
1.650     raeburn  8715: 	    $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 8716: 	} else {
1.503     raeburn  8717:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  8718: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  8719:             } else {
1.539     riegler  8720:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  8721:             }
1.492     albertel 8722: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   8723: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   8724: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 8725: 	}
1.157     albertel 8726:     }
1.614     www      8727:     $r->print(" </form><br />");
1.157     albertel 8728:     return '';
                   8729: }
                   8730: 
1.423     albertel 8731: 
                   8732: =pod
                   8733: 
                   8734: =item scantron_remove_file
                   8735: 
1.659     raeburn  8736:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 8737:    scantron_original_<filename> is never removed
                   8738: 
                   8739: 
1.423     albertel 8740: =cut
                   8741: 
1.200     albertel 8742: sub scantron_remove_file {
1.192     albertel 8743:     my ($which)=@_;
1.257     albertel 8744:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8745:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8746:     my $file='scantron_';
1.200     albertel 8747:     if ($which eq 'corrected' || $which eq 'skipped') {
                   8748: 	$file.=$which.'_';
1.192     albertel 8749:     } else {
                   8750: 	return 'refused';
                   8751:     }
1.257     albertel 8752:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 8753:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   8754: }
                   8755: 
1.423     albertel 8756: 
                   8757: =pod
                   8758: 
                   8759: =item scantron_remove_scan_data
                   8760: 
1.659     raeburn  8761:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 8762:    data file.  (In the case that both the are doing skipped records we need
                   8763:    to remember the old skipped lines for the time being so that element
                   8764:    persists for a while.)
                   8765: 
1.423     albertel 8766: =cut
                   8767: 
1.200     albertel 8768: sub scantron_remove_scan_data {
1.257     albertel 8769:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8770:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8771:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   8772:     my @todelete;
1.257     albertel 8773:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 8774:     foreach my $key (@keys) {
                   8775: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 8776: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 8777: 		$key=~/remember_skipping/) {
                   8778: 		next;
                   8779: 	    }
1.192     albertel 8780: 	    push(@todelete,$key);
                   8781: 	}
                   8782:     }
1.200     albertel 8783:     my $result;
1.192     albertel 8784:     if (@todelete) {
1.491     albertel 8785: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   8786: 				       \@todelete,$cdom,$cname);
                   8787:     } else {
                   8788: 	$result = 'ok';
1.192     albertel 8789:     }
                   8790:     return $result;
                   8791: }
                   8792: 
1.423     albertel 8793: 
                   8794: =pod
                   8795: 
                   8796: =item scantron_getfile
                   8797: 
1.659     raeburn  8798:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 8799:     the scan_data hash
                   8800:   
                   8801:   Arguments:
                   8802:     None
                   8803: 
                   8804:   Returns:
                   8805:     2 hash references
                   8806: 
                   8807:      - first one has 
                   8808:          orig      -
                   8809:          corrected -
                   8810:          skipped   -  each of which points to an array ref of the specified
                   8811:                       file broken up into individual lines
                   8812:          count     - number of scanlines
                   8813:  
                   8814:      - second is the scan_data hash possible keys are
1.425     albertel 8815:        ($number refers to scanline numbered $number and thus the key affects
                   8816:         only that scanline
                   8817:         $bubline refers to the specific bubble line element and the aspects
                   8818:         refers to that specific bubble line element)
                   8819: 
                   8820:        $number.user - username:domain to use
                   8821:        $number.CODE_ignore_dup 
                   8822:                     - ignore the duplicate CODE error 
                   8823:        $number.useCODE
                   8824:                     - use the CODE in the scanline as is
                   8825:        $number.no_bubble.$bubline
                   8826:                     - it is valid that there is no bubbled in bubble
                   8827:                       at $number $bubline
                   8828:        remember_skipping
                   8829:                     - a frozen hash containing keys of $number and values
                   8830:                       of either 
                   8831:                         1 - we are on a 'do skipped records pass' and plan
                   8832:                             on processing this line
                   8833:                         2 - we are on a 'do skipped records pass' and this
                   8834:                             scanline has been marked to skip yet again
1.424     albertel 8835: 
1.423     albertel 8836: =cut
                   8837: 
1.157     albertel 8838: sub scantron_getfile {
1.200     albertel 8839:     #FIXME really would prefer a scantron directory
1.257     albertel 8840:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8841:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 8842:     my $lines;
                   8843:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8844: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 8845:     my %scanlines;
                   8846:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   8847:     my $temp=$scanlines{'orig'};
                   8848:     $scanlines{'count'}=$#$temp;
                   8849: 
                   8850:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8851: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 8852:     if ($lines eq '-1') {
                   8853: 	$scanlines{'corrected'}=[];
                   8854:     } else {
                   8855: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   8856:     }
                   8857:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8858: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 8859:     if ($lines eq '-1') {
                   8860: 	$scanlines{'skipped'}=[];
                   8861:     } else {
                   8862: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   8863:     }
1.175     albertel 8864:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 8865:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   8866:     my %scan_data = @tmp;
                   8867:     return (\%scanlines,\%scan_data);
                   8868: }
                   8869: 
1.423     albertel 8870: =pod
                   8871: 
                   8872: =item lonnet_putfile
                   8873: 
1.424     albertel 8874:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   8875: 
                   8876:  Arguments:
                   8877:    $contents - data to store
                   8878:    $filename - filename to store $contents into
                   8879: 
                   8880:  Returns:
                   8881:    result value from &Apache::lonnet::finishuserfileupload
                   8882: 
1.423     albertel 8883: =cut
                   8884: 
1.157     albertel 8885: sub lonnet_putfile {
                   8886:     my ($contents,$filename)=@_;
1.257     albertel 8887:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8888:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8889:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 8890:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 8891: 
                   8892: }
                   8893: 
1.423     albertel 8894: =pod
                   8895: 
                   8896: =item scantron_putfile
                   8897: 
1.659     raeburn  8898:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 8899:     scan_data hash. (Does not modify the original version only the
                   8900:     corrected and skipped versions.
                   8901: 
                   8902:  Arguments:
                   8903:     $scanlines - hash ref that looks like the first return value from
                   8904:                  &scantron_getfile()
                   8905:     $scan_data - hash ref that looks like the second return value from
                   8906:                  &scantron_getfile()
                   8907: 
1.423     albertel 8908: =cut
                   8909: 
1.157     albertel 8910: sub scantron_putfile {
                   8911:     my ($scanlines,$scan_data) = @_;
1.200     albertel 8912:     #FIXME really would prefer a scantron directory
1.257     albertel 8913:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8914:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 8915:     if ($scanlines) {
                   8916: 	my $prefix='scantron_';
1.157     albertel 8917: # no need to update orig, shouldn't change
                   8918: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 8919: #		    $env{'form.scantron_selectfile'});
1.200     albertel 8920: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   8921: 			$prefix.'corrected_'.
1.257     albertel 8922: 			$env{'form.scantron_selectfile'});
1.200     albertel 8923: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   8924: 			$prefix.'skipped_'.
1.257     albertel 8925: 			$env{'form.scantron_selectfile'});
1.200     albertel 8926:     }
1.175     albertel 8927:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 8928: }
                   8929: 
1.423     albertel 8930: =pod
                   8931: 
                   8932: =item scantron_get_line
                   8933: 
1.424     albertel 8934:    Returns the correct version of the scanline
                   8935: 
                   8936:  Arguments:
                   8937:     $scanlines - hash ref that looks like the first return value from
                   8938:                  &scantron_getfile()
                   8939:     $scan_data - hash ref that looks like the second return value from
                   8940:                  &scantron_getfile()
                   8941:     $i         - number of the requested line (starts at 0)
                   8942: 
                   8943:  Returns:
                   8944:    A scanline, (either the original or the corrected one if it
                   8945:    exists), or undef if the requested scanline should be
                   8946:    skipped. (Either because it's an skipped scanline, or it's an
                   8947:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   8948:    pass.
                   8949: 
1.423     albertel 8950: =cut
                   8951: 
1.157     albertel 8952: sub scantron_get_line {
1.200     albertel 8953:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 8954:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   8955:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 8956:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   8957:     return $scanlines->{'orig'}[$i]; 
                   8958: }
                   8959: 
1.423     albertel 8960: =pod
                   8961: 
                   8962: =item scantron_todo_count
                   8963: 
1.424     albertel 8964:     Counts the number of scanlines that need processing.
                   8965: 
                   8966:  Arguments:
                   8967:     $scanlines - hash ref that looks like the first return value from
                   8968:                  &scantron_getfile()
                   8969:     $scan_data - hash ref that looks like the second return value from
                   8970:                  &scantron_getfile()
                   8971: 
                   8972:  Returns:
                   8973:     $count - number of scanlines to process
                   8974: 
1.423     albertel 8975: =cut
                   8976: 
1.200     albertel 8977: sub get_todo_count {
                   8978:     my ($scanlines,$scan_data)=@_;
                   8979:     my $count=0;
                   8980:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8981: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   8982: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8983: 	$count++;
                   8984:     }
                   8985:     return $count;
                   8986: }
                   8987: 
1.423     albertel 8988: =pod
                   8989: 
                   8990: =item scantron_put_line
                   8991: 
1.659     raeburn  8992:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 8993:     data file.
                   8994: 
                   8995:  Arguments:
                   8996:     $scanlines - hash ref that looks like the first return value from
                   8997:                  &scantron_getfile()
                   8998:     $scan_data - hash ref that looks like the second return value from
                   8999:                  &scantron_getfile()
                   9000:     $i         - line number to update
                   9001:     $newline   - contents of the updated scanline
                   9002:     $skip      - if true make the line for skipping and update the
                   9003:                  'skipped' file
                   9004: 
1.423     albertel 9005: =cut
                   9006: 
1.157     albertel 9007: sub scantron_put_line {
1.200     albertel 9008:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 9009:     if ($skip) {
                   9010: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 9011: 	&start_skipping($scan_data,$i);
1.157     albertel 9012: 	return;
                   9013:     }
                   9014:     $scanlines->{'corrected'}[$i]=$newline;
                   9015: }
                   9016: 
1.423     albertel 9017: =pod
                   9018: 
                   9019: =item scantron_clear_skip
                   9020: 
1.424     albertel 9021:    Remove a line from the 'skipped' file
                   9022: 
                   9023:  Arguments:
                   9024:     $scanlines - hash ref that looks like the first return value from
                   9025:                  &scantron_getfile()
                   9026:     $scan_data - hash ref that looks like the second return value from
                   9027:                  &scantron_getfile()
                   9028:     $i         - line number to update
                   9029: 
1.423     albertel 9030: =cut
                   9031: 
1.376     albertel 9032: sub scantron_clear_skip {
                   9033:     my ($scanlines,$scan_data,$i)=@_;
                   9034:     if (exists($scanlines->{'skipped'}[$i])) {
                   9035: 	undef($scanlines->{'skipped'}[$i]);
                   9036: 	return 1;
                   9037:     }
                   9038:     return 0;
                   9039: }
                   9040: 
1.423     albertel 9041: =pod
                   9042: 
                   9043: =item scantron_filter_not_exam
                   9044: 
1.424     albertel 9045:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   9046:    filter out resources that are not marked as 'exam' mode
                   9047: 
1.423     albertel 9048: =cut
                   9049: 
1.334     albertel 9050: sub scantron_filter_not_exam {
                   9051:     my ($curres)=@_;
                   9052:     
                   9053:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   9054: 	# if the user has asked to not have either hidden
                   9055: 	# or 'randomout' controlled resources to be graded
                   9056: 	# don't include them
                   9057: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   9058: 	    && $curres->randomout) {
                   9059: 	    return 0;
                   9060: 	}
                   9061: 	return 1;
                   9062:     }
                   9063:     return 0;
                   9064: }
                   9065: 
1.423     albertel 9066: =pod
                   9067: 
                   9068: =item scantron_validate_sequence
                   9069: 
1.424     albertel 9070:     Validates the selected sequence, checking for resource that are
                   9071:     not set to exam mode.
                   9072: 
1.423     albertel 9073: =cut
                   9074: 
1.334     albertel 9075: sub scantron_validate_sequence {
                   9076:     my ($r,$currentphase) = @_;
                   9077: 
                   9078:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9079:     unless (ref($navmap)) {
                   9080:         $r->print(&navmap_errormsg());
                   9081:         return (1,$currentphase);
                   9082:     }
1.334     albertel 9083:     my (undef,undef,$sequence)=
                   9084: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9085: 
                   9086:     my $map=$navmap->getResourceByUrl($sequence);
                   9087: 
                   9088:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   9089:                                     value="ignore" />');
                   9090:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   9091: 	my @resources=
                   9092: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   9093: 	if (@resources) {
1.675     bisitz   9094: 	    $r->print(
                   9095:                 '<p class="LC_warning">'
                   9096:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   9097:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   9098:                    .' work correctly.')
                   9099:                .'</p>'
                   9100:             );
1.334     albertel 9101: 	    return (1,$currentphase);
                   9102: 	}
                   9103:     }
                   9104: 
                   9105:     return (0,$currentphase+1);
                   9106: }
                   9107: 
1.423     albertel 9108: 
                   9109: 
1.157     albertel 9110: sub scantron_validate_ID {
1.770     raeburn  9111:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 9112:     
                   9113:     #get student info
                   9114:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9115:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  9116:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 9117: 
                   9118:     #get scantron line setup
1.754     raeburn  9119:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9120:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  9121: 
                   9122:     my $nav_error;
1.649     raeburn  9123:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  9124:     if ($nav_error) {
                   9125:         $r->print(&navmap_errormsg());
                   9126:         return(1,$currentphase);
                   9127:     }
1.157     albertel 9128: 
                   9129:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  9130:     my $unsavedskips = 0;
1.157     albertel 9131:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9132: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9133: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9134: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9135: 						 $scan_data);
                   9136: 	my $id=$$scan_record{'scantron.ID'};
                   9137: 	my $found;
                   9138: 	foreach my $checkid (keys(%idmap)) {
                   9139: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   9140: 	}
                   9141: 	if ($found) {
                   9142: 	    my $username=$idmap{$found};
1.770     raeburn  9143:             if ($checksec) {
                   9144:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   9145:                     my $stusec = $classlist->{$username}->[$secidx];
                   9146:                     if ($stusec ne $checksec) {
                   9147:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9148:                             my $skip=1;
                   9149:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9150:                             if (ref($skipbysec) eq 'HASH') {
                   9151:                                 if ($stusec eq '') {
                   9152:                                     $skipbysec->{'none'} ++;
                   9153:                                 } else {
                   9154:                                     $skipbysec->{$stusec} ++;
                   9155:                                 }
                   9156:                             }
                   9157:                             $unsavedskips ++;
                   9158:                             next;
                   9159:                         }
                   9160:                     }
                   9161:                 }
                   9162:             }
1.157     albertel 9163: 	    if ($found{'ids'}{$found}) {
                   9164: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9165: 					 $line,'duplicateID',$found);
1.770     raeburn  9166:                 if ($unsavedskips) {
                   9167:                     &scantron_putfile($scanlines,$scan_data);
                   9168:                     $unsavedskips = 0;
                   9169:                 }
1.194     albertel 9170: 		return(1,$currentphase);
1.157     albertel 9171: 	    } elsif ($found{'usernames'}{$username}) {
                   9172: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9173: 					 $line,'duplicateID',$username);
1.770     raeburn  9174:                 if ($unsavedskips) {
                   9175:                     &scantron_putfile($scanlines,$scan_data);
                   9176:                     $unsavedskips = 0;
                   9177:                 }
1.194     albertel 9178: 		return(1,$currentphase);
1.157     albertel 9179: 	    }
1.186     albertel 9180: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 9181: 	    $found{'ids'}{$found}++;
                   9182: 	    $found{'usernames'}{$username}++;
                   9183: 	} else {
                   9184: 	    if ($id =~ /^\s*$/) {
1.158     albertel 9185: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  9186:                 if (($checksec && $username ne '')) {
                   9187:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   9188:                         my $stusec = $classlist->{$username}->[$secidx];
                   9189:                         if ($stusec ne $checksec) {
                   9190:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   9191:                                 my $skip=1;
                   9192:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   9193:                                 if (ref($skipbysec) eq 'HASH') {
                   9194:                                     if ($stusec eq '') {
                   9195:                                         $skipbysec->{'none'} ++;
                   9196:                                     } else {
                   9197:                                         $skipbysec->{$stusec} ++;
                   9198:                                     }
                   9199:                                 }
                   9200:                                 $unsavedskips ++;
                   9201:                                 next;
                   9202:                             }
                   9203:                         }
                   9204:                     }
                   9205: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 9206: 		    &scantron_get_correction($r,$i,$scan_record,
                   9207: 					     \%scantron_config,
                   9208: 					     $line,'duplicateID',$username);
1.770     raeburn  9209:                     if ($unsavedskips) {
                   9210:                         &scantron_putfile($scanlines,$scan_data);
                   9211:                         $unsavedskips = 0;
                   9212:                     }
1.194     albertel 9213: 		    return(1,$currentphase);
1.157     albertel 9214: 		} elsif (!defined($username)) {
                   9215: 		    &scantron_get_correction($r,$i,$scan_record,
                   9216: 					     \%scantron_config,
                   9217: 					     $line,'incorrectID');
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: 		}
                   9224: 		$found{'usernames'}{$username}++;
                   9225: 	    } else {
                   9226: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   9227: 					 $line,'incorrectID');
1.770     raeburn  9228:                 if ($unsavedskips) {
                   9229:                     &scantron_putfile($scanlines,$scan_data);
                   9230:                     $unsavedskips = 0;
                   9231:                 }
1.194     albertel 9232: 		return(1,$currentphase);
1.157     albertel 9233: 	    }
                   9234: 	}
                   9235:     }
1.770     raeburn  9236:     if ($unsavedskips) {
                   9237:         &scantron_putfile($scanlines,$scan_data);
                   9238:         $unsavedskips = 0;
                   9239:     }
1.157     albertel 9240:     return (0,$currentphase+1);
                   9241: }
                   9242: 
1.770     raeburn  9243: sub scantron_get_sections {
                   9244:     my %bysec;
                   9245:     if ($env{'form.scantron_format'} ne '') {
                   9246:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   9247:         my ($scanlines,$scan_data)=&scantron_getfile();
                   9248:         my $classlist=&Apache::loncoursedata::get_classlist();
                   9249:         my %idmap=&username_to_idmap($classlist);
                   9250:         foreach my $key (keys(%idmap)) {
                   9251:             my $lckey = lc($key);
                   9252:             $idmap{$lckey} = $idmap{$key};
                   9253:         }
                   9254:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   9255:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   9256:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   9257:             if ($line=~/^[\s\cz]*$/) { next; }
                   9258:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9259:                                                      $scan_data);
                   9260:             my $id=lc($$scan_record{'scantron.ID'});
                   9261:             if (exists($idmap{$id})) {
                   9262:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9263:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9264:                     if ($stusec eq '') {
                   9265:                         $bysec{'none'} ++;
                   9266:                     } else {
                   9267:                         $bysec{$stusec} ++;
                   9268:                     }
                   9269:                 }
                   9270:             }
                   9271:         }
                   9272:     }
                   9273:     return %bysec;
                   9274: }
1.423     albertel 9275: 
1.157     albertel 9276: sub scantron_get_correction {
1.691     raeburn  9277:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   9278:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 9279: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 9280: #to show both the current line and the previous one and allow skipping
                   9281: #the previous one or the current one
                   9282: 
1.333     albertel 9283:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   9284:         $r->print(
                   9285:             '<p class="LC_warning">'
                   9286:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   9287:                 "<b>$error</b>",
                   9288:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   9289:            ."</p> \n");
1.157     albertel 9290:     } else {
1.658     bisitz   9291:         $r->print(
                   9292:             '<p class="LC_warning">'
                   9293:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   9294:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   9295:            ."</p> \n");
                   9296:     }
                   9297:     my $message =
                   9298:         '<p>'
                   9299:        .&mt('The ID on the form is [_1]',
                   9300:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   9301:        .'<br />'
1.665     raeburn  9302:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   9303:             $$scan_record{'scantron.LastName'},
                   9304:             $$scan_record{'scantron.FirstName'})
                   9305:        .'</p>';
1.242     albertel 9306: 
1.157     albertel 9307:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   9308:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  9309:                            # Array populated for doublebubble or
                   9310:     my @lines_to_correct;  # missingbubble errors to build javascript
                   9311:                            # to validate radio button checking   
                   9312: 
1.157     albertel 9313:     if ($error =~ /ID$/) {
1.186     albertel 9314: 	if ($error eq 'incorrectID') {
1.658     bisitz   9315:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 9316: 		      "</p>\n");
1.157     albertel 9317: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   9318:             $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 9319: 	}
1.242     albertel 9320: 	$r->print($message);
1.492     albertel 9321: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 9322: 	$r->print("\n<ul><li> ");
                   9323: 	#FIXME it would be nice if this sent back the user ID and
                   9324: 	#could do partial userID matches
                   9325: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   9326: 				       'scantron_username','scantron_domain'));
                   9327: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   9328: 	$r->print("\n:\n".
1.257     albertel 9329: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 9330: 
                   9331: 	$r->print('</li>');
1.186     albertel 9332:     } elsif ($error =~ /CODE$/) {
                   9333: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   9334: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 9335: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   9336: 	    $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 9337: 	}
1.658     bisitz   9338: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   9339: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   9340:                  ."</p>\n");
1.242     albertel 9341: 	$r->print($message);
1.658     bisitz   9342: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 9343: 	$r->print("\n<br /> ");
1.194     albertel 9344: 	my $i=0;
1.273     albertel 9345: 	if ($error eq 'incorrectCODE' 
                   9346: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 9347: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 9348: 	    if ($closest > 0) {
                   9349: 		foreach my $testcode (@{$closest}) {
                   9350: 		    my $checked='';
1.569     bisitz   9351: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9352: 		    $r->print("
                   9353:    <label>
1.569     bisitz   9354:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 9355:        ".&mt("Use the similar CODE [_1] instead.",
                   9356: 	    "<b><tt>".$testcode."</tt></b>")."
                   9357:     </label>
                   9358:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 9359: 		    $r->print("\n<br />");
                   9360: 		    $i++;
                   9361: 		}
1.194     albertel 9362: 	    }
                   9363: 	}
1.273     albertel 9364: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   9365: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 9366: 	    $r->print("
                   9367:     <label>
1.569     bisitz   9368:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  9369:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 9370: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   9371:     </label>");
1.273     albertel 9372: 	    $r->print("\n<br />");
                   9373: 	}
1.194     albertel 9374: 
1.597     wenzelju 9375: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 9376: function change_radio(field) {
1.190     albertel 9377:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 9378:     var i;
                   9379:     for (i=0;i<slct.length;i++) {
                   9380:         if (slct[i].value==field) { slct[i].checked=true; }
                   9381:     }
                   9382: }
                   9383: ENDSCRIPT
1.187     albertel 9384: 	my $href="/adm/pickcode?".
1.359     www      9385: 	   "form=".&escape("scantronupload").
                   9386: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   9387: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   9388: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   9389: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 9390: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 9391: 	    $r->print("
                   9392:     <label>
                   9393:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   9394:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   9395: 	     "<a target='_blank' href='$href'>","</a>")."
                   9396:     </label> 
1.558     bisitz   9397:     ".&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 9398: 	    $r->print("\n<br />");
                   9399: 	}
1.492     albertel 9400: 	$r->print("
                   9401:     <label>
                   9402:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   9403:        ".&mt("Use [_1] as the CODE.",
                   9404: 	     "</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 9405: 	$r->print("\n<br /><br />");
1.157     albertel 9406:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   9407: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     9408: 
                   9409: 	# The form field scantron_questions is acutally a list of line numbers.
                   9410: 	# represented by this form so:
                   9411: 
1.691     raeburn  9412: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9413:                                                 $respnumlookup,$startline);
1.497     foxr     9414: 
1.157     albertel 9415: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9416: 		  $line_list.'" />');
1.242     albertel 9417: 	$r->print($message);
1.492     albertel 9418: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 9419: 	foreach my $question (@{$arg}) {
1.503     raeburn  9420: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9421:                                                    $scan_record, $error,
                   9422:                                                    $randomorder,$randompick,
                   9423:                                                    $respnumlookup,$startline);
1.524     raeburn  9424:             push(@lines_to_correct,@linenums);
1.157     albertel 9425: 	}
1.503     raeburn  9426:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9427:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   9428: 	$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 9429: 	$r->print($message);
1.492     albertel 9430: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  9431: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     9432: 
1.503     raeburn  9433: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     9434: 	# a list of question numbers. Therefore:
                   9435: 	#
1.691     raeburn  9436: 
                   9437: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   9438:                                                 $respnumlookup,$startline);
1.497     foxr     9439: 
1.157     albertel 9440: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     9441: 		  $line_list.'" />');
1.157     albertel 9442: 	foreach my $question (@{$arg}) {
1.503     raeburn  9443: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  9444:                                                    $scan_record, $error,
                   9445:                                                    $randomorder,$randompick,
                   9446:                                                    $respnumlookup,$startline);
1.524     raeburn  9447:             push(@lines_to_correct,@linenums);
1.157     albertel 9448: 	}
1.503     raeburn  9449:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 9450:     } else {
                   9451: 	$r->print("\n<ul>");
                   9452:     }
                   9453:     $r->print("\n</li></ul>");
1.497     foxr     9454: }
                   9455: 
1.503     raeburn  9456: sub verify_bubbles_checked {
                   9457:     my (@ansnums) = @_;
                   9458:     my $ansnumstr = join('","',@ansnums);
                   9459:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  9460:     &js_escape(\$warning);
1.767     raeburn  9461:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  9462: function verify_bubble_radio(form) {
                   9463:     var ansnumArray = new Array ("$ansnumstr");
                   9464:     var need_bubble_count = 0;
                   9465:     for (var i=0; i<ansnumArray.length; i++) {
                   9466:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   9467:             var bubble_picked = 0; 
                   9468:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   9469:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   9470:                     bubble_picked = 1;
                   9471:                 }
                   9472:             }
                   9473:             if (bubble_picked == 0) {
                   9474:                 need_bubble_count ++;
                   9475:             }
                   9476:         }
                   9477:     }
                   9478:     if (need_bubble_count) {
                   9479:         alert("$warning");
                   9480:         return;
                   9481:     }
                   9482:     form.submit(); 
                   9483: }
                   9484: ENDSCRIPT
                   9485:     return $output;
                   9486: }
                   9487: 
1.497     foxr     9488: =pod
                   9489: 
                   9490: =item  questions_to_line_list
1.157     albertel 9491: 
1.497     foxr     9492: Converts a list of questions into a string of comma separated
                   9493: line numbers in the answer sheet used by the questions.  This is
                   9494: used to fill in the scantron_questions form field.
                   9495: 
                   9496:   Arguments:
                   9497:      questions    - Reference to an array of questions.
1.691     raeburn  9498:      randomorder  - True if randomorder in use.
                   9499:      randompick   - True if randompick in use.
                   9500:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9501:                      for current line to question number used for same question
                   9502:                      in "Master Seqence" (as seen by Course Coordinator).
                   9503:      startline    - Reference to hash where key is question number (0 is first)
                   9504:                     and key is number of first bubble line for current student
                   9505:                     or code-based randompick and/or randomorder.
1.693     raeburn  9506: 
1.497     foxr     9507: =cut
                   9508: 
                   9509: 
                   9510: sub questions_to_line_list {
1.691     raeburn  9511:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     9512:     my @lines;
                   9513: 
1.503     raeburn  9514:     foreach my $item (@{$questions}) {
                   9515:         my $question = $item;
                   9516:         my ($first,$count,$last);
                   9517:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   9518:             $question = $1;
                   9519:             my $subquestion = $2;
1.691     raeburn  9520:             my $responsenum = $question-1;
                   9521:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9522:                 $responsenum = $respnumlookup->{$question-1};
                   9523:                 if (ref($startline) eq 'HASH') {
                   9524:                     $first = $startline->{$question-1} + 1;
                   9525:                 }
                   9526:             } else {
                   9527:                 $first = $first_bubble_line{$responsenum} + 1;
                   9528:             }
                   9529:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9530:             my $subcount = 1;
                   9531:             while ($subcount<$subquestion) {
                   9532:                 $first += $subans[$subcount-1];
                   9533:                 $subcount ++;
                   9534:             }
                   9535:             $count = $subans[$subquestion-1];
                   9536:         } else {
1.691     raeburn  9537:             my $responsenum = $question-1;
                   9538:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9539:                 $responsenum = $respnumlookup->{$question-1};
                   9540:                 if (ref($startline) eq 'HASH') {
                   9541:                     $first = $startline->{$question-1} + 1;
                   9542:                 }
                   9543:             } else {
                   9544:                 $first = $first_bubble_line{$responsenum} + 1;
                   9545:             }
                   9546: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9547:         }
1.506     raeburn  9548:         $last = $first+$count-1;
1.503     raeburn  9549:         push(@lines, ($first..$last));
1.497     foxr     9550:     }
                   9551:     return join(',', @lines);
                   9552: }
                   9553: 
                   9554: =pod 
                   9555: 
                   9556: =item prompt_for_corrections
                   9557: 
                   9558: Prompts for a potentially multiline correction to the
                   9559: user's bubbling (factors out common code from scantron_get_correction
                   9560: for multi and missing bubble cases).
                   9561: 
                   9562:  Arguments:
                   9563:    $r           - Apache request object.
                   9564:    $question    - The question number to prompt for.
                   9565:    $scan_config - The scantron file configuration hash.
                   9566:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  9567:    $error       - Type of error
1.691     raeburn  9568:    $randomorder - True if randomorder in use.
                   9569:    $randompick  - True if randompick in use.
                   9570:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9571:                     for current line to question number used for same question
                   9572:                     in "Master Seqence" (as seen by Course Coordinator).
                   9573:    $startline   - Reference to hash where key is question number (0 is first)
                   9574:                   and value is number of first bubble line for current student
                   9575:                   or code-based randompick and/or randomorder.
                   9576: 
1.497     foxr     9577: 
                   9578:  Implicit inputs:
                   9579:    %bubble_lines_per_response   - Starting line numbers for each question.
                   9580:                                   Numbered from 0 (but question numbers are from
                   9581:                                   1.
                   9582:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  9583:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   9584:                                   type problems render as separate sub-questions, 
1.503     raeburn  9585:                                   in exam mode. This hash contains a 
                   9586:                                   comma-separated list of the lines per 
                   9587:                                   sub-question.
1.510     raeburn  9588:    %responsetype_per_response   - essayresponse, formularesponse,
                   9589:                                   stringresponse, imageresponse, reactionresponse,
                   9590:                                   and organicresponse type problem parts can have
1.503     raeburn  9591:                                   multiple lines per response if the weight
                   9592:                                   assigned exceeds 10.  In this case, only
                   9593:                                   one bubble per line is permitted, but more 
                   9594:                                   than one line might contain bubbles, e.g.
                   9595:                                   bubbling of: line 1 - J, line 2 - J, 
                   9596:                                   line 3 - B would assign 22 points.  
1.497     foxr     9597: 
                   9598: =cut
                   9599: 
                   9600: sub prompt_for_corrections {
1.691     raeburn  9601:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   9602:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  9603:     my ($current_line,$lines);
                   9604:     my @linenums;
                   9605:     my $questionnum = $question;
1.691     raeburn  9606:     my ($first,$responsenum);
1.503     raeburn  9607:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   9608:         $question = $1;
                   9609:         my $subquestion = $2;
1.691     raeburn  9610:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9611:             $responsenum = $respnumlookup->{$question-1};
                   9612:             if (ref($startline) eq 'HASH') {
                   9613:                 $first = $startline->{$question-1};
                   9614:             }
                   9615:         } else {
                   9616:             $responsenum = $question-1;
1.714     raeburn  9617:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  9618:         }
                   9619:         $current_line = $first + 1 ;
                   9620:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9621:         my $subcount = 1;
                   9622:         while ($subcount<$subquestion) {
                   9623:             $current_line += $subans[$subcount-1];
                   9624:             $subcount ++;
                   9625:         }
                   9626:         $lines = $subans[$subquestion-1];
                   9627:     } else {
1.691     raeburn  9628:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9629:             $responsenum = $respnumlookup->{$question-1};
                   9630:             if (ref($startline) eq 'HASH') { 
                   9631:                 $first = $startline->{$question-1};
                   9632:             }
                   9633:         } else {
                   9634:             $responsenum = $question-1;
                   9635:             $first = $first_bubble_line{$responsenum};
                   9636:         }
                   9637:         $current_line = $first + 1;
                   9638:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9639:     }
1.497     foxr     9640:     if ($lines > 1) {
1.503     raeburn  9641:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  9642:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   9643:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   9644:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   9645:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   9646:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   9647:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   9648:             $r->print(
                   9649:                 &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)
                   9650:                .'<br /><br />'
                   9651:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   9652:                .'<br />'
                   9653:                .&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.')
                   9654:                .'<br />'
                   9655:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   9656:                .'<br /><br />'
                   9657:             );
1.503     raeburn  9658:         } else {
                   9659:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   9660:         }
1.497     foxr     9661:     }
                   9662:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  9663:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  9664: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  9665: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  9666:         push(@linenums,$current_line);
1.497     foxr     9667: 	$current_line++;
                   9668:     }
                   9669:     if ($lines > 1) {
                   9670: 	$r->print("<hr /><br />");
                   9671:     }
1.503     raeburn  9672:     return @linenums;
1.157     albertel 9673: }
1.423     albertel 9674: 
                   9675: =pod
                   9676: 
                   9677: =item scantron_bubble_selector
                   9678:   
                   9679:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 9680:    possibly showing the existing the selected bubbles if known
1.423     albertel 9681: 
                   9682:  Arguments:
                   9683:     $r           - Apache request object
1.754     raeburn  9684:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     9685:     $line        - Number of the line being displayed.
1.503     raeburn  9686:     $questionnum - Question number (may include subquestion)
                   9687:     $error       - Type of error.
1.497     foxr     9688:     @selected    - Array of bubbles picked on this line.
1.423     albertel 9689: 
                   9690: =cut
                   9691: 
1.157     albertel 9692: sub scantron_bubble_selector {
1.503     raeburn  9693:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 9694:     my $max=$$scan_config{'Qlength'};
1.274     albertel 9695: 
                   9696:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  9697:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   9698:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   9699:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   9700:             $max=$$scan_config{'BubblesPerRow'};
                   9701:             if (($scmode eq 'number') && ($max > 10)) {
                   9702:                 $max = 10;
                   9703:             } elsif (($scmode eq 'letter') && $max > 26) {
                   9704:                 $max = 26;
                   9705:             }
                   9706:         } else {
                   9707:             $max = 10;
                   9708:         }
                   9709:     }
1.274     albertel 9710: 
1.157     albertel 9711:     my @alphabet=('A'..'Z');
1.503     raeburn  9712:     $r->print(&Apache::loncommon::start_data_table().
                   9713:               &Apache::loncommon::start_data_table_row());
                   9714:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     9715:     for (my $i=0;$i<$max+1;$i++) {
                   9716: 	$r->print("\n".'<td align="center">');
                   9717: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   9718: 	else { $r->print('&nbsp;'); }
                   9719: 	$r->print('</td>');
                   9720:     }
1.503     raeburn  9721:     $r->print(&Apache::loncommon::end_data_table_row().
                   9722:               &Apache::loncommon::start_data_table_row());
1.497     foxr     9723:     for (my $i=0;$i<$max;$i++) {
                   9724: 	$r->print("\n".
                   9725: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   9726: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   9727:     }
1.503     raeburn  9728:     my $nobub_checked = ' ';
                   9729:     if ($error eq 'missingbubble') {
                   9730:         $nobub_checked = ' checked = "checked" ';
                   9731:     }
                   9732:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   9733: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   9734:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   9735:               $line.'" value="'.$questionnum.'" /></td>');
                   9736:     $r->print(&Apache::loncommon::end_data_table_row().
                   9737:               &Apache::loncommon::end_data_table());
1.157     albertel 9738: }
                   9739: 
1.423     albertel 9740: =pod
                   9741: 
                   9742: =item num_matches
                   9743: 
1.424     albertel 9744:    Counts the number of characters that are the same between the two arguments.
                   9745: 
                   9746:  Arguments:
                   9747:    $orig - CODE from the scanline
                   9748:    $code - CODE to match against
                   9749: 
                   9750:  Returns:
                   9751:    $count - integer count of the number of same characters between the
                   9752:             two arguments
                   9753: 
1.423     albertel 9754: =cut
                   9755: 
1.194     albertel 9756: sub num_matches {
                   9757:     my ($orig,$code) = @_;
                   9758:     my @code=split(//,$code);
                   9759:     my @orig=split(//,$orig);
                   9760:     my $same=0;
                   9761:     for (my $i=0;$i<scalar(@code);$i++) {
                   9762: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   9763:     }
                   9764:     return $same;
                   9765: }
                   9766: 
1.423     albertel 9767: =pod
                   9768: 
                   9769: =item scantron_get_closely_matching_CODEs
                   9770: 
1.424     albertel 9771:    Cycles through all CODEs and finds the set that has the greatest
                   9772:    number of same characters as the provided CODE
                   9773: 
                   9774:  Arguments:
                   9775:    $allcodes - hash ref returned by &get_codes()
                   9776:    $CODE     - CODE from the current scanline
                   9777: 
                   9778:  Returns:
                   9779:    2 element list
                   9780:     - first elements is number of how closely matching the best fit is 
                   9781:       (5 means best set has 5 matching characters)
                   9782:     - second element is an arrary ref containing the set of valid CODEs
                   9783:       that best fit the passed in CODE
                   9784: 
1.423     albertel 9785: =cut
                   9786: 
1.194     albertel 9787: sub scantron_get_closely_matching_CODEs {
                   9788:     my ($allcodes,$CODE)=@_;
                   9789:     my @CODEs;
                   9790:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   9791: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   9792:     }
                   9793: 
                   9794:     return ($#CODEs,$CODEs[-1]);
                   9795: }
                   9796: 
1.423     albertel 9797: =pod
                   9798: 
                   9799: =item get_codes
                   9800: 
1.424     albertel 9801:    Builds a hash which has keys of all of the valid CODEs from the selected
                   9802:    set of remembered CODEs.
                   9803: 
                   9804:  Arguments:
                   9805:   $old_name - name of the set of remembered CODEs
                   9806:   $cdom     - domain of the course
                   9807:   $cnum     - internal course name
                   9808: 
                   9809:  Returns:
                   9810:   %allcodes - keys are the valid CODEs, values are all 1
                   9811: 
1.423     albertel 9812: =cut
                   9813: 
1.194     albertel 9814: sub get_codes {
1.280     foxr     9815:     my ($old_name, $cdom, $cnum) = @_;
                   9816:     if (!$old_name) {
                   9817: 	$old_name=$env{'form.scantron_CODElist'};
                   9818:     }
                   9819:     if (!$cdom) {
                   9820: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9821:     }
                   9822:     if (!$cnum) {
                   9823: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   9824:     }
1.278     albertel 9825:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   9826: 				    $cdom,$cnum);
                   9827:     my %allcodes;
                   9828:     if ($result{"type\0$old_name"} eq 'number') {
                   9829: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   9830:     } else {
                   9831: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   9832:     }
1.194     albertel 9833:     return %allcodes;
                   9834: }
                   9835: 
1.423     albertel 9836: =pod
                   9837: 
                   9838: =item scantron_validate_CODE
                   9839: 
1.424     albertel 9840:    Validates all scanlines in the selected file to not have any
                   9841:    invalid or underspecified CODEs and that none of the codes are
                   9842:    duplicated if this was requested.
                   9843: 
1.423     albertel 9844: =cut
                   9845: 
1.157     albertel 9846: sub scantron_validate_CODE {
                   9847:     my ($r,$currentphase) = @_;
1.754     raeburn  9848:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 9849:     if ($scantron_config{'CODElocation'} &&
                   9850: 	$scantron_config{'CODEstart'} &&
                   9851: 	$scantron_config{'CODElength'}) {
1.257     albertel 9852: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 9853: 	    &FIXME_blow_up()
                   9854: 	}
                   9855:     } else {
                   9856: 	return (0,$currentphase+1);
                   9857:     }
                   9858:     
                   9859:     my %usedCODEs;
                   9860: 
1.194     albertel 9861:     my %allcodes=&get_codes();
1.186     albertel 9862: 
1.582     raeburn  9863:     my $nav_error;
1.649     raeburn  9864:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  9865:     if ($nav_error) {
                   9866:         $r->print(&navmap_errormsg());
                   9867:         return(1,$currentphase);
                   9868:     }
1.447     foxr     9869: 
1.186     albertel 9870:     my ($scanlines,$scan_data)=&scantron_getfile();
                   9871:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9872: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 9873: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9874: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9875: 						 $scan_data);
                   9876: 	my $CODE=$$scan_record{'scantron.CODE'};
                   9877: 	my $error=0;
1.224     albertel 9878: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   9879: 	    &scantron_get_correction($r,$i,$scan_record,
                   9880: 				     \%scantron_config,
                   9881: 				     $line,'incorrectCODE',\%allcodes);
                   9882: 	    return(1,$currentphase);
                   9883: 	}
1.221     albertel 9884: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   9885: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 9886: 	    &scantron_get_correction($r,$i,$scan_record,
                   9887: 				     \%scantron_config,
1.194     albertel 9888: 				     $line,'incorrectCODE',\%allcodes);
                   9889: 	    return(1,$currentphase);
1.186     albertel 9890: 	}
1.214     albertel 9891: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 9892: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 9893: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 9894: 	    &scantron_get_correction($r,$i,$scan_record,
                   9895: 				     \%scantron_config,
1.194     albertel 9896: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   9897: 	    return(1,$currentphase);
1.186     albertel 9898: 	}
1.524     raeburn  9899: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 9900:     }
1.157     albertel 9901:     return (0,$currentphase+1);
                   9902: }
                   9903: 
1.423     albertel 9904: =pod
                   9905: 
                   9906: =item scantron_validate_doublebubble
                   9907: 
1.424     albertel 9908:    Validates all scanlines in the selected file to not have any
                   9909:    bubble lines with multiple bubbles marked.
                   9910: 
1.423     albertel 9911: =cut
                   9912: 
1.157     albertel 9913: sub scantron_validate_doublebubble {
                   9914:     my ($r,$currentphase) = @_;
                   9915:     #get student info
                   9916:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9917:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  9918:     my (undef,undef,$sequence)=
                   9919:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 9920: 
                   9921:     #get scantron line setup
1.754     raeburn  9922:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9923:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  9924: 
                   9925:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9926:     unless (ref($navmap)) {
                   9927:         $r->print(&navmap_errormsg());
                   9928:         return(1,$currentphase);
                   9929:     }
                   9930:     my $map=$navmap->getResourceByUrl($sequence);
                   9931:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9932:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9933:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   9934:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9935: 
1.583     raeburn  9936:     my $nav_error;
1.691     raeburn  9937:     if (ref($map)) {
                   9938:         $randomorder = $map->randomorder();
                   9939:         $randompick = $map->randompick();
1.788     raeburn  9940:         unless ($randomorder || $randompick) {
                   9941:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9942:                 if ($res->randomorder()) {
                   9943:                     $randomorder = 1;
                   9944:                 }
                   9945:                 if ($res->randompick()) {
                   9946:                     $randompick = 1;
                   9947:                 }
                   9948:                 last if ($randomorder || $randompick);
                   9949:             }
                   9950:         }
1.691     raeburn  9951:         if ($randomorder || $randompick) {
                   9952:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9953:             if ($nav_error) {
                   9954:                 $r->print(&navmap_errormsg());
                   9955:                 return(1,$currentphase);
                   9956:             }
                   9957:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9958:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   9959:         }
                   9960:     } else {
                   9961:         $r->print(&navmap_errormsg());
                   9962:         return(1,$currentphase);
                   9963:     }
                   9964: 
1.649     raeburn  9965:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  9966:     if ($nav_error) {
                   9967:         $r->print(&navmap_errormsg());
                   9968:         return(1,$currentphase);
                   9969:     }
1.447     foxr     9970: 
1.157     albertel 9971:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9972: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9973: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9974: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9975: 						 $scan_data,undef,\%idmap,$randomorder,
                   9976:                                                  $randompick,$sequence,\@master_seq,
                   9977:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9978:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 9979: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   9980: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   9981: 				 'doublebubble',
1.691     raeburn  9982: 				 $$scan_record{'scantron.doubleerror'},
                   9983:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 9984:     	return (1,$currentphase);
                   9985:     }
                   9986:     return (0,$currentphase+1);
                   9987: }
                   9988: 
1.423     albertel 9989: 
1.503     raeburn  9990: sub scantron_get_maxbubble {
1.649     raeburn  9991:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 9992:     if (defined($env{'form.scantron_maxbubble'}) &&
                   9993: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     9994: 	&restore_bubble_lines();
1.257     albertel 9995: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 9996:     }
1.330     albertel 9997: 
1.447     foxr     9998:     my (undef, undef, $sequence) =
1.257     albertel 9999: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 10000: 
1.447     foxr     10001:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10002:     unless (ref($navmap)) {
                   10003:         if (ref($nav_error)) {
                   10004:             $$nav_error = 1;
                   10005:         }
1.591     raeburn  10006:         return;
1.582     raeburn  10007:     }
1.191     albertel 10008:     my $map=$navmap->getResourceByUrl($sequence);
                   10009:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  10010:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 10011: 
                   10012:     &Apache::lonxml::clear_problem_counter();
                   10013: 
1.557     raeburn  10014:     my $uname       = $env{'user.name'};
                   10015:     my $udom        = $env{'user.domain'};
1.435     foxr     10016:     my $cid         = $env{'request.course.id'};
                   10017:     my $total_lines = 0;
                   10018:     %bubble_lines_per_response = ();
1.447     foxr     10019:     %first_bubble_line         = ();
1.503     raeburn  10020:     %subdivided_bubble_lines   = ();
                   10021:     %responsetype_per_response = ();
1.691     raeburn  10022:     %masterseq_id_responsenum  = ();
1.554     raeburn  10023: 
1.447     foxr     10024:     my $response_number = 0;
                   10025:     my $bubble_line     = 0;
1.191     albertel 10026:     foreach my $resource (@resources) {
1.691     raeburn  10027:         my $resid = $resource->id(); 
1.672     raeburn  10028:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   10029:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  10030:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   10031: 	    foreach my $part_id (@{$parts}) {
                   10032:                 my $lines;
                   10033: 
                   10034: 	        # TODO - make this a persistent hash not an array.
                   10035: 
                   10036:                 # optionresponse, matchresponse and rankresponse type items 
                   10037:                 # render as separate sub-questions in exam mode.
                   10038:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   10039:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   10040:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   10041:                     my ($numbub,$numshown);
                   10042:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   10043:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   10044:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   10045:                         }
                   10046:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   10047:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   10048:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   10049:                         }
                   10050:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   10051:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   10052:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   10053:                         }
                   10054:                     }
                   10055:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   10056:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   10057:                     }
1.649     raeburn  10058:                     my $bubbles_per_row =
                   10059:                         &bubblesheet_bubbles_per_row($scantron_config);
                   10060:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   10061:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  10062:                         $inner_bubble_lines++;
                   10063:                     }
                   10064:                     for (my $i=0; $i<$numshown; $i++) {
                   10065:                         $subdivided_bubble_lines{$response_number} .= 
                   10066:                             $inner_bubble_lines.',';
                   10067:                     }
                   10068:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   10069:                     $lines = $numshown * $inner_bubble_lines;
                   10070:                 } else {
                   10071:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  10072:                 }
1.542     raeburn  10073: 
                   10074:                 $first_bubble_line{$response_number} = $bubble_line;
                   10075: 	        $bubble_lines_per_response{$response_number} = $lines;
                   10076:                 $responsetype_per_response{$response_number} = 
                   10077:                     $analysis->{$part_id.'.type'};
1.691     raeburn  10078:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  10079: 	        $response_number++;
                   10080: 
                   10081: 	        $bubble_line +=  $lines;
                   10082: 	        $total_lines +=  $lines;
                   10083: 	    }
                   10084:         }
                   10085:     }
1.552     raeburn  10086:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  10087: 
                   10088:     &save_bubble_lines();
                   10089:     $env{'form.scantron_maxbubble'} =
                   10090: 	$total_lines;
                   10091:     return $env{'form.scantron_maxbubble'};
                   10092: }
1.523     raeburn  10093: 
1.649     raeburn  10094: sub bubblesheet_bubbles_per_row {
                   10095:     my ($scantron_config) = @_;
                   10096:     my $bubbles_per_row;
                   10097:     if (ref($scantron_config) eq 'HASH') {
                   10098:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   10099:     }
                   10100:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   10101:         $bubbles_per_row = 10;
                   10102:     }
                   10103:     return $bubbles_per_row;
                   10104: }
                   10105: 
1.157     albertel 10106: sub scantron_validate_missingbubbles {
                   10107:     my ($r,$currentphase) = @_;
                   10108:     #get student info
                   10109:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10110:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  10111:     my (undef,undef,$sequence)=
                   10112:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 10113: 
                   10114:     #get scantron line setup
1.754     raeburn  10115:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 10116:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  10117: 
                   10118:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10119:     unless (ref($navmap)) {
                   10120:         $r->print(&navmap_errormsg());
                   10121:         return(1,$currentphase);
                   10122:     }
                   10123: 
                   10124:     my $map=$navmap->getResourceByUrl($sequence);
                   10125:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10126:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10127:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   10128:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10129: 
1.582     raeburn  10130:     my $nav_error;
1.691     raeburn  10131:     if (ref($map)) {
                   10132:         $randomorder = $map->randomorder();
                   10133:         $randompick = $map->randompick();
1.788     raeburn  10134:         unless ($randomorder || $randompick) {
                   10135:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10136:                 if ($res->randomorder()) {
                   10137:                     $randomorder = 1;
                   10138:                 }
                   10139:                 if ($res->randompick()) {
                   10140:                     $randompick = 1;
                   10141:                 }
                   10142:                 last if ($randomorder || $randompick);
                   10143:             }
                   10144:         }
1.691     raeburn  10145:         if ($randomorder || $randompick) {
                   10146:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10147:             if ($nav_error) {
                   10148:                 $r->print(&navmap_errormsg());
                   10149:                 return(1,$currentphase);
                   10150:             }
                   10151:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10152:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   10153:         }
                   10154:     } else {
                   10155:         $r->print(&navmap_errormsg());
                   10156:         return(1,$currentphase);
                   10157:     }
                   10158: 
                   10159: 
1.649     raeburn  10160:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  10161:     if ($nav_error) {
1.691     raeburn  10162:         $r->print(&navmap_errormsg());
1.693     raeburn  10163:         return(1,$currentphase);
1.582     raeburn  10164:     }
1.691     raeburn  10165: 
1.157     albertel 10166:     if (!$max_bubble) { $max_bubble=2**31; }
                   10167:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 10168: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10169: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  10170: 	my $scan_record =
                   10171:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   10172: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   10173:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   10174:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 10175: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   10176: 	my @to_correct;
1.470     foxr     10177: 	
                   10178: 	# Probably here's where the error is...
                   10179: 
1.157     albertel 10180: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  10181:             my $lastbubble;
                   10182:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   10183:                my $question = $1;
                   10184:                my $subquestion = $2;
1.691     raeburn  10185:                my ($first,$responsenum);
                   10186:                if ($randomorder || $randompick) {
                   10187:                    $responsenum = $respnumlookup{$question-1};
                   10188:                    $first = $startline{$question-1};
                   10189:                } else {
                   10190:                    $responsenum = $question-1; 
                   10191:                    $first = $first_bubble_line{$responsenum};
                   10192:                }
                   10193:                if (!defined($first)) { next; }
                   10194:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  10195:                my $subcount = 1;
                   10196:                while ($subcount<$subquestion) {
                   10197:                    $first += $subans[$subcount-1];
                   10198:                    $subcount ++;
                   10199:                }
                   10200:                my $count = $subans[$subquestion-1];
                   10201:                $lastbubble = $first + $count;
                   10202:             } else {
1.691     raeburn  10203:                my ($first,$responsenum);
                   10204:                if ($randomorder || $randompick) {
                   10205:                    $responsenum = $respnumlookup{$missing-1};
                   10206:                    $first = $startline{$missing-1};
                   10207:                } else {
                   10208:                    $responsenum = $missing-1;
                   10209:                    $first = $first_bubble_line{$responsenum};
                   10210:                }
                   10211:                if (!defined($first)) { next; }
                   10212:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  10213:             }
                   10214:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 10215: 	    push(@to_correct,$missing);
                   10216: 	}
                   10217: 	if (@to_correct) {
                   10218: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  10219: 				     $line,'missingbubble',\@to_correct,
                   10220:                                      $randomorder,$randompick,\%respnumlookup,
                   10221:                                      \%startline);
1.157     albertel 10222: 	    return (1,$currentphase);
                   10223: 	}
                   10224: 
                   10225:     }
                   10226:     return (0,$currentphase+1);
                   10227: }
                   10228: 
1.663     raeburn  10229: sub hand_bubble_option {
                   10230:     my (undef, undef, $sequence) =
                   10231:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10232:     return if ($sequence eq '');
                   10233:     my $navmap = Apache::lonnavmaps::navmap->new();
                   10234:     unless (ref($navmap)) {
                   10235:         return;
                   10236:     }
                   10237:     my $needs_hand_bubbles;
                   10238:     my $map=$navmap->getResourceByUrl($sequence);
                   10239:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   10240:     foreach my $res (@resources) {
                   10241:         if (ref($res)) {
                   10242:             if ($res->is_problem()) {
                   10243:                 my $partlist = $res->parts();
                   10244:                 foreach my $part (@{ $partlist }) {
                   10245:                     my @types = $res->responseType($part);
                   10246:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   10247:                         $needs_hand_bubbles = 1;
                   10248:                         last;
                   10249:                     }
                   10250:                 }
                   10251:             }
                   10252:         }
                   10253:     }
                   10254:     if ($needs_hand_bubbles) {
1.754     raeburn  10255:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  10256:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   10257:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   10258:                &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 />').
                   10259:                '<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  10260:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  10261:     }
                   10262:     return;
                   10263: }
1.423     albertel 10264: 
1.82      albertel 10265: sub scantron_process_students {
1.608     www      10266:     my ($r,$symb) = @_;
1.513     foxr     10267: 
1.257     albertel 10268:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     10269:     if (!$symb) {
                   10270: 	return '';
                   10271:     }
1.324     albertel 10272:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 10273: 
1.754     raeburn  10274:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  10275:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 10276:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 10277:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10278:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 10279:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10280:     unless (ref($navmap)) {
                   10281:         $r->print(&navmap_errormsg());
                   10282:         return '';
1.691     raeburn  10283:     }
1.83      albertel 10284:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10285:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.788     raeburn  10286:         %grader_randomlists_by_symb,%symb_for_examcode);
1.677     raeburn  10287:     if (ref($map)) {
                   10288:         $randomorder = $map->randomorder();
1.689     raeburn  10289:         $randompick = $map->randompick();
1.788     raeburn  10290:         unless ($randomorder || $randompick) {
                   10291:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10292:                 if ($res->randomorder()) {
                   10293:                     $randomorder = 1;
                   10294:                 }
                   10295:                 if ($res->randompick()) {
                   10296:                     $randompick = 1;
                   10297:                 }
                   10298:                 last if ($randomorder || $randompick);
                   10299:             }
                   10300:         }
1.691     raeburn  10301:     } else {
                   10302:         $r->print(&navmap_errormsg());
                   10303:         return '';
1.677     raeburn  10304:     }
1.691     raeburn  10305:     my $nav_error;
1.83      albertel 10306:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10307:     if ($randomorder || $randompick) {
1.788     raeburn  10308:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
1.691     raeburn  10309:         if ($nav_error) {
                   10310:             $r->print(&navmap_errormsg());
                   10311:             return '';
                   10312:         }
                   10313:     }
1.557     raeburn  10314:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  10315:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  10316: 
1.554     raeburn  10317:     my ($uname,$udom);
1.82      albertel 10318:     my $result= <<SCANTRONFORM;
1.81      albertel 10319: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   10320:   <input type="hidden" name="command" value="scantron_configphase" />
                   10321:   $default_form_data
                   10322: SCANTRONFORM
1.82      albertel 10323:     $r->print($result);
                   10324: 
1.770     raeburn  10325:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 10326:     my @delayqueue;
1.542     raeburn  10327:     my (%completedstudents,%scandata);
1.770     raeburn  10328: 
1.520     www      10329:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 10330:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10331:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   10332:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  10333:     $r->print('<br />');
1.140     albertel 10334:     my $start=&Time::HiRes::time();
1.158     albertel 10335:     my $i=-1;
1.542     raeburn  10336:     my $started;
1.447     foxr     10337: 
1.649     raeburn  10338:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10339:     if ($nav_error) {
                   10340:         $r->print(&navmap_errormsg());
                   10341:         return '';
                   10342:     }
                   10343: 
1.513     foxr     10344:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   10345:     # the user and return.
                   10346: 
                   10347:     if ($ssi_error) {
                   10348: 	$r->print("</form>");
                   10349: 	&ssi_print_error($r);
1.520     www      10350:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     10351: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   10352:     }
1.447     foxr     10353: 
1.755     raeburn  10354:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  10355:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  10356:     my %orderedforcode;
1.542     raeburn  10357: 
1.157     albertel 10358:     while ($i<$scanlines->{'count'}) {
                   10359:  	($uname,$udom)=('','');
                   10360:  	$i++;
1.200     albertel 10361:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 10362:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 10363: 	if ($started) {
1.667     www      10364: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 10365: 	}
                   10366: 	$started=1;
1.691     raeburn  10367:         my %respnumlookup = ();
                   10368:         my %startline = ();
                   10369:         my $total;
1.157     albertel 10370:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  10371:                                                  $scan_data,undef,\%idmap,$randomorder,
                   10372:                                                  $randompick,$sequence,\@master_seq,
                   10373:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   10374:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   10375:                                                  \$total);
1.157     albertel 10376:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10377:  					      \%idmap,$i)) {
                   10378:   	    &scantron_add_delay(\@delayqueue,$line,
                   10379:  				'Unable to find a student that matches',1);
                   10380:  	    next;
                   10381:   	}
                   10382:  	if (exists $completedstudents{$uname}) {
                   10383:  	    &scantron_add_delay(\@delayqueue,$line,
                   10384:  				'Student '.$uname.' has multiple sheets',2);
                   10385:  	    next;
                   10386:  	}
1.677     raeburn  10387:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  10388:         if (($checksec ne '') && ($checksec ne $usec)) {
                   10389:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   10390:                 &scantron_add_delay(\@delayqueue,$line,
                   10391:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   10392:                 next;
                   10393:             }
                   10394:         }
1.677     raeburn  10395:         my $user = $uname.':'.$usec;
1.157     albertel 10396:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 10397: 
1.677     raeburn  10398:         my $scancode;
                   10399:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10400:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10401:             $scancode = $scan_record->{'scantron.CODE'};
                   10402:         } else {
                   10403:             $scancode = '';
                   10404:         }
                   10405: 
                   10406:         my @mapresources = @resources;
1.689     raeburn  10407:         if ($randomorder || $randompick) {
1.678     raeburn  10408:             @mapresources = 
1.691     raeburn  10409:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10410:                              \%orderedforcode);
1.677     raeburn  10411:         }
1.586     raeburn  10412:         my (%partids_by_symb,$res_error);
1.677     raeburn  10413:         foreach my $resource (@mapresources) {
1.586     raeburn  10414:             my $ressymb;
                   10415:             if (ref($resource)) {
                   10416:                 $ressymb = $resource->symb();
                   10417:             } else {
                   10418:                 $res_error = 1;
                   10419:                 last;
                   10420:             }
1.557     raeburn  10421:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10422:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10423:                 my $currcode;
                   10424:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10425:                     $currcode = $scancode;
                   10426:                 }
1.557     raeburn  10427:                 my ($analysis,$parts) =
1.672     raeburn  10428:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  10429:                                               $uname,$udom,undef,$bubbles_per_row,
                   10430:                                               $currcode);
1.557     raeburn  10431:                 $partids_by_symb{$ressymb} = $parts;
                   10432:             } else {
                   10433:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   10434:             }
1.554     raeburn  10435:         }
                   10436: 
1.586     raeburn  10437:         if ($res_error) {
                   10438:             &scantron_add_delay(\@delayqueue,$line,
                   10439:                                 'An error occurred while grading student '.$uname,2);
                   10440:             next;
                   10441:         }
                   10442: 
1.330     albertel 10443: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  10444:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 10445: 
                   10446: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   10447: 	    &scantron_putfile($scanlines,$scan_data);
                   10448: 	}
1.161     albertel 10449: 	
1.542     raeburn  10450:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10451:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  10452:                                    $bubbles_per_row,$randomorder,$randompick,
                   10453:                                    \%respnumlookup,\%startline) 
                   10454:             eq 'ssi_error') {
1.542     raeburn  10455:             $ssi_error = 0; # So end of handler error message does not trigger.
                   10456:             $r->print("</form>");
                   10457:             &ssi_print_error($r);
                   10458:             &Apache::lonnet::remove_lock($lock);
                   10459:             return '';      # Why return ''?  Beats me.
                   10460:         }
1.513     foxr     10461: 
1.692     raeburn  10462:         if (($scancode) && ($randomorder || $randompick)) {
1.788     raeburn  10463:             foreach my $key (keys(%symb_for_examcode)) {
                   10464:                 my $symb_in_map = $symb_for_examcode{$key};
                   10465:                 if ($symb_in_map ne '') {
                   10466:                     my $parmresult =
                   10467:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   10468:                                                                '0_examcode',2,$scancode,
                   10469:                                                                'string_examcode',$uname,
                   10470:                                                                $udom);
                   10471:                 }
                   10472:             }
1.692     raeburn  10473:         }
1.140     albertel 10474: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  10475:         if ($env{'form.verifyrecord'}) {
                   10476:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  10477:             if ($randompick) {
                   10478:                 if ($total) {
                   10479:                     $lastpos = $total*$scantron_config{'Qlength'};
                   10480:                 }
                   10481:             }
                   10482: 
1.542     raeburn  10483:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10484:             chomp($studentdata);
                   10485:             $studentdata =~ s/\r$//;
                   10486:             my $studentrecord = '';
                   10487:             my $counter = -1;
1.677     raeburn  10488:             foreach my $resource (@mapresources) {
1.554     raeburn  10489:                 my $ressymb = $resource->symb();
1.542     raeburn  10490:                 ($counter,my $recording) =
                   10491:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10492:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10493:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   10494:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  10495:                 $studentrecord .= $recording;
                   10496:             }
                   10497:             if ($studentrecord ne $studentdata) {
1.554     raeburn  10498:                 &Apache::lonxml::clear_problem_counter();
                   10499:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10500:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  10501:                                            $bubbles_per_row,$randomorder,$randompick,
                   10502:                                            \%respnumlookup,\%startline) 
                   10503:                     eq 'ssi_error') {
1.554     raeburn  10504:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   10505:                     $r->print("</form>");
                   10506:                     &ssi_print_error($r);
                   10507:                     &Apache::lonnet::remove_lock($lock);
                   10508:                     delete($completedstudents{$uname});
                   10509:                     return '';
                   10510:                 }
1.542     raeburn  10511:                 $counter = -1;
                   10512:                 $studentrecord = '';
1.677     raeburn  10513:                 foreach my $resource (@mapresources) {
1.554     raeburn  10514:                     my $ressymb = $resource->symb();
1.542     raeburn  10515:                     ($counter,my $recording) =
                   10516:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10517:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10518:                                                  \%scantron_config,\%lettdig,$numletts,
                   10519:                                                  $randomorder,$randompick,\%respnumlookup,
                   10520:                                                  \%startline);
1.542     raeburn  10521:                     $studentrecord .= $recording;
                   10522:                 }
                   10523:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   10524:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  10525:                     if ($scancode eq '') {
1.658     bisitz   10526:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  10527:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   10528:                     } else {
1.658     bisitz   10529:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  10530:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   10531:                     }
                   10532:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   10533:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   10534:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   10535:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   10536:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10537:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   10538:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  10539:                               &Apache::loncommon::end_data_table_row().
                   10540:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10541:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   10542:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  10543:                               &Apache::loncommon::end_data_table_row().
                   10544:                               &Apache::loncommon::end_data_table().'</p>');
                   10545:                 } else {
                   10546:                     $r->print('<br /><span class="LC_warning">'.
                   10547:                              &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 />'.
                   10548:                              &mt("As a consequence, this user's submission history records two tries.").
                   10549:                                  '</span><br />');
                   10550:                 }
                   10551:             }
                   10552:         }
1.543     raeburn  10553:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 10554:     } continue {
1.330     albertel 10555: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  10556: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 10557:     }
1.140     albertel 10558:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      10559:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 10560: #    my $lasttime = &Time::HiRes::time()-$start;
                   10561: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 10562: 
1.200     albertel 10563:     $r->print("</form>");
1.157     albertel 10564:     return '';
1.75      albertel 10565: }
1.157     albertel 10566: 
1.557     raeburn  10567: sub graders_resources_pass {
1.649     raeburn  10568:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   10569:         $bubbles_per_row) = @_;
1.557     raeburn  10570:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   10571:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   10572:         foreach my $resource (@{$resources}) {
                   10573:             my $ressymb = $resource->symb();
                   10574:             my ($analysis,$parts) =
                   10575:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  10576:                                           $env{'user.name'},$env{'user.domain'},
                   10577:                                           1,$bubbles_per_row);
1.557     raeburn  10578:             $grader_partids_by_symb->{$ressymb} = $parts;
                   10579:             if (ref($analysis) eq 'HASH') {
                   10580:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   10581:                     $grader_randomlists_by_symb->{$ressymb} =
                   10582:                         $analysis->{'parts_withrandomlist'};
                   10583:                 }
                   10584:             }
                   10585:         }
                   10586:     }
                   10587:     return;
                   10588: }
                   10589: 
1.678     raeburn  10590: =pod
                   10591: 
                   10592: =item users_order
                   10593: 
                   10594:   Returns array of resources in current map, ordered based on either CODE,
                   10595:   if this is a CODEd exam, or based on student's identity if this is a 
                   10596:   "NAMEd" exam.
                   10597: 
1.691     raeburn  10598:   Should be used when randomorder and/or randompick applied when the 
                   10599:   corresponding exam was printed, prior to students completing bubblesheets 
                   10600:   for the version of the exam the student received.
1.678     raeburn  10601: 
                   10602: =cut
                   10603: 
                   10604: sub users_order  {
1.691     raeburn  10605:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  10606:     my @mapresources;
1.691     raeburn  10607:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  10608:         return @mapresources;
1.691     raeburn  10609:     }
                   10610:     if ($scancode) {
                   10611:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   10612:             @mapresources = @{$orderedforcode->{$scancode}};
                   10613:         } else {
                   10614:             $env{'form.CODE'} = $scancode;
                   10615:             my $actual_seq =
                   10616:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10617:                                                                $master_seq,
                   10618:                                                                $user,$scancode,1);
                   10619:             if (ref($actual_seq) eq 'ARRAY') {
                   10620:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10621:                 if (ref($orderedforcode) eq 'HASH') {
                   10622:                     if (@mapresources > 0) { 
                   10623:                         $orderedforcode->{$scancode} = \@mapresources;
                   10624:                     }
                   10625:                 }
                   10626:             }
                   10627:             delete($env{'form.CODE'});
1.678     raeburn  10628:         }
                   10629:     } else {
                   10630:         my $actual_seq =
                   10631:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10632:                                                            $master_seq,
1.688     raeburn  10633:                                                            $user,undef,1);
1.678     raeburn  10634:         if (ref($actual_seq) eq 'ARRAY') {
                   10635:             @mapresources = 
                   10636:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10637:         }
1.691     raeburn  10638:     }
                   10639:     return @mapresources;
1.678     raeburn  10640: }
                   10641: 
1.542     raeburn  10642: sub grade_student_bubbles {
1.691     raeburn  10643:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   10644:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   10645:     my $uselookup = 0;
                   10646:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   10647:         (ref($startline) eq 'HASH')) {
                   10648:         $uselookup = 1;
                   10649:     }
                   10650: 
1.554     raeburn  10651:     if (ref($resources) eq 'ARRAY') {
                   10652:         my $count = 0;
                   10653:         foreach my $resource (@{$resources}) {
                   10654:             my $ressymb = $resource->symb();
                   10655:             my %form = ('submitted'      => 'scantron',
                   10656:                         'grade_target'   => 'grade',
                   10657:                         'grade_username' => $uname,
                   10658:                         'grade_domain'   => $udom,
                   10659:                         'grade_courseid' => $env{'request.course.id'},
                   10660:                         'grade_symb'     => $ressymb,
                   10661:                         'CODE'           => $scancode
                   10662:                        );
1.649     raeburn  10663:             if ($bubbles_per_row ne '') {
                   10664:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   10665:             }
1.663     raeburn  10666:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   10667:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   10668:             }
1.554     raeburn  10669:             if (ref($parts) eq 'HASH') {
                   10670:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   10671:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  10672:                         if ($uselookup) {
                   10673:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   10674:                         } else {
                   10675:                             $form{'scantron_questnum_start.'.$part} =
                   10676:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   10677:                         }
1.554     raeburn  10678:                         $count++;
                   10679:                     }
                   10680:                 }
                   10681:             }
                   10682:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   10683:             return 'ssi_error' if ($ssi_error);
                   10684:             last if (&Apache::loncommon::connection_aborted($r));
                   10685:         }
1.542     raeburn  10686:     }
                   10687:     return;
                   10688: }
                   10689: 
1.157     albertel 10690: sub scantron_upload_scantron_data {
1.767     raeburn  10691:     my ($r,$symb) = @_;
1.565     raeburn  10692:     my $dom = $env{'request.role.domain'};
1.754     raeburn  10693:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  10694:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   10695:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 10696:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 10697: 							  'domainid',
1.565     raeburn  10698: 							  'coursename',$dom);
                   10699:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   10700:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      10701:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  10702:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  10703:     &js_escape(\$nofile_alert);
1.579     raeburn  10704:     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  10705:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 10706:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 10707:     function checkUpload(formname) {
                   10708: 	if (formname.upfile.value == "") {
1.579     raeburn  10709: 	    alert("'.$nofile_alert.'");
1.157     albertel 10710: 	    return false;
                   10711: 	}
1.565     raeburn  10712:         if (formname.courseid.value == "") {
1.579     raeburn  10713:             alert("'.$nocourseid_alert.'");
1.565     raeburn  10714:             return false;
                   10715:         }
1.157     albertel 10716: 	formname.submit();
                   10717:     }
1.565     raeburn  10718: 
                   10719:     function ToSyllabus() {
                   10720:         var cdom = '."'$dom'".';
                   10721:         var cnum = document.rules.courseid.value;
                   10722:         if (cdom == "" || cdom == null) {
                   10723:             return;
                   10724:         }
                   10725:         if (cnum == "" || cnum == null) {
                   10726:            return;
                   10727:         }
                   10728:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   10729:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   10730:         return;
                   10731:     }
                   10732: 
1.754     raeburn  10733:     '.$formatjs.'
1.597     wenzelju 10734: '));
                   10735:     $r->print('
1.648     bisitz   10736: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  10737: 
1.492     albertel 10738: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  10739: '.$default_form_data.
                   10740:   &Apache::lonhtmlcommon::start_pick_box().
                   10741:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   10742:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   10743:   &Apache::lonhtmlcommon::row_closure().
                   10744:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   10745:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   10746:   &Apache::lonhtmlcommon::row_closure().
                   10747:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   10748:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  10749:   &Apache::lonhtmlcommon::row_closure());
                   10750:     if ($formatoptions) {
                   10751:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   10752:                   &Apache::lonhtmlcommon::row_closure());
                   10753:     }
                   10754:     $r->print(
1.565     raeburn  10755:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   10756:   '<input type="file" name="upfile" size="50" />'.
                   10757:   &Apache::lonhtmlcommon::row_closure(1).
                   10758:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   10759: 
1.492     albertel 10760: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   10761: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 10762: </form>
1.492     albertel 10763: ');
1.157     albertel 10764:     return '';
                   10765: }
                   10766: 
1.754     raeburn  10767: sub scantron_upload_dataformat {
                   10768:     my ($dom) = @_;
                   10769:     my ($formatoptions,$formattitle,$formatjs);
                   10770:     $formatjs = <<'END';
                   10771: function toggleScantab(form) {
                   10772:    return;
                   10773: }
                   10774: END
                   10775:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   10776:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10777:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10778:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   10779:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   10780:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  10781:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   10782:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   10783:                             my ($onclick,$formatextra,$singleline);
                   10784:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   10785:                             my $count = 0;
                   10786:                             foreach my $line (@lines) {
1.790     raeburn  10787:                                 next if (($line =~ /^\#/) || ($line eq ''));
1.756     raeburn  10788:                                 $singleline = $line;
                   10789:                                 $count ++;
                   10790:                             }
                   10791:                             if ($count > 1) {
                   10792:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  10793:                                                '<span class="LC_nobreak">'.
1.776     raeburn  10794:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  10795:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  10796:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   10797:                                 $formatjs = <<"END";
1.754     raeburn  10798: function toggleScantab(form) {
                   10799:     var divid = 'bubbletype';
                   10800:     if (document.getElementById(divid)) {
                   10801:         var radioname = 'fileformat';
                   10802:         var num = form.elements[radioname].length;
                   10803:         if (num) {
                   10804:             for (var i=0; i<num; i++) {
                   10805:                 if (form.elements[radioname][i].checked) {
                   10806:                     var chosen = form.elements[radioname][i].value;
                   10807:                     if (chosen == 'dat') {
                   10808:                         document.getElementById(divid).style.display = 'none';
                   10809:                     } else if (chosen == 'csv') {
1.757     raeburn  10810:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  10811:                     }
                   10812:                 }
                   10813:             }
                   10814:         }
                   10815:     }
                   10816:     return;
                   10817: }
                   10818: 
                   10819: END
1.756     raeburn  10820:                             } elsif ($count == 1) {
                   10821:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   10822:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   10823:                             }
                   10824:                             $formattitle = &mt('File format');
                   10825:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   10826:                                              &mt('Plain Text (no delimiters)').
                   10827:                                              '</label>'.('&nbsp;'x2).
                   10828:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   10829:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  10830:                         }
                   10831:                     }
                   10832:                 }
                   10833:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  10834:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10835:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  10836:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  10837:                         $formatoptions = &scantron_scantab();
                   10838:                     }
1.754     raeburn  10839:                 }
                   10840:             }
                   10841:         }
                   10842:     }
                   10843:     return ($formatoptions,$formattitle,$formatjs);
                   10844: }
1.423     albertel 10845: 
1.157     albertel 10846: sub scantron_upload_scantron_data_save {
1.767     raeburn  10847:     my ($r,$symb) = @_;
1.182     albertel 10848:     my $doanotherupload=
                   10849: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   10850: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 10851: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 10852: 	'</form>'."\n";
1.257     albertel 10853:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 10854: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  10855: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   10856:         !&Apache::lonnet::allowed('usc',
                   10857:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      10858: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      10859: 	unless ($symb) {
1.182     albertel 10860: 	    $r->print($doanotherupload);
                   10861: 	}
1.162     albertel 10862: 	return '';
                   10863:     }
1.257     albertel 10864:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  10865:     my $uploadedfile;
1.710     bisitz   10866:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 10867:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10868:         $r->print(
                   10869:             &Apache::lonhtmlcommon::confirm_success(
                   10870:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10871:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 10872:     } else {
1.754     raeburn  10873:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   10874:         my $parser;
                   10875:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10876:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10877:                 my $is_csv;
                   10878:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   10879:                 if (@possibles > 1) {
                   10880:                     if ($env{'form.fileformat'} eq 'csv') {
                   10881:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10882:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10883:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10884:                                     $is_csv = 1;
                   10885:                                 }
1.754     raeburn  10886:                             }
                   10887:                         }
                   10888:                     }
                   10889:                 } elsif (@possibles == 1) {
                   10890:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10891:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10892:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10893:                                 $is_csv = 1;
                   10894:                             }
1.754     raeburn  10895:                         }
                   10896:                     }
                   10897:                 }
                   10898:                 if ($is_csv) {
                   10899:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   10900:                 }
                   10901:             }
                   10902:         }
                   10903:         my $result =
                   10904:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  10905:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   10906:         if ($result =~ m{^/uploaded/}) {
                   10907:             $r->print(
                   10908:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   10909:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   10910:                         (length($env{'form.upfile'})-1),
                   10911:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  10912:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  10913:             if ($uploadedfile =~ /^scantron_orig_/) {
                   10914:                 my $logname = $uploadedfile;
                   10915:                 $logname =~ s/^scantron_orig_//;
                   10916:                 if ($logname ne '') {
                   10917:                     my $now = time;
                   10918:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   10919:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   10920:                 }
                   10921:             }
1.567     raeburn  10922:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  10923:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   10924:         } else {
                   10925:             $r->print(
                   10926:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   10927:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   10928:                           $result,
1.568     raeburn  10929: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 10930: 	}
                   10931:     }
1.174     albertel 10932:     if ($symb) {
1.612     www      10933: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 10934:     } else {
1.182     albertel 10935: 	$r->print($doanotherupload);
1.174     albertel 10936:     }
1.157     albertel 10937:     return '';
                   10938: }
                   10939: 
1.567     raeburn  10940: sub validate_uploaded_scantron_file {
1.770     raeburn  10941:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   10942: 
1.567     raeburn  10943:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   10944:     my @lines;
                   10945:     if ($scanlines ne '-1') {
                   10946:         @lines=split("\n",$scanlines,-1);
                   10947:     }
1.770     raeburn  10948:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   10949:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   10950:     if ($context eq 'download') {
                   10951:         $priv = 'mgr';
                   10952:     } else {
                   10953:         $priv = 'usc';
                   10954:     }
                   10955:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   10956:             (($env{'request.course.id'}) &&
                   10957:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   10958:         if ($env{'request.course.sec'} ne '') {
                   10959:             unless (&Apache::lonnet::allowed($priv,
                   10960:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   10961:                 unless ($context eq 'download') {
                   10962:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   10963:                 }
                   10964:                 return $output;
                   10965:             }
                   10966:             ($checksec,@possibles)=&gradable_sections();
                   10967:         }
                   10968:     }
1.567     raeburn  10969:     if (@lines) {
                   10970:         my (%counts,$max_match_format);
1.710     bisitz   10971:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  10972:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   10973:         my %idmap = &username_to_idmap($classlist);
                   10974:         foreach my $key (keys(%idmap)) {
                   10975:             my $lckey = lc($key);
                   10976:             $idmap{$lckey} = $idmap{$key};
                   10977:         }
                   10978:         my %unique_formats;
1.754     raeburn  10979:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  10980:         foreach my $line (@formatlines) {
1.790     raeburn  10981:             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  10982:             my @config = split(/:/,$line);
                   10983:             my $idstart = $config[5];
                   10984:             my $idlength = $config[6];
                   10985:             if (($idstart ne '') && ($idlength > 0)) {
                   10986:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   10987:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   10988:                 } else {
                   10989:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   10990:                 }
                   10991:             }
                   10992:         }
                   10993:         foreach my $key (keys(%unique_formats)) {
                   10994:             my ($idstart,$idlength) = split(':',$key);
                   10995:             %{$counts{$key}} = (
                   10996:                                'found'   => 0,
                   10997:                                'total'   => 0,
1.770     raeburn  10998:                                'totalanysec' => 0,
                   10999:                                'othersec' => 0,
1.567     raeburn  11000:                               );
                   11001:             foreach my $line (@lines) {
                   11002:                 next if ($line =~ /^#/);
                   11003:                 next if ($line =~ /^[\s\cz]*$/);
                   11004:                 my $id = substr($line,$idstart-1,$idlength);
                   11005:                 $id = lc($id);
                   11006:                 if (exists($idmap{$id})) {
1.770     raeburn  11007:                     if ($checksec ne '') {
                   11008:                         $counts{$key}{'totalanysec'} ++;
                   11009:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   11010:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   11011:                             if ($stusec ne $checksec) {
                   11012:                                 if (@possibles) {
                   11013:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   11014:                                         $counts{$key}{'othersec'} ++;
                   11015:                                         next;
                   11016:                                     }
                   11017:                                 } else {
                   11018:                                     $counts{$key}{'othersec'} ++;
                   11019:                                     next;
                   11020:                                 }
                   11021:                             }
                   11022:                         }
                   11023:                     }
1.567     raeburn  11024:                     $counts{$key}{'found'} ++;
                   11025:                 }
                   11026:                 $counts{$key}{'total'} ++;
                   11027:             }
                   11028:             if ($counts{$key}{'total'}) {
                   11029:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   11030:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   11031:                     $max_match_pct = $percent_match;
                   11032:                     $max_match_format = $key;
1.710     bisitz   11033:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  11034:                     $max_match_count = $counts{$key}{'total'};
                   11035:                 }
                   11036:             }
                   11037:         }
1.770     raeburn  11038:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  11039:             my $format_descs;
                   11040:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   11041:             for (my $i=0; $i<$numwithformat; $i++) {
                   11042:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   11043:                 if ($i<$numwithformat-2) {
                   11044:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   11045:                 } elsif ($i==$numwithformat-2) {
                   11046:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   11047:                 } elsif ($i==$numwithformat-1) {
                   11048:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   11049:                 }
                   11050:             }
                   11051:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   11052:             $output .= '<br />';
                   11053:             if ($found_match_count == $max_match_count) {
                   11054:                 # 100% matching entries
                   11055:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   11056:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   11057:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   11058:                 &mt('Comparison of student IDs in the uploaded file with'.
                   11059:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   11060:                     ' in the file (for the format defined for [_3]).',
                   11061:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   11062:             } else {
                   11063:                 # Not all entries matching? -> Show warning and additional info
                   11064:                 $output .=
                   11065:                     &Apache::lonhtmlcommon::confirm_success(
                   11066:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   11067:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   11068:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   11069:                     &mt('Comparison of student IDs in the uploaded file with'.
                   11070:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   11071:                         ' in the file (for the format defined for [_3]).',
                   11072:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   11073:                     '<p class="LC_info">'.
                   11074:                     &mt('A low percentage of matches results from one of the following:').
                   11075:                     '</p><ul>'.
                   11076:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   11077:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   11078:                                '<i>'.$cdom.'</i>').'</li>'.
                   11079:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   11080:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   11081:                     '</ul>';
                   11082:             }
1.770     raeburn  11083:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11084:                 if ($counts{$max_match_format}{'othersec'}) {
                   11085:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   11086:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   11087:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   11088:                     &js_escape(\$confirmdel);
                   11089:                     $output .= '<p class="LC_warning">'.
                   11090:                                &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',
                   11091:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   11092:                                '<br />'.
                   11093:                                &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>').
                   11094:                                '</p><p>'.
                   11095:                                &mt('If you prefer to delete the file now, use: [_1]').
                   11096:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   11097:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   11098:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   11099:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   11100:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   11101:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   11102:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   11103:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   11104:                                '</form></p>';
                   11105:                 }
                   11106:             }
1.567     raeburn  11107:         }
1.770     raeburn  11108:         if (($context eq 'download') && ($checksec ne '')) {
                   11109:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   11110:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   11111:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   11112:             }
                   11113:         } 
                   11114:     } elsif ($context ne 'download') {
1.710     bisitz   11115:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  11116:     }
                   11117:     return $output;
                   11118: }
                   11119: 
1.770     raeburn  11120: sub gradable_sections {
                   11121:     my $checksec = $env{'request.course.sec'};
                   11122:     my @oksecs;
                   11123:     if ($checksec) {
                   11124:         my %availablesecs = &sections_grade_privs();
                   11125:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   11126:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   11127:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   11128:                     push(@oksecs,$sec);
                   11129:                 }
                   11130:             }
                   11131:             if (grep(/^all$/,@oksecs)) {
                   11132:                 undef($checksec);
                   11133:             }
                   11134:         }
                   11135:     }
                   11136:     return($checksec,@oksecs);
                   11137: }
                   11138: 
                   11139: sub sections_grade_privs {
                   11140:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11141:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11142:     my %availablesecs = (
                   11143:                           mgr => [],
                   11144:                           vgr => [],
                   11145:                           usc => [],
                   11146:                         );
                   11147:     my $ccrole = 'cc';
                   11148:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   11149:         $ccrole = 'co';
                   11150:     }
                   11151:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   11152:                                                      'userroles',['active'],
                   11153:                                                      [$ccrole,'in','cr'],$cdom,1);
                   11154:     my $crsid = $cnum.':'.$cdom;
                   11155:     foreach my $item (keys(%crsroleshash)) {
                   11156:         next unless ($item =~ /^$crsid\:/);
                   11157:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   11158:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   11159:         if ($sec ne '') {
                   11160:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   11161:         }
                   11162:         if (($role eq $ccrole) || ($role eq 'in')) {
                   11163:             foreach my $priv ('mgr','vgr','usc') { 
                   11164:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11165:                     if ($sec eq '') {
                   11166:                         $availablesecs{$priv} = ['all'];
                   11167:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   11168:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11169:                             push(@{$availablesecs{$priv}},$sec);
                   11170:                         }
                   11171:                     }
                   11172:                 }
                   11173:             }
                   11174:         } elsif ($role =~ m{^cr/}) {
                   11175:             foreach my $priv ('mgr','vgr','usc') {
                   11176:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   11177:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   11178:                         if ($sec eq '') {
                   11179:                             $availablesecs{$priv} = ['all'];
                   11180:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   11181:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   11182:                                 push(@{$availablesecs{$priv}},$sec);
                   11183:                             }
                   11184:                         }
                   11185:                     }
                   11186:                 }
                   11187:             }
                   11188:         }
                   11189:     }
                   11190:     return %availablesecs;
                   11191: }
                   11192: 
                   11193: sub scantron_upload_delete {
                   11194:     my ($r,$symb) = @_;
                   11195:     my $filename = $env{'form.uploadedfile'};
                   11196:     if ($filename =~ /^scantron_orig_/) {
                   11197:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   11198:             &Apache::lonnet::allowed('usc',
                   11199:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   11200:             &Apache::lonnet::allowed('usc',
                   11201:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   11202:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   11203:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   11204:             if ($retrieval eq '-1') {
                   11205:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11206:                           &mt('File requested for deletion not found.'));
                   11207:             } else {
                   11208:                 $filename =~ s/^scantron_orig_//;
                   11209:                 if ($filename ne '') {
                   11210:                     my ($is_valid,$numleft);
                   11211:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11212:                     if (keys(%info)) {
                   11213:                         if (ref($info{$filename}) eq 'HASH') {
                   11214:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   11215:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11216:                                     $is_valid = 1;
                   11217:                                     delete($info{$filename}{$timestamp}); 
                   11218:                                 }
                   11219:                             }
                   11220:                             $numleft = scalar(keys(%{$info{$filename}}));
                   11221:                         }
                   11222:                     }
                   11223:                     if ($is_valid) {
                   11224:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   11225:                         if ($result eq 'ok') {
                   11226:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   11227:                             if ($numleft) {
                   11228:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   11229:                             } else {
                   11230:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   11231:                             }
                   11232:                         } else {
                   11233:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11234:                                       &mt('Result was [_1]',$result));
                   11235:                         }
                   11236:                     } else {
                   11237:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11238:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   11239:                     }
                   11240:                 } else {
                   11241:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11242:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11243:                 }
                   11244:             }
                   11245:         } else {
                   11246:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   11247:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   11248:         }
                   11249:     } else {
                   11250:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   11251:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   11252:     }
                   11253:     return;
                   11254: }
                   11255: 
1.202     albertel 11256: sub valid_file {
                   11257:     my ($requested_file)=@_;
                   11258:     foreach my $filename (sort(&scantron_filenames())) {
                   11259: 	if ($requested_file eq $filename) { return 1; }
                   11260:     }
                   11261:     return 0;
                   11262: }
                   11263: 
                   11264: sub scantron_download_scantron_data {
1.767     raeburn  11265:     my ($r,$symb) = @_;
1.608     www      11266:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 11267:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   11268:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   11269:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 11270:     if (! &valid_file($file)) {
1.492     albertel 11271: 	$r->print('
1.202     albertel 11272: 	<p>
1.686     bisitz   11273: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 11274:         </p>
1.492     albertel 11275: ');
1.202     albertel 11276: 	return;
                   11277:     }
1.770     raeburn  11278:     my (%uploader,$is_owner,%counts,$percent);
                   11279:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   11280:     if (ref($uploader{$file}) eq 'HASH') {
                   11281:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   11282:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   11283:                 $is_owner = 1;
                   11284:                 last;
                   11285:             }
                   11286:         }
                   11287:     }
                   11288:     unless ($is_owner) {
                   11289:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   11290:         if ($counts{'totalanysec'}) {
                   11291:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   11292:             if ($percent_othersec >= 10) {
                   11293:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   11294:                 $r->print('<p class="LC_warning">'.
                   11295:                           &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).
                   11296:                           '</p>');
                   11297:                 return;
                   11298:             }
                   11299:         }
                   11300:     }
1.202     albertel 11301:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   11302:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   11303:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   11304:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   11305:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   11306:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 11307:     $r->print('
1.202     albertel 11308:     <p>
1.723     raeburn  11309: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 11310: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 11311:     </p>
                   11312:     <p>
1.492     albertel 11313: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   11314: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 11315:     </p>
                   11316:     <p>
1.492     albertel 11317: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   11318: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 11319:     </p>
1.492     albertel 11320: ');
1.202     albertel 11321:     return '';
                   11322: }
1.157     albertel 11323: 
1.523     raeburn  11324: sub checkscantron_results {
1.608     www      11325:     my ($r,$symb) = @_;
1.523     raeburn  11326:     if (!$symb) {return '';}
                   11327:     my $cid = $env{'request.course.id'};
1.755     raeburn  11328:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  11329:     my $numletts = scalar(keys(%lettdig));
                   11330:     my $cnum = $env{'course.'.$cid.'.num'};
                   11331:     my $cdom = $env{'course.'.$cid.'.domain'};
                   11332:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   11333:     my %record;
                   11334:     my %scantron_config =
1.754     raeburn  11335:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  11336:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  11337:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  11338:     my $classlist=&Apache::loncoursedata::get_classlist();
                   11339:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   11340:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  11341:     unless (ref($navmap)) {
                   11342:         $r->print(&navmap_errormsg());
                   11343:         return '';
                   11344:     }
1.523     raeburn  11345:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  11346:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   11347:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  11348:     if (ref($map)) { 
                   11349:         $randomorder=$map->randomorder();
1.689     raeburn  11350:         $randompick=$map->randompick();
1.788     raeburn  11351:         unless ($randomorder || $randompick) {
                   11352:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   11353:                 if ($res->randomorder()) {
                   11354:                     $randomorder = 1;
                   11355:                 }
                   11356:                 if ($res->randompick()) {
                   11357:                     $randompick = 1;
                   11358:                 }
                   11359:                 last if ($randomorder || $randompick);
                   11360:             }
                   11361:         }
1.677     raeburn  11362:     }
1.557     raeburn  11363:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  11364:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   11365:     if ($nav_error) {
                   11366:         $r->print(&navmap_errormsg());
                   11367:         return '';
1.678     raeburn  11368:     }
1.673     raeburn  11369:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   11370:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  11371:     my ($uname,$udom);
1.523     raeburn  11372:     my (%scandata,%lastname,%bylast);
                   11373:     $r->print('
                   11374: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   11375: 
                   11376:     my @delayqueue;
                   11377:     my %completedstudents;
                   11378: 
1.691     raeburn  11379:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      11380:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  11381:     my ($username,$domain,$started);
1.649     raeburn  11382:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  11383:     if ($nav_error) {
                   11384:         $r->print(&navmap_errormsg());
                   11385:         return '';
                   11386:     }
1.523     raeburn  11387: 
1.667     www      11388:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  11389:     my $start=&Time::HiRes::time();
                   11390:     my $i=-1;
                   11391: 
                   11392:     while ($i<$scanlines->{'count'}) {
                   11393:         ($username,$domain,$uname)=('','','');
                   11394:         $i++;
                   11395:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   11396:         if ($line=~/^[\s\cz]*$/) { next; }
                   11397:         if ($started) {
1.667     www      11398:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  11399:         }
                   11400:         $started=1;
                   11401:         my $scan_record=
                   11402:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   11403:                                                      $scan_data);
1.693     raeburn  11404:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   11405:                                               \%idmap,$i)) {
1.523     raeburn  11406:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11407:                                 'Unable to find a student that matches',1);
                   11408:             next;
                   11409:         }
                   11410:         if (exists $completedstudents{$uname}) {
                   11411:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   11412:                                 'Student '.$uname.' has multiple sheets',2);
                   11413:             next;
                   11414:         }
                   11415:         my $pid = $scan_record->{'scantron.ID'};
                   11416:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   11417:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  11418:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   11419:         my $user = $uname.':'.$usec;
1.523     raeburn  11420:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  11421: 
1.678     raeburn  11422:         my $scancode;
1.677     raeburn  11423:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   11424:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   11425:             $scancode = $scan_record->{'scantron.CODE'};
                   11426:         } else {
                   11427:             $scancode = '';
                   11428:         }
                   11429: 
                   11430:         my @mapresources = @resources;
1.691     raeburn  11431:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   11432:         my %respnumlookup=();
                   11433:         my %startline=();
1.689     raeburn  11434:         if ($randomorder || $randompick) {
1.678     raeburn  11435:             @mapresources =
1.691     raeburn  11436:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   11437:                              \%orderedforcode);
                   11438:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   11439:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   11440:                                              \%grader_partids_by_symb,\%orderedforcode,
                   11441:                                              \%respnumlookup,\%startline);
                   11442:             if ($randompick && $total) {
                   11443:                 $lastpos = $total*$scantron_config{'Qlength'};
                   11444:             }
1.677     raeburn  11445:         }
1.691     raeburn  11446:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   11447:         chomp($scandata{$pid});
                   11448:         $scandata{$pid} =~ s/\r$//;
                   11449: 
1.523     raeburn  11450:         my $counter = -1;
1.677     raeburn  11451:         foreach my $resource (@mapresources) {
1.557     raeburn  11452:             my $parts;
1.554     raeburn  11453:             my $ressymb = $resource->symb();
1.557     raeburn  11454:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   11455:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  11456:                 my $currcode;
                   11457:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   11458:                     $currcode = $scancode;
                   11459:                 }
1.557     raeburn  11460:                 (my $analysis,$parts) =
1.672     raeburn  11461:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   11462:                                               $username,$domain,undef,
1.741     raeburn  11463:                                               $bubbles_per_row,$currcode);
1.557     raeburn  11464:             } else {
                   11465:                 $parts = $grader_partids_by_symb{$ressymb};
                   11466:             }
1.542     raeburn  11467:             ($counter,my $recording) =
                   11468:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  11469:                                          $scandata{$pid},$parts,
1.691     raeburn  11470:                                          \%scantron_config,\%lettdig,$numletts,
                   11471:                                          $randomorder,$randompick,
                   11472:                                          \%respnumlookup,\%startline);
1.542     raeburn  11473:             $record{$pid} .= $recording;
1.523     raeburn  11474:         }
                   11475:     }
                   11476:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   11477:     $r->print('<br />');
                   11478:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   11479:     $passed = 0;
                   11480:     $failed = 0;
                   11481:     $numstudents = 0;
                   11482:     foreach my $last (sort(keys(%bylast))) {
                   11483:         if (ref($bylast{$last}) eq 'ARRAY') {
                   11484:             foreach my $pid (sort(@{$bylast{$last}})) {
                   11485:                 my $showscandata = $scandata{$pid};
                   11486:                 my $showrecord = $record{$pid};
                   11487:                 $showscandata =~ s/\s/&nbsp;/g;
                   11488:                 $showrecord =~ s/\s/&nbsp;/g;
                   11489:                 if ($scandata{$pid} eq $record{$pid}) {
                   11490:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   11491:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      11492: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  11493: '</tr>'."\n".
                   11494: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11495: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  11496:                     $passed ++;
                   11497:                 } else {
                   11498:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      11499:                     $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  11500: '</tr>'."\n".
                   11501: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11502: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  11503: '</tr>'."\n";
                   11504:                     $failed ++;
                   11505:                 }
                   11506:                 $numstudents ++;
                   11507:             }
                   11508:         }
                   11509:     }
1.648     bisitz   11510:     $r->print(
                   11511:         '<p>'
                   11512:        .&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).',
                   11513:             '<b>',
                   11514:             $numstudents,
                   11515:             '</b>',
                   11516:             $env{'form.scantron_maxbubble'})
                   11517:        .'</p>'
                   11518:     );
1.682     raeburn  11519:     $r->print('<p>'
1.683     raeburn  11520:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  11521:              .'<br />'
                   11522:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   11523:              .'</p>'
                   11524:     );
1.523     raeburn  11525:     if ($passed) {
1.572     www      11526:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11527:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11528:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11529:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11530:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11531:                  $okstudents."\n".
                   11532:                  &Apache::loncommon::end_data_table().'<br />');
                   11533:     }
                   11534:     if ($failed) {
1.572     www      11535:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11536:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11537:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11538:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11539:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11540:                  $badstudents."\n".
                   11541:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      11542:                  &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  11543:     }
1.614     www      11544:     $r->print('</form><br />');
1.523     raeburn  11545:     return;
                   11546: }
                   11547: 
1.542     raeburn  11548: sub verify_scantron_grading {
1.554     raeburn  11549:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  11550:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   11551:         $respnumlookup,$startline) = @_;
1.542     raeburn  11552:     my ($record,%expected,%startpos);
                   11553:     return ($counter,$record) if (!ref($resource));
                   11554:     return ($counter,$record) if (!$resource->is_problem());
                   11555:     my $symb = $resource->symb();
1.554     raeburn  11556:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   11557:     foreach my $part_id (@{$partids}) {
1.542     raeburn  11558:         $counter ++;
                   11559:         $expected{$part_id} = 0;
1.691     raeburn  11560:         my $respnum = $counter;
                   11561:         if ($randomorder || $randompick) {
                   11562:             $respnum = $respnumlookup->{$counter};
                   11563:             $startpos{$part_id} = $startline->{$counter} + 1;
                   11564:         } else {
                   11565:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   11566:         }
                   11567:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   11568:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  11569:             foreach my $item (@sub_lines) {
                   11570:                 $expected{$part_id} += $item;
                   11571:             }
                   11572:         } else {
1.691     raeburn  11573:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  11574:         }
                   11575:     }
                   11576:     if ($symb) {
                   11577:         my %recorded;
                   11578:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   11579:         if ($returnhash{'version'}) {
                   11580:             my %lasthash=();
                   11581:             my $version;
                   11582:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   11583:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   11584:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   11585:                 }
                   11586:             }
                   11587:             foreach my $key (keys(%lasthash)) {
                   11588:                 if ($key =~ /\.scantron$/) {
                   11589:                     my $value = &unescape($lasthash{$key});
                   11590:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   11591:                     if ($value eq '') {
                   11592:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11593:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   11594:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11595:                             }
                   11596:                         }
                   11597:                     } else {
                   11598:                         my @tocheck;
                   11599:                         my @items = split(//,$value);
                   11600:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   11601:                             ($scantron_config->{'Qon'} eq 'number')) {
                   11602:                             if (@items < $expected{$part_id}) {
                   11603:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   11604:                                 my @singles = split(//,$fragment);
                   11605:                                 foreach my $pos (@singles) {
                   11606:                                     if ($pos eq ' ') {
                   11607:                                         push(@tocheck,$pos);
                   11608:                                     } else {
                   11609:                                         my $next = shift(@items);
                   11610:                                         push(@tocheck,$next);
                   11611:                                     }
                   11612:                                 }
                   11613:                             } else {
                   11614:                                 @tocheck = @items;
                   11615:                             }
                   11616:                             foreach my $letter (@tocheck) {
                   11617:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   11618:                                     if ($letter !~ /^[A-J]$/) {
                   11619:                                         $letter = $scantron_config->{'Qoff'};
                   11620:                                     }
                   11621:                                     $recorded{$part_id} .= $letter;
                   11622:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   11623:                                     my $digit;
                   11624:                                     if ($letter !~ /^[A-J]$/) {
                   11625:                                         $digit = $scantron_config->{'Qoff'};
                   11626:                                     } else {
                   11627:                                         $digit = $lettdig->{$letter};
                   11628:                                     }
                   11629:                                     $recorded{$part_id} .= $digit;
                   11630:                                 }
                   11631:                             }
                   11632:                         } else {
                   11633:                             @tocheck = @items;
                   11634:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11635:                                 my $curr_sub = shift(@tocheck);
                   11636:                                 my $digit;
                   11637:                                 if ($curr_sub =~ /^[A-J]$/) {
                   11638:                                     $digit = $lettdig->{$curr_sub}-1;
                   11639:                                 }
                   11640:                                 if ($curr_sub eq 'J') {
                   11641:                                     $digit += scalar($numletts);
                   11642:                                 }
                   11643:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11644:                                     if ($j == $digit) {
                   11645:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   11646:                                     } else {
                   11647:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11648:                                     }
                   11649:                                 }
                   11650:                             }
                   11651:                         }
                   11652:                     }
                   11653:                 }
                   11654:             }
                   11655:         }
1.554     raeburn  11656:         foreach my $part_id (@{$partids}) {
1.542     raeburn  11657:             if ($recorded{$part_id} eq '') {
                   11658:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11659:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11660:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11661:                     }
                   11662:                 }
                   11663:             }
                   11664:             $record .= $recorded{$part_id};
                   11665:         }
                   11666:     }
                   11667:     return ($counter,$record);
                   11668: }
                   11669: 
1.75      albertel 11670: #-------- end of section for handling grading scantron forms -------
                   11671: #
                   11672: #-------------------------------------------------------------------
                   11673: 
1.72      ng       11674: #-------------------------- Menu interface -------------------------
                   11675: #
1.614     www      11676: #--- Href with symb and command ---
                   11677: 
                   11678: sub href_symb_cmd {
                   11679:     my ($symb,$cmd)=@_;
1.796     raeburn  11680:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.
                   11681:            &HTML::Entities::encode($cmd,'<>&"');
1.72      ng       11682: }
                   11683: 
1.443     banghart 11684: sub grading_menu {
1.608     www      11685:     my ($request,$symb) = @_;
1.443     banghart 11686:     if (!$symb) {return '';}
                   11687: 
                   11688:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      11689:                   'command'=>'individual');
1.538     schulted 11690:     
1.598     www      11691:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11692: 
                   11693:     $fields{'command'}='ungraded';
                   11694:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11695: 
                   11696:     $fields{'command'}='table';
                   11697:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11698: 
                   11699:     $fields{'command'}='all_for_one';
                   11700:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11701: 
1.621     www      11702:     $fields{'command'}='downloadfilesselect';
                   11703:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11704: 
1.443     banghart 11705:     $fields{'command'} = 'csvform';
1.538     schulted 11706:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11707:     
1.443     banghart 11708:     $fields{'command'} = 'processclicker';
1.538     schulted 11709:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11710:     
1.443     banghart 11711:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 11712:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      11713: 
                   11714:     $fields{'command'} = 'initialverifyreceipt';
                   11715:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  11716: 
                   11717:     my %permissions;
                   11718:     if ($perm{'mgr'}) {
                   11719:         $permissions{'either'} = 'F';
                   11720:         $permissions{'mgr'} = 'F';
                   11721:     }
                   11722:     if ($perm{'vgr'}) {
                   11723:         $permissions{'either'} = 'F';
                   11724:         $permissions{'vgr'} = 'F';
                   11725:     }
                   11726: 
1.598     www      11727:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 11728:             items =>[
1.598     www      11729:                         {	linktext => 'Select individual students to grade',
                   11730:                     		url => $url1a,
1.781     raeburn  11731:                     		permission => $permissions{'either'},
1.636     wenzelju 11732:                     		icon => 'grade_students.png',
1.598     www      11733:                     		linktitle => 'Grade current resource for a selection of students.'
                   11734:                         }, 
1.764     raeburn  11735:                         {       linktext => 'Grade ungraded submissions',
1.598     www      11736:                                 url => $url1b,
1.781     raeburn  11737:                                 permission => $permissions{'either'},
1.636     wenzelju 11738:                                 icon => 'ungrade_sub.png',
1.598     www      11739:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 11740:                         },
1.598     www      11741: 
                   11742:                         {       linktext => 'Grading table',
                   11743:                                 url => $url1c,
1.781     raeburn  11744:                                 permission => $permissions{'either'},
1.636     wenzelju 11745:                                 icon => 'grading_table.png',
1.598     www      11746:                                 linktitle => 'Grade current resource for all students.'
                   11747:                         },
1.615     www      11748:                         {       linktext => 'Grade page/folder for one student',
1.598     www      11749:                                 url => $url1d,
1.781     raeburn  11750:                                 permission => $permissions{'either'},
1.636     wenzelju 11751:                                 icon => 'grade_PageFolder.png',
1.598     www      11752:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      11753:                         },
                   11754:                         {       linktext => 'Download submissions',
                   11755:                                 url => $url1e,
1.781     raeburn  11756:                                 permission => $permissions{'either'},
1.636     wenzelju 11757:                                 icon => 'download_sub.png',
1.621     www      11758:                                 linktitle => 'Download all students submissions.'
1.598     www      11759:                         }]},
                   11760:                          { categorytitle=>'Automated Grading',
                   11761:                items =>[
                   11762: 
1.538     schulted 11763:                 	    {	linktext => 'Upload Scores',
                   11764:                     		url => $url2,
1.780     raeburn  11765:                     		permission => $permissions{'mgr'},
1.538     schulted 11766:                     		icon => 'uploadscores.png',
                   11767:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   11768:                 	    },
                   11769:                 	    {	linktext => 'Process Clicker',
                   11770:                     		url => $url3,
1.780     raeburn  11771:                     		permission => $permissions{'mgr'},
1.538     schulted 11772:                     		icon => 'addClickerInfoFile.png',
                   11773:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   11774:                 	    },
1.587     raeburn  11775:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 11776:                     		url => $url4,
1.780     raeburn  11777:                     		permission => $permissions{'mgr'},
1.636     wenzelju 11778:                     		icon => 'bubblesheet.png',
1.648     bisitz   11779:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      11780:                 	    },
1.616     www      11781:                             {   linktext => 'Verify Receipt Number',
1.602     www      11782:                                 url => $url5,
1.780     raeburn  11783:                                 permission => $permissions{'either'},
1.636     wenzelju 11784:                                 icon => 'receipt_number.png',
1.602     www      11785:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   11786:                             }
                   11787: 
1.538     schulted 11788:                     ]
                   11789:             });
1.796     raeburn  11790:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   11791:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   11792:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   11793:     if (keys(%passback)) {
                   11794:         $fields{'command'} = 'initialpassback';
                   11795:         my $url6 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11796:         push (@{$menu[1]{items}},
                   11797:                   { linktext => 'Passback of Scores',
                   11798:                     url => $url6,
                   11799:                     permission => $permissions{'either'},
                   11800:                     icon => 'passback.png',
                   11801:                     linktitle => 'Passback scores to launcher CMS for resources accessed via LTI-mediated deep-linking',
                   11802:                   });
                   11803:     }
1.443     banghart 11804:     # Create the menu
                   11805:     my $Str;
1.445     banghart 11806:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   11807:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      11808:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 11809: 
1.602     www      11810:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 11811:     return $Str;    
                   11812: }
                   11813: 
1.598     www      11814: sub ungraded {
                   11815:     my ($request)=@_;
                   11816:     &submit_options($request);
                   11817: }
                   11818: 
1.599     www      11819: sub submit_options_sequence {
1.608     www      11820:     my ($request,$symb) = @_;
1.599     www      11821:     if (!$symb) {return '';}
1.600     www      11822:     &commonJSfunctions($request);
                   11823:     my $result;
1.599     www      11824: 
1.600     www      11825:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11826:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      11827:     $result.=&selectfield(0).
1.601     www      11828:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      11829:             <div>
                   11830:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11831:             </div>
                   11832:         </div>
                   11833:   </form>';
                   11834:     return $result;
                   11835: }
                   11836: 
                   11837: sub submit_options_table {
1.608     www      11838:     my ($request,$symb) = @_;
1.600     www      11839:     if (!$symb) {return '';}
1.599     www      11840:     &commonJSfunctions($request);
1.746     raeburn  11841:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      11842:     my $result;
                   11843: 
                   11844:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11845:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      11846: 
1.745     raeburn  11847:     $result.=&selectfield(1,$is_tool).
1.601     www      11848:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      11849:             <div>
                   11850:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11851:             </div>
                   11852:         </div>
                   11853:   </form>';
                   11854:     return $result;
                   11855: }
1.443     banghart 11856: 
1.621     www      11857: sub submit_options_download {
                   11858:     my ($request,$symb) = @_;
                   11859:     if (!$symb) {return '';}
                   11860: 
1.773     raeburn  11861:     my $res_error;
                   11862:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   11863:         &response_type($symb,\$res_error);
                   11864:     if ($res_error) {
                   11865:         $request->print(&mt('An error occurred retrieving response types'));
                   11866:         return;
                   11867:     }
                   11868:     unless ($numessay) {
                   11869:         $request->print(&mt('No essayresponse items found'));
                   11870:         return;
                   11871:     }
                   11872:     my $table;
                   11873:     if (ref($partlist) eq 'ARRAY') {
                   11874:         if (scalar(@$partlist) > 1 ) {
                   11875:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   11876:         }
                   11877:     }
                   11878: 
1.746     raeburn  11879:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      11880:     &commonJSfunctions($request);
                   11881: 
                   11882:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  11883:                $table."\n".
                   11884:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      11885:     $result.='
                   11886: <h2>
1.750     raeburn  11887:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  11888: </h2>'.&selectfield(1,$is_tool).'
1.621     www      11889:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   11890:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11891:             </div>
                   11892:           </div>
1.600     www      11893: 
                   11894: 
1.621     www      11895:   </form>';
                   11896:     return $result;
                   11897: }
                   11898: 
1.443     banghart 11899: #--- Displays the submissions first page -------
                   11900: sub submit_options {
1.608     www      11901:     my ($request,$symb) = @_;
1.72      ng       11902:     if (!$symb) {return '';}
                   11903: 
1.746     raeburn  11904:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       11905:     &commonJSfunctions($request);
1.473     albertel 11906:     my $result;
1.533     bisitz   11907: 
1.72      ng       11908:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11909: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  11910:     $result.=&selectfield(1,$is_tool).'
1.601     www      11911:                 <input type="hidden" name="command" value="submission" /> 
                   11912: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11913:             </div>
                   11914:           </div>
                   11915:   </form>';
                   11916:     return $result;
                   11917: }
1.533     bisitz   11918: 
1.601     www      11919: sub selectfield {
1.745     raeburn  11920:    my ($full,$is_tool)=@_;
                   11921:    my %options;
                   11922:    if ($is_tool) {
                   11923:        %options =
                   11924:            (&transtatus_options,
                   11925:             'select_form_order' => ['yes','incorrect','all']);
                   11926:    } else {
                   11927:        %options = 
                   11928:            (&substatus_options,
                   11929:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   11930:    }
1.782     raeburn  11931: 
                   11932:   #
                   11933:   # PrepareClasslist() needs to be called to avoid getting a sections list
                   11934:   # for a different course from the @Sections global in lonstatistics.pm, 
                   11935:   # populated by an earlier request.
                   11936:   #
                   11937:    &Apache::lonstatistics::PrepareClasslist();
                   11938: 
1.601     www      11939:    my $result='<div class="LC_columnSection">
1.537     harmsja  11940:   
1.533     bisitz   11941:     <fieldset>
                   11942:       <legend>
                   11943:        '.&mt('Sections').'
                   11944:       </legend>
1.601     www      11945:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   11946:     </fieldset>
1.537     harmsja  11947:   
1.533     bisitz   11948:     <fieldset>
                   11949:       <legend>
                   11950:         '.&mt('Groups').'
                   11951:       </legend>
                   11952:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   11953:     </fieldset>
1.537     harmsja  11954:   
1.533     bisitz   11955:     <fieldset>
                   11956:       <legend>
                   11957:         '.&mt('Access Status').'
                   11958:       </legend>
1.601     www      11959:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   11960:     </fieldset>';
                   11961:     if ($full) {
1.745     raeburn  11962:         my $heading = &mt('Submission Status');
                   11963:         if ($is_tool) {
                   11964:             $heading = &mt('Transaction Status');
                   11965:         }
                   11966:         $result.='
1.533     bisitz   11967:     <fieldset>
                   11968:       <legend>
1.745     raeburn  11969:         '.$heading.'
1.601     www      11970:       </legend>'.
1.635     raeburn  11971:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      11972:    '</fieldset>';
                   11973:     }
                   11974:     $result.='</div><br />';
1.44      ng       11975:     return $result;
1.2       albertel 11976: }
                   11977: 
1.738     raeburn  11978: sub substatus_options {
                   11979:     return &Apache::lonlocal::texthash(
                   11980:                                       'yes'       => 'with submissions',
                   11981:                                       'queued'    => 'in grading queue',
                   11982:                                       'graded'    => 'with ungraded submissions',
                   11983:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  11984:                                       'all'       => 'with any status',
                   11985:                                       );
1.738     raeburn  11986: }
                   11987: 
1.745     raeburn  11988: sub transtatus_options {
                   11989:     return &Apache::lonlocal::texthash(
                   11990:                                        'yes'       => 'with score transactions',
                   11991:                                        'incorrect' => 'with less than full credit',
                   11992:                                        'all'       => 'with any status',
                   11993:                                       );
                   11994: }
                   11995: 
1.285     albertel 11996: sub reset_perm {
                   11997:     undef(%perm);
                   11998: }
                   11999: 
                   12000: sub init_perm {
                   12001:     &reset_perm();
1.770     raeburn  12002:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 12003: 
                   12004: 	my $scope = $env{'request.course.id'};
                   12005: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   12006: 
                   12007: 	    $scope .= '/'.$env{'request.course.sec'};
                   12008: 	    if ( $perm{$test_perm}=
                   12009: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   12010: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   12011: 	    } else {
                   12012: 		delete($perm{$test_perm});
                   12013: 	    }
1.285     albertel 12014: 	}
                   12015:     }
                   12016: }
                   12017: 
1.674     raeburn  12018: sub init_old_essays {
                   12019:     my ($symb,$apath,$adom,$aname) = @_;
                   12020:     if ($symb ne '') {
                   12021:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   12022:         if (keys(%essays) > 0) {
                   12023:             $old_essays{$symb} = \%essays;
                   12024:         }
                   12025:     }
                   12026:     return;
                   12027: }
                   12028: 
                   12029: sub reset_old_essays {
                   12030:     undef(%old_essays);
                   12031: }
                   12032: 
1.400     www      12033: sub gather_clicker_ids {
1.408     albertel 12034:     my %clicker_ids;
1.400     www      12035: 
                   12036:     my $classlist = &Apache::loncoursedata::get_classlist();
                   12037: 
                   12038:     # Set up a couple variables.
1.407     albertel 12039:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   12040:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      12041:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      12042: 
1.407     albertel 12043:     foreach my $student (keys(%$classlist)) {
1.438     www      12044:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 12045:         my $username = $classlist->{$student}->[$username_idx];
                   12046:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      12047:         my $clickers =
1.408     albertel 12048: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      12049:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      12050:             $id=~s/^[\#0]+//;
1.421     www      12051:             $id=~s/[\-\:]//g;
1.407     albertel 12052:             if (exists($clicker_ids{$id})) {
1.408     albertel 12053: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      12054:             } else {
1.408     albertel 12055: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      12056:             }
                   12057:         }
                   12058:     }
1.407     albertel 12059:     return %clicker_ids;
1.400     www      12060: }
                   12061: 
1.402     www      12062: sub gather_adv_clicker_ids {
1.408     albertel 12063:     my %clicker_ids;
1.402     www      12064:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   12065:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   12066:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 12067:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      12068:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   12069:             my ($puname,$pudom)=split(/\:/,$person);
                   12070:             my $clickers =
1.408     albertel 12071: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      12072:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      12073: 		$id=~s/^[\#0]+//;
1.421     www      12074:                 $id=~s/[\-\:]//g;
1.408     albertel 12075: 		if (exists($clicker_ids{$id})) {
                   12076: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   12077: 		} else {
                   12078: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   12079: 		}
1.405     www      12080:             }
1.402     www      12081:         }
                   12082:     }
1.407     albertel 12083:     return %clicker_ids;
1.402     www      12084: }
                   12085: 
1.413     www      12086: sub clicker_grading_parameters {
                   12087:     return ('gradingmechanism' => 'scalar',
                   12088:             'upfiletype' => 'scalar',
                   12089:             'specificid' => 'scalar',
                   12090:             'pcorrect' => 'scalar',
                   12091:             'pincorrect' => 'scalar');
                   12092: }
                   12093: 
1.400     www      12094: sub process_clicker {
1.608     www      12095:     my ($r,$symb)=@_;
1.400     www      12096:     if (!$symb) {return '';}
                   12097:     my $result=&checkforfile_js();
1.632     www      12098:     $result.=&Apache::loncommon::start_data_table().
                   12099:              &Apache::loncommon::start_data_table_header_row().
                   12100:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   12101:              &Apache::loncommon::end_data_table_header_row().
                   12102:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      12103: # Attempt to restore parameters from last session, set defaults if not present
                   12104:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12105:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   12106:                                                  \%Saveable_Parameters);
                   12107:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   12108:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   12109:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   12110:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   12111: 
                   12112:     my %checked;
1.521     www      12113:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      12114:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   12115:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      12116:        }
                   12117:     }
                   12118: 
1.632     www      12119:     my $upload=&mt("Evaluate File");
1.400     www      12120:     my $type=&mt("Type");
1.402     www      12121:     my $attendance=&mt("Award points just for participation");
                   12122:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      12123:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      12124:     my $given=&mt("Correctness determined from given list of answers").' '.
                   12125:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      12126:     my $pcorrect=&mt("Percentage points for correct solution");
                   12127:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      12128:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  12129: 						   {'iclicker' => 'i>clicker',
1.666     www      12130:                                                     'interwrite' => 'interwrite PRS',
                   12131:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 12132:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 12133:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      12134: function sanitycheck() {
                   12135: // Accept only integer percentages
                   12136:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   12137:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   12138: // Find out grading choice
                   12139:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12140:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   12141:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   12142:       }
                   12143:    }
                   12144: // By default, new choice equals user selection
                   12145:    newgradingchoice=gradingchoice;
                   12146: // Not good to give more points for false answers than correct ones
                   12147:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   12148:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   12149:    }
                   12150: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   12151:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   12152:       document.forms.gradesupload.pcorrect.value=100;
                   12153:       document.forms.gradesupload.pincorrect.value=100;
                   12154:    }
                   12155: // If the values are different, cannot be attendance only
                   12156:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   12157:        (gradingchoice=='attendance')) {
                   12158:        newgradingchoice='personnel';
                   12159:    }
                   12160: // Change grading choice to new one
                   12161:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   12162:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   12163:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   12164:       } else {
                   12165:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   12166:       }
                   12167:    }
                   12168: // Remember the old state
                   12169:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   12170: }
1.597     wenzelju 12171: ENDUPFORM
                   12172:     $result.= <<ENDUPFORM;
1.400     www      12173: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   12174: <input type="hidden" name="symb" value="$symb" />
                   12175: <input type="hidden" name="command" value="processclickerfile" />
                   12176: <input type="file" name="upfile" size="50" />
                   12177: <br /><label>$type: $selectform</label>
1.632     www      12178: ENDUPFORM
                   12179:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   12180:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   12181:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   12182: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   12183: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      12184: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   12185: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      12186: <br />&nbsp;&nbsp;&nbsp;
                   12187: <input type="text" name="givenanswer" size="50" />
1.413     www      12188: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      12189: ENDGRADINGFORM
1.766     raeburn  12190:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      12191:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   12192:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   12193: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   12194: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  12195: </form>
1.632     www      12196: ENDPERCFORM
                   12197:     $result.='</td>'.
                   12198:              &Apache::loncommon::end_data_table_row().
                   12199:              &Apache::loncommon::end_data_table();
1.400     www      12200:     return $result;
                   12201: }
                   12202: 
                   12203: sub process_clicker_file {
1.766     raeburn  12204:     my ($r,$symb) = @_;
1.400     www      12205:     if (!$symb) {return '';}
1.413     www      12206: 
                   12207:     my %Saveable_Parameters=&clicker_grading_parameters();
                   12208:     &Apache::loncommon::store_course_settings('grades_clicker',
                   12209:                                               \%Saveable_Parameters);
1.598     www      12210:     my $result='';
1.404     www      12211:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 12212: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      12213: 	return $result;
1.404     www      12214:     }
1.522     www      12215:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      12216:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      12217:         return $result;
1.521     www      12218:     }
1.522     www      12219:     my $foundgiven=0;
1.521     www      12220:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12221:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   12222:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      12223:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      12224:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      12225:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   12226:         $foundgiven=$#answers+1;
1.521     www      12227:     }
1.407     albertel 12228:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 12229:     my %correct_ids;
1.404     www      12230:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 12231: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      12232:     }
                   12233:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      12234: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   12235: 	   $correct_id=~tr/a-z/A-Z/;
                   12236: 	   $correct_id=~s/\s//gs;
                   12237: 	   $correct_id=~s/^[\#0]+//;
1.421     www      12238:            $correct_id=~s/[\-\:]//g;
1.414     www      12239:            if ($correct_id) {
                   12240: 	      $correct_ids{$correct_id}='specified';
                   12241:            }
                   12242:         }
1.400     www      12243:     }
1.404     www      12244:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 12245: 	$result.=&mt('Score based on attendance only');
1.521     www      12246:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      12247:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      12248:     } else {
1.408     albertel 12249: 	my $number=0;
1.411     www      12250: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 12251: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      12252: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 12253: 	    if ($correct_ids{$id} eq 'specified') {
                   12254: 		$result.=&mt('specified');
                   12255: 	    } else {
                   12256: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   12257: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   12258: 	    }
                   12259: 	    $number++;
                   12260: 	}
1.411     www      12261:         $result.="</p>\n";
1.710     bisitz   12262:         if ($number==0) {
                   12263:             $result .=
                   12264:                  &Apache::lonhtmlcommon::confirm_success(
                   12265:                      &mt('No IDs found to determine correct answer'),1);
                   12266:             return $result;
                   12267:         }
1.404     www      12268:     }
1.405     www      12269:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   12270:         $result .=
                   12271:             &Apache::lonhtmlcommon::confirm_success(
                   12272:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   12273:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      12274:         return $result;
1.405     www      12275:     }
1.760     raeburn  12276:     my $mimetype;
                   12277:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   12278:         my $mm = new File::MMagic;
                   12279:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   12280:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   12281:             $result.= '<p>'.
                   12282:                 &Apache::lonhtmlcommon::confirm_success(
                   12283:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   12284:             return $result;
                   12285:         }
                   12286:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   12287:         $result .= '<p>'.
                   12288:             &Apache::lonhtmlcommon::confirm_success(
                   12289:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   12290:         return $result;
                   12291:     }
1.410     www      12292: 
                   12293: # Were able to get all the info needed, now analyze the file
                   12294: 
1.411     www      12295:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 12296:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      12297:     $result.=&Apache::loncommon::start_data_table().
                   12298:              &Apache::loncommon::start_data_table_header_row().
                   12299:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   12300:              &Apache::loncommon::end_data_table_header_row().
                   12301:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   12302: <td>
1.410     www      12303: <form method="post" action="/adm/grades" name="clickeranalysis">
                   12304: <input type="hidden" name="symb" value="$symb" />
                   12305: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      12306: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   12307: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   12308: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      12309: ENDHEADER
1.522     www      12310:     if ($env{'form.gradingmechanism'} eq 'given') {
                   12311:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   12312:     } 
1.408     albertel 12313:     my %responses;
                   12314:     my @questiontitles;
1.405     www      12315:     my $errormsg='';
                   12316:     my $number=0;
                   12317:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  12318:         if ($mimetype eq 'text/plain') {
                   12319:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   12320:         } elsif ($mimetype eq 'text/html') {
                   12321:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   12322:         }
                   12323:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      12324:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  12325:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      12326:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   12327:     }
1.411     www      12328:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   12329:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   12330:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   12331:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   12332:              '<br />';
1.522     www      12333:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   12334:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      12335:        return $result;
1.522     www      12336:     } 
1.414     www      12337: # Remember Question Titles
                   12338: # FIXME: Possibly need delimiter other than ":"
                   12339:     for (my $i=0;$i<$number;$i++) {
                   12340:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   12341:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   12342:     }
1.411     www      12343:     my $correct_count=0;
                   12344:     my $student_count=0;
                   12345:     my $unknown_count=0;
1.414     www      12346: # Match answers with usernames
                   12347: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 12348:     foreach my $id (keys(%responses)) {
1.410     www      12349:        if ($correct_ids{$id}) {
1.414     www      12350:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      12351:           $correct_count++;
1.410     www      12352:        } elsif ($clicker_ids{$id}) {
1.437     www      12353:           if ($clicker_ids{$id}=~/\,/) {
                   12354: # More than one user with the same clicker!
1.632     www      12355:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12356:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12357:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      12358:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12359:                            "<select name='multi".$id."'>";
                   12360:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   12361:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   12362:              }
                   12363:              $result.='</select>';
                   12364:              $unknown_count++;
                   12365:           } else {
                   12366: # Good: found one and only one user with the right clicker
                   12367:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   12368:              $student_count++;
                   12369:           }
1.410     www      12370:        } else {
1.632     www      12371:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   12372:                            &Apache::loncommon::start_data_table_row()."<td>".
                   12373:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      12374:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   12375:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   12376:                    "\n".&mt("Domain").": ".
                   12377:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  12378:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      12379:           $unknown_count++;
1.410     www      12380:        }
1.405     www      12381:     }
1.412     www      12382:     $result.='<hr />'.
                   12383:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      12384:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      12385:        if ($correct_count==0) {
1.696     bisitz   12386:           $errormsg.="Found no correct answers for grading!";
1.412     www      12387:        } elsif ($correct_count>1) {
1.414     www      12388:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      12389:        }
                   12390:     }
1.428     www      12391:     if ($number<1) {
                   12392:        $errormsg.="Found no questions.";
                   12393:     }
1.412     www      12394:     if ($errormsg) {
                   12395:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   12396:     } else {
                   12397:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   12398:     }
1.632     www      12399:     $result.='</form></td>'.
                   12400:              &Apache::loncommon::end_data_table_row().
                   12401:              &Apache::loncommon::end_data_table();
1.614     www      12402:     return $result;
1.400     www      12403: }
                   12404: 
1.405     www      12405: sub iclicker_eval {
1.406     www      12406:     my ($questiontitles,$responses)=@_;
1.405     www      12407:     my $number=0;
                   12408:     my $errormsg='';
                   12409:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      12410:         my %components=&Apache::loncommon::record_sep($line);
                   12411:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 12412: 	if ($entries[0] eq 'Question') {
                   12413: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   12414: 		$$questiontitles[$number]=$entries[$i];
                   12415: 		$number++;
                   12416: 	    }
                   12417: 	}
                   12418: 	if ($entries[0]=~/^\#/) {
                   12419: 	    my $id=$entries[0];
                   12420: 	    my @idresponses;
                   12421: 	    $id=~s/^[\#0]+//;
                   12422: 	    for (my $i=0;$i<$number;$i++) {
                   12423: 		my $idx=3+$i*6;
1.644     www      12424:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 12425: 		push(@idresponses,$entries[$idx]);
                   12426: 	    }
                   12427: 	    $$responses{$id}=join(',',@idresponses);
                   12428: 	}
1.405     www      12429:     }
                   12430:     return ($errormsg,$number);
                   12431: }
                   12432: 
1.760     raeburn  12433: sub iclickerxml_eval {
                   12434:     my ($questiontitles,$responses)=@_;
                   12435:     my $number=0;
                   12436:     my $errormsg='';
                   12437:     my @state;
                   12438:     my %respbyid;
                   12439:     my $p = HTML::Parser->new
                   12440:     (
                   12441:         xml_mode => 1,
                   12442:         start_h =>
                   12443:             [sub {
                   12444:                  my ($tagname,$attr) = @_;
                   12445:                  push(@state,$tagname);
                   12446:                  if ("@state" eq "ssn p") {
                   12447:                      my $title = $attr->{qn};
                   12448:                      $title =~ s/(^\s+|\s+$)//g;
                   12449:                      $questiontitles->[$number]=$title;
                   12450:                  } elsif ("@state" eq "ssn p v") {
                   12451:                      my $id = $attr->{id};
                   12452:                      my $entry = $attr->{ans};
                   12453:                      $id=~s/^[\#0]+//;
                   12454:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   12455:                      $respbyid{$id}[$number] = $entry;
                   12456:                  }
                   12457:             }, "tagname, attr"],
                   12458:          end_h =>
                   12459:                [sub {
                   12460:                    my ($tagname) = @_;
                   12461:                    if ("@state" eq "ssn p") {
                   12462:                        $number++;
                   12463:                    }
                   12464:                    pop(@state);
                   12465:                 }, "tagname"],
                   12466:     );
                   12467: 
                   12468:     $p->parse($env{'form.upfile'});
                   12469:     $p->eof;
                   12470:     foreach my $id (keys(%respbyid)) {
                   12471:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   12472:     }
                   12473:     return ($errormsg,$number);
                   12474: }
                   12475: 
1.419     www      12476: sub interwrite_eval {
                   12477:     my ($questiontitles,$responses)=@_;
                   12478:     my $number=0;
                   12479:     my $errormsg='';
1.420     www      12480:     my $skipline=1;
                   12481:     my $questionnumber=0;
                   12482:     my %idresponses=();
1.419     www      12483:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12484:         my %components=&Apache::loncommon::record_sep($line);
                   12485:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      12486:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   12487:         if ($entries[1] eq 'Response') { $skipline=1; }
                   12488:         next if $skipline;
                   12489:         if ($entries[0]!=$questionnumber) {
                   12490:            $questionnumber=$entries[0];
                   12491:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   12492:            $number++;
1.419     www      12493:         }
1.420     www      12494:         my $id=$entries[4];
                   12495:         $id=~s/^[\#0]+//;
1.421     www      12496:         $id=~s/^v\d*\://i;
                   12497:         $id=~s/[\-\:]//g;
1.420     www      12498:         $idresponses{$id}[$number]=$entries[6];
                   12499:     }
1.524     raeburn  12500:     foreach my $id (keys(%idresponses)) {
1.420     www      12501:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   12502:        $$responses{$id}=~s/^\s*\,//;
1.419     www      12503:     }
                   12504:     return ($errormsg,$number);
                   12505: }
                   12506: 
1.666     www      12507: sub turning_eval {
                   12508:     my ($questiontitles,$responses)=@_;
                   12509:     my $number=0;
                   12510:     my $errormsg='';
                   12511:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12512:         my %components=&Apache::loncommon::record_sep($line);
                   12513:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   12514:         if ($#entries>$number) { $number=$#entries; }
                   12515:         my $id=$entries[0];
                   12516:         my @idresponses;
                   12517:         $id=~s/^[\#0]+//;
                   12518:         unless ($id) { next; }
                   12519:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   12520:             $entries[$idx]=~s/\,/\;/g;
                   12521:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   12522:             push(@idresponses,$entries[$idx]);
                   12523:         }
                   12524:         $$responses{$id}=join(',',@idresponses);
                   12525:     }
                   12526:     for (my $i=1; $i<=$number; $i++) {
                   12527:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   12528:     }
                   12529:     return ($errormsg,$number);
                   12530: }
                   12531: 
                   12532: 
1.414     www      12533: sub assign_clicker_grades {
1.766     raeburn  12534:     my ($r,$symb) = @_;
1.414     www      12535:     if (!$symb) {return '';}
1.416     www      12536: # See which part we are saving to
1.582     raeburn  12537:     my $res_error;
                   12538:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   12539:     if ($res_error) {
                   12540:         return &navmap_errormsg();
                   12541:     }
1.416     www      12542: # FIXME: This should probably look for the first handgradeable part
                   12543:     my $part=$$partlist[0];
                   12544: # Start screen output
1.766     raeburn  12545:     my $result = &Apache::loncommon::start_data_table().
                   12546:                  &Apache::loncommon::start_data_table_header_row().
                   12547:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   12548:                  &Apache::loncommon::end_data_table_header_row().
                   12549:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      12550: # Get correct result
                   12551: # FIXME: Possibly need delimiter other than ":"
                   12552:     my @correct=();
1.415     www      12553:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   12554:     my $number=$env{'form.number'};
                   12555:     if ($gradingmechanism ne 'attendance') {
1.414     www      12556:        foreach my $key (keys(%env)) {
                   12557:           if ($key=~/^form\.correct\:/) {
                   12558:              my @input=split(/\,/,$env{$key});
                   12559:              for (my $i=0;$i<=$#input;$i++) {
                   12560:                  if (($correct[$i]) && ($input[$i]) &&
                   12561:                      ($correct[$i] ne $input[$i])) {
                   12562:                     $result.='<br /><span class="LC_warning">'.
                   12563:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   12564:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      12565:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      12566:                     $correct[$i]=$input[$i];
                   12567:                  }
                   12568:              }
                   12569:           }
                   12570:        }
1.415     www      12571:        for (my $i=0;$i<$number;$i++) {
1.644     www      12572:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      12573:              $result.='<br /><span class="LC_error">'.
                   12574:                       &mt('No correct result given for question "[_1]"!',
                   12575:                           $env{'form.question:'.$i}).'</span>';
                   12576:           }
                   12577:        }
1.644     www      12578:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      12579:     }
                   12580: # Start grading
1.415     www      12581:     my $pcorrect=$env{'form.pcorrect'};
                   12582:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      12583:     my $storecount=0;
1.632     www      12584:     my %users=();
1.415     www      12585:     foreach my $key (keys(%env)) {
1.420     www      12586:        my $user='';
1.415     www      12587:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      12588:           $user=$1;
                   12589:        }
                   12590:        if ($key=~/^form\.unknown\:(.*)$/) {
                   12591:           my $id=$1;
                   12592:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   12593:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      12594:           } elsif ($env{'form.multi'.$id}) {
                   12595:              $user=$env{'form.multi'.$id};
1.420     www      12596:           }
                   12597:        }
1.632     www      12598:        if ($user) {
                   12599:           if ($users{$user}) {
                   12600:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   12601:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      12602:                       '</span><br />';
                   12603:           }
                   12604:           $users{$user}=1; 
1.415     www      12605:           my @answer=split(/\,/,$env{$key});
                   12606:           my $sum=0;
1.522     www      12607:           my $realnumber=$number;
1.415     www      12608:           for (my $i=0;$i<$number;$i++) {
1.576     www      12609:              if  ($correct[$i] eq '-') {
                   12610:                 $realnumber--;
1.766     raeburn  12611:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      12612:                 if ($gradingmechanism eq 'attendance') {
                   12613:                    $sum+=$pcorrect;
1.576     www      12614:                 } elsif ($correct[$i] eq '*') {
1.522     www      12615:                    $sum+=$pcorrect;
1.415     www      12616:                 } else {
1.644     www      12617: # We actually grade if correct or not
                   12618:                    my $increment=$pincorrect;
                   12619: # Special case: numerical answer "0"
                   12620:                    if ($correct[$i] eq '0') {
                   12621:                       if ($answer[$i]=~/^[0\.]+$/) {
                   12622:                          $increment=$pcorrect;
                   12623:                       }
                   12624: # General numerical answer, both evaluate to something non-zero
                   12625:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   12626:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   12627:                          $increment=$pcorrect;
                   12628:                       }
                   12629: # Must be just alphanumeric
                   12630:                    } elsif ($answer[$i] eq $correct[$i]) {
                   12631:                       $increment=$pcorrect;
1.415     www      12632:                    }
1.644     www      12633:                    $sum+=$increment;
1.415     www      12634:                 }
                   12635:              }
                   12636:           }
1.522     www      12637:           my $ave=$sum/(100*$realnumber);
1.416     www      12638: # Store
                   12639:           my ($username,$domain)=split(/\:/,$user);
                   12640:           my %grades=();
                   12641:           $grades{"resource.$part.solved"}='correct_by_override';
                   12642:           $grades{"resource.$part.awarded"}=$ave;
                   12643:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   12644:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   12645:                                                  $env{'request.course.id'},
                   12646:                                                  $domain,$username);
                   12647:           if ($returncode ne 'ok') {
                   12648:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   12649:           } else {
                   12650:              $storecount++;
1.798   ! raeburn  12651:              #FIXME Do passback for $user if required
1.416     www      12652:           }
1.415     www      12653:        }
                   12654:     }
                   12655: # We are done
1.549     hauer    12656:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      12657:              '</td>'.
                   12658:              &Apache::loncommon::end_data_table_row().
                   12659:              &Apache::loncommon::end_data_table();
1.614     www      12660:     return $result;
1.414     www      12661: }
                   12662: 
1.582     raeburn  12663: sub navmap_errormsg {
                   12664:     return '<div class="LC_error">'.
                   12665:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  12666:            &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  12667:            '</div>';
                   12668: }
1.607     droeschl 12669: 
1.609     www      12670: sub startpage {
1.777     raeburn  12671:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  12672:     my %args;
                   12673:     if ($onload) {
                   12674:          my %loaditems = (
                   12675:                         'onload' => $onload,
                   12676:                       );
                   12677:          $args{'add_entries'} = \%loaditems;
                   12678:     }
1.671     raeburn  12679:     if ($nomenu) {
1.754     raeburn  12680:         $args{'only_body'} = 1; 
1.777     raeburn  12681:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  12682:     } else {
1.785     raeburn  12683:         if ($env{'request.course.id'}) { 
                   12684:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   12685:         }
1.754     raeburn  12686:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  12687:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  12688:         if ($env{'request.course.id'}) {
                   12689:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   12690:         }
1.671     raeburn  12691:     }
1.613     www      12692:     unless ($nodisplayflag) {
1.773     raeburn  12693:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      12694:     }
1.607     droeschl 12695: }
1.582     raeburn  12696: 
1.622     www      12697: sub select_problem {
                   12698:     my ($r)=@_;
1.632     www      12699:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  12700:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      12701:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   12702:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   12703: }
                   12704: 
1.793     raeburn  12705: #----- display problem, answer, and submissions for a single student (no grading)
                   12706: 
                   12707: sub view_as_user {
                   12708:     my ($symb,$vuname,$vudom,$hasperm) = @_;
                   12709:     my $plainname = &Apache::loncommon::plainname($vuname,$vudom,'lastname');
                   12710:     my $displayname = &nameUserString('',$plainname,$vuname,$vudom);
                   12711:     my $output = &Apache::loncommon::get_student_view($symb,$vuname,$vudom,
                   12712:                                                       $env{'request.course.id'},
                   12713:                                                       undef,{'disable_submit' => 1}).
                   12714:                  "\n\n".
                   12715:                  '<div class="LC_grade_show_user">'.
                   12716:                  '<h2>'.$displayname.'</h2>'.
                   12717:                  "\n".
                   12718:                  &Apache::loncommon::track_student_link('View recent activity',
                   12719:                                                         $vuname,$vudom,'check').' '.
                   12720:                  "\n";
                   12721:     if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) ||
                   12722:         (($env{'request.course.sec'} ne '') &&
                   12723:          &Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
                   12724:         $output .= &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   12725:                                                $vuname,$vudom,$symb,'check');
                   12726:     }
                   12727:     $output .= "\n";
                   12728:     my $companswer = &Apache::loncommon::get_student_answers($symb,$vuname,$vudom,
                   12729:                                                              $env{'request.course.id'});
                   12730:     $companswer=~s|<form(.*?)>||g;
                   12731:     $companswer=~s|</form>||g;
                   12732:     $companswer=~s|name="submit"|name="would_have_been_submit"|g;
                   12733:     $output .= '<div class="LC_Box">'.
                   12734:                '<h3 class="LC_hcell">'.&mt('Correct answer for[_1]',$displayname).'</h3>'.
                   12735:                $companswer.
                   12736:                '</div>'."\n";
                   12737:     my $is_tool = ($symb =~ /ext\.tool$/);
                   12738:     my ($essayurl,%coursedesc_by_cid);
                   12739:     (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   12740:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$vudom,$vuname);
                   12741:     my $res_error;
                   12742:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   12743:         &response_type($symb,\$res_error);
                   12744:     my $fullname;
                   12745:     my $collabinfo;
                   12746:     if ($numessay) {
                   12747:         unless ($hasperm) {
                   12748:             &init_perm();
                   12749:         }
                   12750:         ($collabinfo,$fullname)=
                   12751:             &check_collaborators($symb,$vuname,$vudom,\%record,$handgrade,0);
                   12752:         unless ($hasperm) {
                   12753:             &reset_perm();
                   12754:         }
                   12755:     }
                   12756:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   12757:                     '" src="'.$Apache::lonnet::perlvar{'lonIconsURL'}.
                   12758:                     '/check.gif" height="16" border="0" />';
                   12759:     my ($lastsubonly,$partinfo) =
                   12760:         &show_last_submission($vuname,$vudom,$symb,$essayurl,$responseType,'datesub',
                   12761:                               '',$fullname,\%record,\%coursedesc_by_cid);
                   12762:     $output .= '<div class="LC_Box">'.
                   12763:                '<h3 class="LC_hcell">'.&mt('Submissions').'</h3>'."\n".$collabinfo."\n";
                   12764:     if (($numresp > $numessay) & !$is_tool) {
                   12765:         $output .='<p class="LC_info">'.
                   12766:                   &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon).
                   12767:                   "</p>\n";
                   12768:     }
                   12769:     $output .= $partinfo;
                   12770:     $output .= $lastsubonly;
                   12771:     $output .= &displaySubByDates($symb,\%record,$partlist,$responseType,$checkIcon,$vuname,$vudom);
                   12772:     $output .= '</div></div>'."\n";
                   12773:     return $output;
                   12774: }
                   12775: 
1.1       albertel 12776: sub handler {
1.41      ng       12777:     my $request=$_[0];
1.434     albertel 12778:     &reset_caches();
1.646     raeburn  12779:     if ($request->header_only) {
                   12780:         &Apache::loncommon::content_type($request,'text/html');
                   12781:         $request->send_http_header;
                   12782:         return OK;
                   12783:     }
                   12784:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   12785: 
1.664     raeburn  12786: # see what command we need to execute
                   12787: 
                   12788:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   12789:     my $command=$commands[0];
                   12790: 
1.646     raeburn  12791:     &init_perm();
                   12792:     if (!$env{'request.course.id'}) {
1.664     raeburn  12793:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   12794:                 ($command =~ /^scantronupload/)) {
                   12795:             # Not in a course.
                   12796:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   12797:             return HTTP_NOT_ACCEPTABLE;
                   12798:         }
1.646     raeburn  12799:     } elsif (!%perm) {
                   12800:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  12801:         return OK;
1.41      ng       12802:     }
1.646     raeburn  12803:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       12804:     $request->send_http_header;
1.646     raeburn  12805: 
1.160     albertel 12806:     if ($#commands > 0) {
                   12807: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   12808:     }
1.608     www      12809: 
                   12810: # see what the symb is
                   12811: 
                   12812:     my $symb=$env{'form.symb'};
                   12813:     unless ($symb) {
                   12814:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   12815:        $symb=&Apache::lonnet::symbread($url);
                   12816:     }
1.646     raeburn  12817:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      12818: 
1.513     foxr     12819:     $ssi_error = 0;
1.637     www      12820:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      12821: #
1.637     www      12822: # Not called from a resource, but inside a course
1.601     www      12823: #    
1.622     www      12824:         &startpage($request,undef,[],1,1);
                   12825:         &select_problem($request);
1.41      ng       12826:     } else {
1.104     albertel 12827: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  12828:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  12829:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   12830:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12831:                     &choose_task_version_form($symb,$env{'form.student'},
                   12832:                                               $env{'form.userdom'});
                   12833:             }
1.773     raeburn  12834:             my $divforres;
                   12835:             if ($env{'form.student'} eq '') {
                   12836:                 $js .= &part_selector_js();
                   12837:                 $onload = "toggleParts('gradesub');";
                   12838:             } else {
                   12839:                 $divforres = 1;
                   12840:             }
1.778     raeburn  12841:             my $head_extra = $js;
                   12842:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12843:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12844:                 if ($csslinks) {
                   12845:                     $head_extra .= "\n$csslinks";
                   12846:                 }
                   12847:             }
1.777     raeburn  12848:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   12849:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  12850:             if ($versionform) {
1.775     raeburn  12851:                 if ($divforres) {
                   12852:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   12853:                 }
1.671     raeburn  12854:                 $request->print($versionform);
                   12855:             }
1.773     raeburn  12856: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  12857:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   12858:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12859:                 &choose_task_version_form($symb,$env{'form.student'},
                   12860:                                           $env{'form.userdom'},
                   12861:                                           $env{'form.inhibitmenu'});
1.778     raeburn  12862:             my $head_extra = $js;
                   12863:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12864:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12865:                 if ($csslinks) {
                   12866:                     $head_extra .= "\n$csslinks";
                   12867:                 }
                   12868:             }
1.777     raeburn  12869:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   12870:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  12871:             if ($versionform) {
                   12872:                 $request->print($versionform);
                   12873:             }
                   12874:             $request->print('<br clear="all" />');
                   12875:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 12876: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      12877:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12878:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      12879: 	    &pickStudentPage($request,$symb);
1.103     albertel 12880: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  12881:             my $csslinks;
                   12882:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12883:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  12884:             }
1.615     www      12885:             &startpage($request,$symb,
                   12886:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12887:                                        {href=>'',text=>'Select student'},
1.777     raeburn  12888:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      12889: 	    &displayPage($request,$symb);
1.104     albertel 12890: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      12891:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12892:                                        {href=>'',text=>'Select student'},
                   12893:                                        {href=>'',text=>'Grade student'},
                   12894:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      12895: 	    &updateGradeByPage($request,$symb);
1.104     albertel 12896: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  12897:             my $csslinks;
                   12898:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12899:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12900:             }
1.619     www      12901:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  12902:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      12903: 	    &processGroup($request,$symb);
1.104     albertel 12904: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      12905:             &startpage($request,$symb);
                   12906: 	    $request->print(&grading_menu($request,$symb));
1.598     www      12907: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      12908:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      12909: 	    $request->print(&submit_options($request,$symb));
1.598     www      12910:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  12911:             my $js = &part_selector_js();
                   12912:             my $onload = "toggleParts('gradesub');";
                   12913:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   12914:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      12915:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      12916:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      12917:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      12918:             $request->print(&submit_options_table($request,$symb));
1.598     www      12919:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      12920:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      12921:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 12922: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      12923:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      12924: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 12925: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      12926:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   12927:                                        {href=>'',text=>'Store grades'}]);
1.608     www      12928: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 12929: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      12930:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   12931:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   12932:                                                                              text=>"Modify grades"},
                   12933:                                        {href=>'', text=>"Store grades"}]);
1.608     www      12934: 	    $request->print(&editgrades($request,$symb));
1.602     www      12935:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      12936:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      12937:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 12938: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      12939:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   12940:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      12941: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      12942:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      12943:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      12944:             $request->print(&process_clicker($request,$symb));
1.400     www      12945:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      12946:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   12947:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      12948:             $request->print(&process_clicker_file($request,$symb));
1.414     www      12949:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      12950:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   12951:                                        {href=>'', text=>'Process clicker file'},
                   12952:                                        {href=>'', text=>'Store grades'}]);
1.608     www      12953:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 12954: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      12955:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12956: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 12957: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      12958:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12959: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 12960: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      12961:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12962: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 12963: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 12964: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      12965:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12966: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       12967: 	    } else {
1.257     albertel 12968: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   12969: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       12970: 		} else {
1.257     albertel 12971: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       12972: 		}
1.627     www      12973:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12974: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       12975: 	    }
1.246     albertel 12976: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      12977:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12978: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 12979: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  12980:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   12981:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      12982: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 12983:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      12984:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      12985:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 12986: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      12987:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      12988: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 12989: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      12990:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      12991: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 12992:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  12993:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  12994:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   12995:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      12996:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 12997:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  12998:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      12999:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13000:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  13001:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      13002:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      13003:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  13004:         } elsif ($command eq 'scantronupload_delete' &&
                   13005:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   13006:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   13007:             &scantron_upload_delete($request,$symb);
1.523     raeburn  13008:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      13009:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      13010:             $request->print(&checkscantron_results($request,$symb));
                   13011:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  13012:             my $js = &part_selector_js();
                   13013:             my $onload = "toggleParts('gradingMenu');";
                   13014:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   13015:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      13016:             $request->print(&submit_options_download($request,$symb));
                   13017:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   13018:             &startpage($request,$symb,
                   13019:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  13020:     {href=>'', text=>'Download submitted files'}],
                   13021:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  13022:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      13023:             &submit_download_link($request,$symb);
1.796     raeburn  13024:         } elsif ($command eq 'initialpassback') {
                   13025:             &startpage($request,$symb,[{href=>'', text=>'Choose Launcher'}],undef,1);
                   13026:             $request->print(&initialpassback($request,$symb));
                   13027:         } elsif ($command eq 'passback') {
                   13028:             &startpage($request,$symb,
                   13029:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13030:                         {href=>'', text=>'Types of User'}],undef,1);
                   13031:             $request->print(&passback_filters($request,$symb));
                   13032:         } elsif ($command eq 'passbacknames') {
                   13033:             my $chosen;
                   13034:             if ($env{'form.passback'} ne '') {
                   13035:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13036:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13037:                 }
                   13038:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13039:             }
                   13040:             &startpage($request,$symb,
                   13041:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13042:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13043:                         {href=>'', text=>'Select Users'}],undef,1);
                   13044:             $request->print(&names_for_passback($request,$symb));
                   13045:         } elsif ($command eq 'passbackscores') {
                   13046:             my ($chosen,$stu_status);
                   13047:             if ($env{'form.passback'} ne '') {
                   13048:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   13049:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   13050:                 }
                   13051:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   13052:             }
                   13053:             if ($env{'form.Status'}) {
                   13054:                 $stu_status = &HTML::Entities::encode($env{'form.Status'});
                   13055:             }
                   13056:             &startpage($request,$symb,
                   13057:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   13058:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   13059:                         {href=>&href_symb_cmd($symb,'passbacknames').'&amp;Status='.$stu_status.'&amp;passback='.$chosen, text=>'Select Users'},
                   13060:                         {href=>'', text=>'Execute Passback'}],undef,1);
                   13061:             $request->print(&do_passback($request,$symb));
1.106     albertel 13062: 	} elsif ($command) {
1.620     www      13063:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   13064: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 13065: 	}
1.2       albertel 13066:     }
1.513     foxr     13067:     if ($ssi_error) {
                   13068: 	&ssi_print_error($request);
                   13069:     }
1.671     raeburn  13070:     if ($env{'form.inhibitmenu'}) {
                   13071:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  13072:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  13073:         &Apache::lonquickgrades::endGradeScreen($request);
                   13074:     }
1.434     albertel 13075:     &reset_caches();
1.646     raeburn  13076:     return OK;
1.44      ng       13077: }
                   13078: 
1.1       albertel 13079: 1;
                   13080: 
1.13      albertel 13081: __END__;
1.531     jms      13082: 
                   13083: 
                   13084: =head1 NAME
                   13085: 
                   13086: Apache::grades
                   13087: 
                   13088: =head1 SYNOPSIS
                   13089: 
                   13090: Handles the viewing of grades.
                   13091: 
                   13092: This is part of the LearningOnline Network with CAPA project
                   13093: described at http://www.lon-capa.org.
                   13094: 
                   13095: =head1 OVERVIEW
                   13096: 
                   13097: Do an ssi with retries:
1.715     bisitz   13098: While I'd love to factor out this with the version in lonprintout,
1.531     jms      13099: 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
                   13100: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   13101: 
                   13102: At least the logic that drives this has been pulled out into loncommon.
                   13103: 
                   13104: 
                   13105: 
                   13106: ssi_with_retries - Does the server side include of a resource.
                   13107:                      if the ssi call returns an error we'll retry it up to
                   13108:                      the number of times requested by the caller.
1.715     bisitz   13109:                      If we still have a problem, no text is appended to the
1.531     jms      13110:                      output and we set some global variables.
                   13111:                      to indicate to the caller an SSI error occurred.  
                   13112:                      All of this is supposed to deal with the issues described
1.715     bisitz   13113:                      in LON-CAPA BZ 5631 see:
1.531     jms      13114:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   13115:                      by informing the user that this happened.
                   13116: 
                   13117: Parameters:
                   13118:   resource   - The resource to include.  This is passed directly, without
                   13119:                interpretation to lonnet::ssi.
                   13120:   form       - The form hash parameters that guide the interpretation of the resource
                   13121:                
                   13122:   retries    - Number of retries allowed before giving up completely.
                   13123: Returns:
                   13124:   On success, returns the rendered resource identified by the resource parameter.
                   13125: Side Effects:
                   13126:   The following global variables can be set:
                   13127:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   13128:                               It is up to the caller to initialize this to false
                   13129:                               if desired.
                   13130:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   13131:                               of the resource that could not be rendered by the ssi
                   13132:                               call.
                   13133:    ssi_error_message   - The error string fetched from the ssi response
                   13134:                               in the event of an error.
                   13135: 
                   13136: 
                   13137: =head1 HANDLER SUBROUTINE
                   13138: 
                   13139: ssi_with_retries()
                   13140: 
                   13141: =head1 SUBROUTINES
                   13142: 
                   13143: =over
                   13144: 
1.671     raeburn  13145: =head1 Routines to display previous version of a Task for a specific student
                   13146: 
                   13147: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   13148: can receive another opportunity. Access to tasks is slot-based. If a slot
                   13149: requires a proctor to check-in the student, a new version of the Task will
                   13150: be created when the student is checked in to the new opportunity.
                   13151: 
                   13152: If a particular student has tried two or more versions of a particular task,
                   13153: the submission screen provides a user with vgr privileges (e.g., a Course
                   13154: Coordinator) the ability to display a previous version worked on by the
                   13155: student.  By default, the current version is displayed. If a previous version
                   13156: has been selected for display, submission data are only shown that pertain
                   13157: to that particular version, and the interface to submit grades is not shown.
                   13158: 
                   13159: =over 4
                   13160: 
                   13161: =item show_previous_task_version()
                   13162: 
                   13163: Displays a specified version of a student's Task, as the student sees it.
                   13164: 
                   13165: Inputs: 2
                   13166:         request - request object
                   13167:         symb    - unique symb for current instance of resource
                   13168: 
                   13169: Output: None.
                   13170: 
                   13171: Side Effects: calls &show_problem() to print version of Task, with
                   13172:               version contained in form item: $env{'form.previousversion'}
                   13173: 
                   13174: =item choose_task_version_form()
                   13175: 
                   13176: Displays a web form used to select which version of a student's view of a
                   13177: Task should be displayed.  Either launches a pop-up window, or replaces
                   13178: content in existing pop-up, or replaces page in main window.
                   13179: 
                   13180: Inputs: 4
                   13181:         symb    - unique symb for current instance of resource
                   13182:         uname   - username of student
                   13183:         udom    - domain of student
                   13184:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13185:                   breadcrumbs etc., are displayed
                   13186: 
                   13187: Output: 4
                   13188:         current   - student's current version
                   13189:         displayed - student's version being displayed
                   13190:         result    - scalar containing HTML for web form used to switch to
                   13191:                     a different version (or a link to close window, if pop-up).
                   13192:         js        - javascript for processing selection in versions web form
                   13193: 
                   13194: Side Effects: None.
                   13195: 
                   13196: =item previous_display_javascript()
                   13197: 
                   13198: Inputs: 2
                   13199:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   13200:                   breadcrumbs etc., are displayed.
                   13201:         current - student's current version number.
                   13202: 
                   13203: Output: 1
                   13204:         js      - javascript for processing selection in versions web form.
                   13205: 
                   13206: Side Effects: None.
                   13207: 
                   13208: =back
                   13209: 
                   13210: =head1 Routines to process bubblesheet data.
                   13211: 
                   13212: =over 4
                   13213: 
1.531     jms      13214: =item scantron_get_correction() : 
                   13215: 
                   13216:    Builds the interface screen to interact with the operator to fix a
                   13217:    specific error condition in a specific scanline
                   13218: 
                   13219:  Arguments:
                   13220:     $r           - Apache request object
                   13221:     $i           - number of the current scanline
                   13222:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  13223:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      13224:     $line        - full contents of the current scanline
                   13225:     $error       - error condition, valid values are
                   13226:                    'incorrectCODE', 'duplicateCODE',
                   13227:                    'doublebubble', 'missingbubble',
                   13228:                    'duplicateID', 'incorrectID'
                   13229:     $arg         - extra information needed
                   13230:        For errors:
                   13231:          - duplicateID   - paper number that this studentID was seen before on
                   13232:          - duplicateCODE - array ref of the paper numbers this CODE was
                   13233:                            seen on before
                   13234:          - incorrectCODE - current incorrect CODE 
                   13235:          - doublebubble  - array ref of the bubble lines that have double
                   13236:                            bubble errors
                   13237:          - missingbubble - array ref of the bubble lines that have missing
                   13238:                            bubble errors
                   13239: 
1.788     raeburn  13240:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   13241:    $randompick  - True if exam folder (or a sub-folder) has randompick set
1.691     raeburn  13242:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   13243:                      for current line to question number used for same question
                   13244:                      in "Master Seqence" (as seen by Course Coordinator).
                   13245:    $startline   - Reference to hash where key is question number (0 is first)
                   13246:                   and value is number of first bubble line for current student
                   13247:                   or code-based randompick and/or randomorder.
                   13248: 
                   13249: 
                   13250: 
1.531     jms      13251: =item  scantron_get_maxbubble() : 
                   13252: 
1.582     raeburn  13253:    Arguments:
                   13254:        $nav_error  - Reference to scalar which is a flag to indicate a
                   13255:                       failure to retrieve a navmap object.
                   13256:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   13257:        calling routine should trap the error condition and display the warning
                   13258:        found in &navmap_errormsg().
                   13259: 
1.649     raeburn  13260:        $scantron_config - Reference to bubblesheet format configuration hash.
                   13261: 
1.531     jms      13262:    Returns the maximum number of bubble lines that are expected to
                   13263:    occur. Does this by walking the selected sequence rendering the
                   13264:    resource and then checking &Apache::lonxml::get_problem_counter()
                   13265:    for what the current value of the problem counter is.
                   13266: 
                   13267:    Caches the results to $env{'form.scantron_maxbubble'},
                   13268:    $env{'form.scantron.bubble_lines.n'}, 
                   13269:    $env{'form.scantron.first_bubble_line.n'} and
                   13270:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  13271:    which are the total number of bubble lines, the number of bubble
1.531     jms      13272:    lines for response n and number of the first bubble line for response n,
                   13273:    and a comma separated list of numbers of bubble lines for sub-questions
                   13274:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   13275: 
                   13276: 
                   13277: =item  scantron_validate_missingbubbles() : 
                   13278: 
                   13279:    Validates all scanlines in the selected file to not have any
                   13280:     answers that don't have bubbles that have not been verified
                   13281:     to be bubble free.
                   13282: 
                   13283: =item  scantron_process_students() : 
                   13284: 
1.659     raeburn  13285:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      13286: 
                   13287:    The parsed scanline hash is added to %env 
                   13288: 
                   13289:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   13290:    foreach resource , with the form data of
                   13291: 
                   13292: 	'submitted'     =>'scantron' 
                   13293: 	'grade_target'  =>'grade',
                   13294: 	'grade_username'=> username of student
                   13295: 	'grade_domain'  => domain of student
                   13296: 	'grade_courseid'=> of course
                   13297: 	'grade_symb'    => symb of resource to grade
                   13298: 
                   13299:     This triggers a grading pass. The problem grading code takes care
                   13300:     of converting the bubbled letter information (now in %env) into a
                   13301:     valid submission.
                   13302: 
                   13303: =item  scantron_upload_scantron_data() :
                   13304: 
1.659     raeburn  13305:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      13306: 
                   13307: =item  scantron_upload_scantron_data_save() : 
                   13308: 
                   13309:    Adds a provided bubble information data file to the course if user
1.770     raeburn  13310:    has the correct privileges to do so.
                   13311: 
                   13312: = item scantron_upload_delete() :
                   13313: 
                   13314:    Deletes a previously uploaded bubble information data file, if user
                   13315:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      13316: 
                   13317: =item  valid_file() :
                   13318: 
                   13319:    Validates that the requested bubble data file exists in the course.
                   13320: 
                   13321: =item  scantron_download_scantron_data() : 
                   13322: 
                   13323:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  13324:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      13325:    course.
                   13326: 
                   13327: =item  scantron_validate_ID() : 
                   13328: 
                   13329:    Validates all scanlines in the selected file to not have any
1.556     weissno  13330:    invalid or underspecified student/employee IDs
1.531     jms      13331: 
1.582     raeburn  13332: =item navmap_errormsg() :
                   13333: 
                   13334:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  13335:    Should be called whenever the request to instantiate a navmap object fails.
                   13336: 
                   13337: =back
1.582     raeburn  13338: 
1.531     jms      13339: =back
                   13340: 
                   13341: =cut

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