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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.797   ! raeburn     4: # $Id: grades.pm,v 1.796 2024/12/03 23:34:10 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.752     raeburn    49: use Apache::lontexconvert();
1.796     raeburn    50: use Apache::loncourserespicker;
1.170     albertel   51: use String::Similarity;
1.760     raeburn    52: use HTML::Parser();
                     53: use File::MMagic;
1.359     www        54: use LONCAPA;
1.796     raeburn    55: use LONCAPA::ltiutils();
1.359     www        56: 
1.315     bowersj2   57: use POSIX qw(floor);
1.87      www        58: 
1.435     foxr       59: 
1.513     foxr       60: 
1.435     foxr       61: my %perm=();
1.674     raeburn    62: my %old_essays=();
1.447     foxr       63: 
1.513     foxr       64: #  These variables are used to recover from ssi errors
                     65: 
                     66: my $ssi_retries = 5;
                     67: my $ssi_error;
                     68: my $ssi_error_resource;
                     69: my $ssi_error_message;
                     70: 
                     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') {
                    779:                     $passback{$student} = $pbinfo{$filterbypbid}
                    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.796     raeburn  1064: sub initialpassback {
                   1065:     my ($request,$symb) = @_;
                   1066:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1067:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1068:     my $crstype = &Apache::loncommon::course_type();
                   1069:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   1070:     my $readonly;
                   1071:     unless ($perm{'mgr'}) {
                   1072:         $readonly = 1;
                   1073:     }
                   1074:     my $formname = 'initialpassback';
                   1075:     my $navmap = Apache::lonnavmaps::navmap->new();
                   1076:     my $output;
                   1077:     if (!defined($navmap)) {
                   1078:         if ($crstype eq 'Community') {
                   1079:             $output = &mt('Unable to retrieve information about community contents');
                   1080:         } else {
                   1081:             $output = &mt('Unable to retrieve information about course contents');
                   1082:         }
                   1083:         return '<p>'.$output.'</p>';
                   1084:     }
                   1085:     return &Apache::loncourserespicker::create_picker($navmap,'passback',$formname,$crstype,undef,
                   1086:                                                       undef,undef,undef,undef,undef,undef,
                   1087:                                                       \%passback,$readonly);
                   1088: }
                   1089: 
                   1090: sub passback_filters {
                   1091:     my ($request,$symb) = @_;
                   1092:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1093:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1094:     my $crstype = &Apache::loncommon::course_type();
                   1095:     my ($launcher,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
                   1096:     if ($env{'form.passback'} ne '') {
                   1097:         $chosen = &unescape($env{'form.passback'});
                   1098:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1099:         ($launcher,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
                   1100:     }
                   1101:     my $result;
                   1102:     if ($launcher ne '') {
                   1103:         $result = &launcher_info_box($launcher,$appname,$setter,$linkuri,$scope).
                   1104:                   '<p><br />'.&mt('Set criteria to use to list students for possible passback of scores, then push Next [_1]',
                   1105:                                   '&rarr;').
                   1106:                   '</p>';
                   1107:     }
                   1108:     $result .= '<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   1109:                '<input type="hidden" name="passback" value="'.&escape($chosen).'" />'."\n".
                   1110:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   1111:     my ($submittext,$newcommand);
                   1112:     if ($launcher ne '') {
                   1113:         $submittext = &mt('Next').' &rarr;';
                   1114:         $newcommand = 'passbacknames';
                   1115:         $result .=  &selectfield(0)."\n";
                   1116:     } else {
                   1117:         $submittext = '&larr; '.&mt('Previous');
                   1118:         $newcommand = 'initialpassback';
                   1119:         if ($env{'form.passback'}) {
                   1120:             $result .= '<span class="LC_warning">'.&mt('Invalid launcher').'</span>'."\n";
                   1121:         } else {
                   1122:             $result .= '<span class="LC_warning">'.&mt('No launcher selected').'</span>'."\n";
                   1123:         }
                   1124:     }
                   1125:     $result .=  '<input type="hidden" name="command" value="'.$newcommand.'" />'."\n".
                   1126:                 '<div>'."\n".
                   1127:                 '<input type="submit" value="'.$submittext.'" />'."\n".
                   1128:                 '</div>'."\n".
                   1129:                 '</form>'."\n";
                   1130:     return $result;
                   1131: }
                   1132: 
                   1133: sub names_for_passback {
                   1134:     my ($request,$symb) = @_;
                   1135:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1136:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1137:     my $crstype = &Apache::loncommon::course_type();
                   1138:     my ($launcher,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
                   1139:     if ($env{'form.passback'} ne '') {
                   1140:         $chosen = &unescape($env{'form.passback'});
                   1141:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1142:         ($launcher,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
                   1143:     }
                   1144:     my ($result,$ctr,$newcommand,$submittext);
                   1145:     if ($launcher ne '') {
                   1146:         $result = &launcher_info_box($launcher,$appname,$setter,$linkuri,$scope);
                   1147:     }
                   1148:     $ctr = 0;
                   1149:     my @statuses = &Apache::loncommon::get_env_multiple('form.Status');
                   1150:     my $stu_status = join(':',@statuses);
                   1151:     $result .= '<form action="/adm/grades" method="post" name="passbackusers">'."\n".
                   1152:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   1153:     if ($launcher ne '') {
                   1154:         $result .= '<input type="hidden" name="passback" value="'.&escape($chosen).'" />'."\n".
                   1155:                    '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
                   1156:         my ($sections,$groups,$group_display,$disabled) = &sections_and_groups();
                   1157:         my $section_display = join(' ',@{$sections});
                   1158:         my $status_display;
                   1159:         if ((grep(/^Any$/,@statuses)) ||
                   1160:             (@statuses == 3)) {
                   1161:             $status_display = &mt('Any');
                   1162:         } else {
                   1163:             $status_display = join(' '.&mt('or').' ',map { &mt($_); } @statuses);
                   1164:         }
                   1165:         $result .= '<p>'.&mt('Student(s) with stored passback credentials for [_1], and also satisfy:',
                   1166:                              '<span class="LC_cusr_emph">'.$linkuri.'</span>').
                   1167:                    '<ul>'.
                   1168:                    '<li>'.&mt('Section(s)').": $section_display</li>\n".
                   1169:                    '<li>'.&mt('Group(s)').": $group_display</li>\n".
                   1170:                    '<li>'.&mt('Status').": $status_display</li>\n".
                   1171:                    '</ul>';
                   1172:         my ($classlist,undef,$fullname) = &getclasslist($sections,'1',$groups,'','','',$chosen);
                   1173:         if (keys(%$fullname)) {
                   1174:             $newcommand = 'passbackscores';
                   1175:             $result .= &build_section_inputs().
                   1176:                        &checkselect_js('passbackusers').
                   1177:                        '<p><br />'.
                   1178:                        &mt("To send scores, check box(es) next to the student's name(s), then push 'Send Scores'.").
                   1179:                        '</p>'.
                   1180:                        &check_script('passbackusers', 'stuinfo')."\n".
                   1181:                        '<input type="button" '."\n".
                   1182:                        'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1183:                        'value="'.&mt('Send Scores').'" /> <br />'."\n".
                   1184:                        &check_buttons()."\n".
                   1185:                        &Apache::loncommon::start_data_table().
                   1186:                        &Apache::loncommon::start_data_table_header_row();
                   1187:             my $loop = 0;
                   1188:             while ($loop < 2) {
                   1189:                 $result .= '<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1190:                            '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
                   1191:                 $loop++;
                   1192:             }
                   1193:             $result .= &Apache::loncommon::end_data_table_header_row()."\n";
                   1194:             foreach my $student (sort
                   1195:                                  {
                   1196:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1197:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1198:                                      }
                   1199:                                      return $a cmp $b;
                   1200:                                  }
                   1201:                                  (keys(%$fullname))) {
                   1202:                 $ctr++;
                   1203:                 my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                   1204:                 my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
                   1205:                 my $udom = $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                   1206:                 my $uname = $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                   1207:                 if ( $perm{'vgr'} eq 'F' ) {
                   1208:                     if ($ctr%2 ==1) {
                   1209:                         $result.= &Apache::loncommon::start_data_table_row();
                   1210:                     }
                   1211:                     $result .= '<td align="right">'.$ctr.'&nbsp;</td>'.
                   1212:                                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
                   1213:                                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1214:                                ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1215:                                &nameUserString(undef,$$fullname{$student},$uname,$udom).
                   1216:                                '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
                   1217: 
                   1218:                     if ($ctr%2 ==0) {
                   1219:                         $result .= &Apache::loncommon::end_data_table_row()."\n";
                   1220:                     }
                   1221:                 }
                   1222:             }
                   1223:             if ($ctr%2 ==1) {
                   1224:                 $result .= &Apache::loncommon::end_data_table_row();
                   1225:             }
                   1226:             $result .= &Apache::loncommon::end_data_table()."\n";
                   1227:             if ($ctr) {
                   1228:                 $result .= '<input type="button" '.
                   1229:                            'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1230:                            'value="'.&mt('Send Scores').'" />'."\n";
                   1231:             }
                   1232:         } else {
                   1233:             $submittext = '&larr; '.&mt('Previous');
                   1234:             $newcommand = 'passback';
                   1235:             $result .= '<span class="LC_warning">'.&mt('No students match the selection criteria').'</p>';
                   1236:         }
                   1237:     } else {
                   1238:         $newcommand = 'initialpassback';
                   1239:         $submittext = &mt('Start over');
                   1240:         if ($env{'form.passback'}) {
                   1241:             $result .= '<span class="LC_warning">'.&mt('Invalid launcher').'</span>'."\n";
                   1242:         } else {
                   1243:             $result .= '<span class="LC_warning">'.&mt('No launcher selected').'</span>'."\n";
                   1244:         }
                   1245:     }
                   1246:     $result .=  '<input type="hidden" name="command" value="'.$newcommand.'" />'."\n";
                   1247:     if (!$ctr) {
                   1248:         $result .= '<div>'."\n".
                   1249:                    '<input type="submit" value="'.$submittext.'" />'."\n".
                   1250:                    '</div>'."\n";
                   1251:     }
                   1252:     $result .= '</form>'."\n";
                   1253:     return $result;
                   1254: }
                   1255: 
                   1256: sub do_passback {
                   1257:     my ($request,$symb) = @_;
                   1258:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   1259:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   1260:     my $crstype = &Apache::loncommon::course_type();
                   1261:     my ($launcher,$appname,$setter,$linkuri,$linkprotector,$scope,$chosen);
                   1262:     if ($env{'form.passback'} ne '') {
                   1263:         $chosen = &unescape($env{'form.passback'});
                   1264:         ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1265:         ($launcher,$appname,$setter) = &get_passback_launcher($cdom,$cnum,$chosen);
                   1266:     }
                   1267:     if ($launcher ne '') {
                   1268:         $request->print(&launcher_info_box($launcher,$appname,$setter,$linkuri,$scope));
                   1269:     }
                   1270:     my $error;
                   1271:     if ($perm{'mgr'}) {
                   1272:         if ($launcher ne '') {
                   1273:             my @poss_students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   1274:             if (@poss_students) {
                   1275:                 my %possibles;
                   1276:                 foreach my $item (@poss_students) {
                   1277:                     my ($stuname,$studom) = split(/:/,$item,3);
                   1278:                     $possibles{$stuname.':'.$studom} = 1;
                   1279:                 }
                   1280:                 my ($sections,$groups,$group_display,$disabled) = &sections_and_groups();
                   1281:                 my ($classlist,undef,$fullname,$pbinfo) =
                   1282:                     &getclasslist($sections,'1',$groups,'','','',$chosen,\%possibles);
                   1283:                 if ((ref($classlist) eq 'HASH') && (ref($pbinfo) eq 'HASH')) {
                   1284:                     my %passback = %{$pbinfo};
                   1285:                     my (%tosend,%remotenotok,%scorenotok,%zeroposs,%nopbinfo);
                   1286:                     foreach my $possible (keys(%possibles)) {
                   1287:                         if ((exists($classlist->{$possible})) &&
                   1288:                             (exists($passback{$possible})) && (ref($passback{$possible}) eq 'ARRAY')) {
                   1289:                             $tosend{$possible} = 1;
                   1290:                         }
                   1291:                     }
                   1292:                     if (keys(%tosend)) {
                   1293:                         my ($lti_in_use,$crsdef);
                   1294:                         my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
                   1295:                         if ($ltitype eq 'c') {
                   1296:                             my %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1297:                             $lti_in_use = $crslti{$ltinum};
                   1298:                             $crsdef = 1;
                   1299:                         } else {
                   1300:                             my %domlti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1301:                             $lti_in_use = $domlti{$ltinum};
                   1302:                         }
                   1303:                         if (ref($lti_in_use) eq 'HASH') {
                   1304:                             my $msgformat = $lti_in_use->{'passbackformat'};
                   1305:                             my $keynum = $lti_in_use->{'cipher'};
                   1306:                             my $scoretype = 'decimal';
                   1307:                             if ($lti_in_use->{'scoreformat'} =~ /^(decimal|ratio|percentage)$/) {
                   1308:                                 $scoretype = $1;
                   1309:                             }
                   1310:                             my $pbsymb = &Apache::loncommon::symb_from_tinyurl($linkuri,$cnum,$cdom);
                   1311:                             my $pbmap;
                   1312:                             if ($pbsymb =~ /\.(page|sequence)$/) {
                   1313:                                 $pbmap = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pbsymb))[2]);
                   1314:                             } else {
                   1315:                                 $pbmap = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($pbsymb))[0]);
                   1316:                             }
                   1317:                             $pbmap = &Apache::lonnet::clutter($pbmap);
                   1318:                             my $pbscope;
                   1319:                             if ($scope eq 'res') {
                   1320:                                 $pbscope = 'resource';
                   1321:                             } elsif ($scope eq 'map') {
                   1322:                                 $pbscope = 'nonrec';
                   1323:                             } elsif ($scope eq 'rec') {
                   1324:                                 $pbscope = 'map';
                   1325:                             }
                   1326:                             my $sigmethod = 'HMAC-SHA1';
                   1327:                             my $type = 'linkprot';
                   1328:                             my $clientip = &Apache::lonnet::get_requestor_ip();
                   1329:                             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   1330:                             my $ip = &Apache::lonnet::get_host_ip($lonhost);
                   1331:                             my $numstudents = scalar(keys(%tosend));
                   1332:                             my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($request,$numstudents);
                   1333:                             my $outcome = &Apache::loncommon::start_data_table().
                   1334:                                          &Apache::loncommon::start_data_table_header_row();
                   1335:                             my $loop = 0;
                   1336:                             while ($loop < 2) {
                   1337:                                 $outcome .= '<th>'.&mt('No.').'</th>'.
                   1338:                                            '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>'.
                   1339:                                            '<th>'.&mt('Score').'</th>';
                   1340:                                  $loop++;
                   1341:                             }
                   1342:                             $outcome .= &Apache::loncommon::end_data_table_header_row()."\n";
                   1343:                             my $ctr=0;
                   1344:                             foreach my $student (sort
                   1345:                                 {
                   1346:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1347:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1348:                                      }
                   1349:                                      return $a cmp $b;
                   1350:                                 } (keys(%$fullname))) {
                   1351:                                 next unless ($tosend{$student});
                   1352:                                 my ($uname,$udom) = split(/:/,$student);
                   1353:                                 &Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last student');
                   1354:                                 my ($uname,$udom) = split(/:/,$student);
                   1355:                                 my $uhome = &Apache::lonnet::homeserver($uname,$udom),
                   1356:                                 my $id = $passback{$student}[0],
                   1357:                                 my $url = $passback{$student}[1],
                   1358:                                 my ($total,$possible,$usec);
                   1359:                                 if (ref($classlist->{$student}) eq 'ARRAY') {
                   1360:                                     $usec = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION];
                   1361:                                 }
                   1362:                                 if ($pbscope eq 'resource') {
                   1363:                                     $total = 0;
                   1364:                                     $possible = 0;
                   1365:                                     my $navmap = Apache::lonnavmaps::navmap->new($uname,$udom);
                   1366:                                     if (ref($navmap)) {
                   1367:                                         my $res = $navmap->getBySymb($pbsymb);
                   1368:                                         if (ref($res)) {
                   1369:                                             my $partlist = $res->parts();
                   1370:                                             if (ref($partlist) eq 'ARRAY') {
                   1371:                                                 my %record = &Apache::lonnet::restore($pbsymb,$env{'request.course.id'},$udom,$uname);
                   1372:                                                 foreach my $part (@{$partlist}) {
                   1373:                                                     next if ($record{"resource.$part.solved"} =~/^excused/);
                   1374:                                                     my $weight = &Apache::lonnet::EXT("resource.$part.weight",$pbsymb,$udom,$uname,$usec);
                   1375:                                                     $possible += $weight;
                   1376:                                                     if (($record{'version'}) && (exists($record{"resource.$part.awarded"}))) {
                   1377:                                                         my $awarded = $record{"resource.$part.awarded"};
                   1378:                                                         if ($awarded) {
                   1379:                                                             $total += $weight * $awarded;
                   1380:                                                         }
                   1381:                                                     }
                   1382:                                                 }
                   1383:                                             }
                   1384:                                         }
                   1385:                                     }
                   1386:                                 } elsif (($pbscope eq 'map') || ($pbscope eq 'nonrec')) {
                   1387:                                     ($total,$possible) =
                   1388:                                         &Apache::lonhomework::get_lti_score($uname,$udom,$pbmap,$pbscope);
                   1389:                                 }
                   1390:                                 if (($id ne '') && ($url ne '') && ($possible)) {
                   1391:                                     my ($sent,$score,$code,$result) =
                   1392:                                         &LONCAPA::ltiutils::send_grade($cdom,$cnum,$crsdef,$type,$ltinum,$keynum,$id,
                   1393:                                                                        $url,$scoretype,$sigmethod,$msgformat,$total,$possible);
                   1394:                                     my $no_passback;
                   1395:                                     if ($sent) {
                   1396:                                         if ($code == 200) {
                   1397:                                             delete($tosend{$student});
                   1398:                                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
                   1399:                                             my $store = {
                   1400:                                                  'score' => $score,
                   1401:                                                  'ip' => $ip,
                   1402:                                                  'host' => $lonhost,
                   1403:                                                  'protector' => $linkprotector,
                   1404:                                                  'deeplink' => $linkuri,
                   1405:                                                  'scope' => $scope,
                   1406:                                                  'url' => $url,
                   1407:                                                  'id' => $id,
                   1408:                                                  'clientip' => $clientip,
                   1409:                                                  'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
                   1410:                                                 };
                   1411:                                             my $value='';
                   1412:                                             foreach my $key (keys(%{$store})) {
                   1413:                                                 $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
                   1414:                                             }
                   1415:                                             $value=~s/\&$//;
                   1416:                                             &Apache::lonnet::courselog(&escape($linkuri).':'.$uname.':'.$udom.':EXPORT:'.$value);
                   1417:                                             &Apache::lonnet::cstore({'score' => $score},$chosen,$namespace,$udom,$uname,'',$ip,1);
                   1418:                                             $ctr++;
                   1419:                                             if ($ctr%2 ==1) {
                   1420:                                                 $outcome .= &Apache::loncommon::start_data_table_row();
                   1421:                                             }
                   1422:                                             my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                   1423:                                             my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
                   1424:                                             $outcome .= '<td align="right">'.$ctr.'&nbsp;</td>'.
                   1425:                                                        '<td>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).
                   1426:                                                        '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'.
                   1427:                                                        '<td>'.$score.'</td>'."\n";
                   1428:                                             if ($ctr%2 ==0) {
                   1429:                                                 $outcome .= &Apache::loncommon::end_data_table_row()."\n";
                   1430:                                             }
                   1431:                                         } else {
                   1432:                                             $remotenotok{$student} = 1;
                   1433:                                             $no_passback = "Passback response for ".$linkprotector." was $code ($result)";
                   1434:                                             &Apache::lonnet::logthis($no_passback." for $uname:$udom in ${cdom}_${cnum}");
                   1435:                                         }
                   1436:                                     } else {
                   1437:                                         $scorenotok{$student} = 1;
                   1438:                                         $no_passback = "Passback of grades not sent for ".$linkprotector;
                   1439:                                         &Apache::lonnet::logthis($no_passback." for $uname:$udom in ${cdom}_${cnum}");
                   1440:                                     }
                   1441:                                     if ($no_passback) {
                   1442:                                         &Apache::lonnet::log($udom,$uname,$uhome,$no_passback." score: $score; total: $total; possible: $possible");
                   1443:                                         my $ltigrade = {
                   1444:                                             'ltinum'   => $ltinum,
                   1445:                                             'lti'      => $lti_in_use,
                   1446:                                             'crsdef'   => $crsdef,
                   1447:                                             'cid'      => $cdom.'_'.$cnum,
                   1448:                                             'uname'    => $uname,
                   1449:                                             'udom'     => $udom,
                   1450:                                             'uhome'    => $uhome,
                   1451:                                             'pbid'     => $id,
                   1452:                                             'pburl'    => $url,
                   1453:                                             'pbtype'   => $type,
                   1454:                                             'pbscope'  => $pbscope,
                   1455:                                             'pbmap'    => $pbmap,
                   1456:                                             'pbsymb'   => $pbsymb,
                   1457:                                             'format'   => $scoretype,
                   1458:                                             'scope'    => $scope,
                   1459:                                             'clientip' => $clientip,
                   1460:                                             'linkprot' => $linkprotector,
                   1461:                                             'total'    => $total,
                   1462:                                             'possible' => $possible,
                   1463:                                             'score'    => $score,
                   1464:                                         };
                   1465:                                         &Apache::lonnet::put('linkprot_passback_pending',$ltigrade,$cdom,$cnum);
                   1466:                                     }
                   1467:                                 } else {
                   1468:                                     if (($id ne '') && ($url ne '')) {
                   1469:                                         $zeroposs{$student} = 1;
                   1470:                                     } else {
                   1471:                                         $nopbinfo{$student} = 1;
                   1472:                                     }
                   1473:                                 }
                   1474:                             }
                   1475:                             &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
                   1476:                             if ($ctr%2 ==1) {
                   1477:                                 $outcome .= &Apache::loncommon::end_data_table_row();
                   1478:                             }
                   1479:                             $outcome .= &Apache::loncommon::end_data_table();
                   1480:                             if ($ctr) {
                   1481:                                 $request->print('<p><br />'.&mt('Scores sent to launcher CMS').'</p>'.
                   1482:                                                 '<p>'.$outcome.'</p>');
                   1483:                             } else {
                   1484:                                 $request->print('<p>'.&mt('No scores sent to launcher CMS').'</p>');
                   1485:                             }
                   1486:                             if (keys(%tosend)) {
                   1487:                                 $request->print('<p>'.&mt('No scores sent for following'));
                   1488:                                 my ($zeros,$nopbcreds,$noconfirm,$noscore);
                   1489:                                 foreach my $student (sort
                   1490:                                 {
                   1491:                                      if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1492:                                          return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1493:                                      }
                   1494:                                      return $a cmp $b;
                   1495:                                 } (keys(%$fullname))) {
                   1496:                                     next unless ($tosend{$student});
                   1497:                                     my ($uname,$udom) = split(/:/,$student);
                   1498:                                     my $line = '<li>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).'</li>'."\n";
                   1499:                                     if ($zeroposs{$student}) {
                   1500:                                         $zeros .= $line;
                   1501:                                     } elsif ($nopbinfo{$student}) {
                   1502:                                         $nopbcreds .= $line;
                   1503:                                     } elsif ($remotenotok{$student}) {
                   1504:                                         $noconfirm .= $line;
                   1505:                                     } elsif ($scorenotok{$student}) {
                   1506:                                         $noscore .= $line;
                   1507:                                     }
                   1508:                                 }
                   1509:                                 if ($zeros) {
                   1510:                                     $request->print('<br />'.&mt('Total points possible was 0').':'.
                   1511:                                                     '<ul>'.$zeros.'</ul><br />');
                   1512:                                 }
                   1513:                                 if ($nopbcreds) {
                   1514:                                     $request->print('<br />'.&mt('Missing unique identifier and/or passback location').':'.
                   1515:                                                     '<ul>'.$nopbcreds.'</ul><br />');
                   1516:                                 }
                   1517:                                 if ($noconfirm) {
                   1518:                                     $request->print('<br />'.&mt('Score receipt not confirmed by receiving CMS').':'.
                   1519:                                                     '<ul>'.$noconfirm.'</ul><br />');
                   1520:                                 }
                   1521:                                 if ($noscore) {
                   1522:                                     $request->print('<br />'.&mt('Score computation or transmission failed').':'.
                   1523:                                                     '<ul>'.$noscore.'</ul><br />');
                   1524:                                 }
                   1525:                                 $request->print('</p>');
                   1526:                             }
                   1527:                         } else {
                   1528:                             $error = &mt('Settings for deep-link launch target unavailable, so no scores were sent');
                   1529:                         }
                   1530:                     } else {
                   1531:                         $error = &mt('No available students for whom scores can be sent.');
                   1532:                     }
                   1533:                 } else {
                   1534:                     $error = &mt('Classlist could not be retrieved so no scores were sent.');
                   1535:                 }
                   1536:             } else {
                   1537:                 $error = &mt('No students selected to receive scores so none were sent.');
                   1538:             }
                   1539:         } else {
                   1540:             if ($env{'form.passback'}) {
                   1541:                 $error = &mt('Deep-link launch target was invalid so no scores were sent.');
                   1542:             } else {
                   1543:                 $error = &mt('Deep-link launch target was missing so no scores were sent.');
                   1544:             }
                   1545:         }
                   1546:     } else {
                   1547:         $error = &mt('You do not have permission to manage grades, so no scores were sent');
                   1548:     }
                   1549:     if ($error) {
                   1550:         $request->print('<p class="LC_info">'.$error.'</p>');
                   1551:     }
                   1552:     return;
                   1553: }
                   1554: 
                   1555: sub get_passback_launcher {
                   1556:     my ($cdom,$cnum,$chosen) = @_;
                   1557:     my ($linkuri,$linkprotector,$scope) = split("\0",$chosen);
                   1558:     my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
                   1559:     my ($appname,$setter);
                   1560:     if ($ltitype eq 'c') {
                   1561:         my %lti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                   1562:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1563:             $appname = $lti{$ltinum}{'name'};
                   1564:             if ($appname) {
                   1565:                 $setter = ' (defined in course)';
                   1566:             }
                   1567:         }
                   1568:     } elsif ($ltitype eq 'd') {
                   1569:         my %lti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                   1570:         if (ref($lti{$ltinum}) eq 'HASH') {
                   1571:             $appname = $lti{$ltinum}{'name'};
                   1572:             if ($appname) {
                   1573:                 $setter = ' (defined in domain)';
                   1574:             }
                   1575:         }
                   1576:     }
                   1577:     if ($linkuri =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   1578:         my $key = $1;
                   1579:         my $tinyurl;
                   1580:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   1581:         if (defined($cached)) {
                   1582:             $tinyurl = $result;
                   1583:         } else {
                   1584:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   1585:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   1586:             if ($currtiny{$key} ne '') {
                   1587:                 $tinyurl = $currtiny{$key};
                   1588:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   1589:             }
                   1590:         }
                   1591:         if ($tinyurl) {
                   1592:             my ($crsnum,$launchsymb) = split(/\&/,$tinyurl);
                   1593:             if ($crsnum eq $cnum) {
                   1594:                 my %passback = &Apache::lonnet::get('nohist_linkprot_passback',[$launchsymb],$cdom,$cnum);
                   1595:                 if (ref($passback{$launchsymb}) eq 'HASH') {
                   1596:                     if (exists($passback{$launchsymb}{$chosen})) {
                   1597:                         return ($launchsymb,$appname,$setter)
                   1598:                     }
                   1599:                 }
                   1600:             }
                   1601:         }
                   1602:     }
                   1603:     return ();
                   1604: }
                   1605: 
                   1606: sub sections_and_groups {
                   1607:     my (@sections,@groups,$group_display);
                   1608:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   1609:     if (grep(/^all$/,@groups)) {
                   1610:          @groups = ('all');
                   1611:          $group_display = 'all';
                   1612:     } elsif (grep(/^none$/,@groups)) {
                   1613:          @groups = ('none');
                   1614:          $group_display = 'none';
                   1615:     } elsif (@groups > 0) {
                   1616:          $group_display = join(', ',@groups);
                   1617:     }
                   1618:     if ($env{'request.course.sec'} ne '') {
                   1619:         @sections = ($env{'request.course.sec'});
                   1620:     } else {
                   1621:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1622:     }
                   1623:     my $disabled = ' disabled="disabled"';
                   1624:     if ($perm{'mgr'}) {
                   1625:         if (grep(/^all$/,@sections)) {
                   1626:             undef($disabled);
                   1627:         } else {
                   1628:             foreach my $sec (@sections) {
                   1629:                 if (&canmodify($sec)) {
                   1630:                     undef($disabled);
                   1631:                     last;
                   1632:                 }
                   1633:             }
                   1634:         }
                   1635:     }
                   1636:     if (grep(/^all$/,@sections)) {
                   1637:         @sections = ('all');
                   1638:     }
                   1639:     return(\@sections,\@groups,$group_display,$disabled);
                   1640: }
                   1641: 
                   1642: sub launcher_info_box {
                   1643:     my ($launcher,$appname,$setter,$linkuri,$scope) = @_;
                   1644:     my $shownscope;
                   1645:     if ($scope eq 'res') {
                   1646:         $shownscope = &mt('Resource');
                   1647:     } elsif ($scope eq 'map') {
                   1648:         $shownscope = &mt('Folder');
                   1649:     }  elsif ($scope eq 'rec') {
                   1650:         $shownscope = &mt('Folder + sub-folders');
                   1651:     }
                   1652:     return '<p>'.
                   1653:            &Apache::lonhtmlcommon::start_pick_box().
                   1654:            &Apache::lonhtmlcommon::row_title(&mt('Launch Item Title')).
1.797   ! raeburn  1655:            &Apache::lonnet::gettitle($launcher).
1.796     raeburn  1656:            &Apache::lonhtmlcommon::row_closure().
                   1657:            &Apache::lonhtmlcommon::row_title(&mt('Deep-link')).
                   1658:            $linkuri.
                   1659:            &Apache::lonhtmlcommon::row_closure().
                   1660:            &Apache::lonhtmlcommon::row_title(&mt('Launcher')).
                   1661:            $appname.' '.$setter.
                   1662:            &Apache::lonhtmlcommon::row_closure().
                   1663:            &Apache::lonhtmlcommon::row_title(&mt('Score Type')).
                   1664:            $shownscope.      
                   1665:            &Apache::lonhtmlcommon::row_closure(1).
                   1666:            &Apache::lonhtmlcommon::end_pick_box().'</p>'."\n";
                   1667: }
                   1668: 
1.44      ng       1669: #--- This is called by a number of programs.
                   1670: #--- Called from the Grading Menu - View/Grade an individual student
                   1671: #--- Also called directly when one clicks on the subm button 
                   1672: #    on the problem page.
1.30      ng       1673: sub listStudents {
1.773     raeburn  1674:     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1675: 
1.747     raeburn  1676:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1677:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1678:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1679:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1680:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www      1681:     unless ($submitonly) {
1.766     raeburn  1682:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www      1683:     }
1.49      albertel 1684: 
1.632     www      1685:     my $result='';
1.623     www      1686:     my $res_error;
1.773     raeburn  1687:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   1688: 
                   1689:     my $table;
                   1690:     if (ref($partlist) eq 'ARRAY') {
                   1691:         if (scalar(@$partlist) > 1 ) {
                   1692:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1693:         } elsif ($divforres) {
                   1694:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1695:         } else {
                   1696:             $table = '<br clear="all" />';
                   1697:         }
                   1698:     }
1.49      albertel 1699: 
1.796     raeburn  1700:     $request->print(&checkselect_js());
1.597     wenzelju 1701:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1702: 
                   1703:     function reLoadList(formname) {
1.112     ng       1704: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1705: 	formname.command.value = 'submission';
                   1706: 	formname.submit();
                   1707:     }
1.45      ng       1708: LISTJAVASCRIPT
                   1709: 
1.118     ng       1710:     &commonJSfunctions($request);
1.41      ng       1711:     $request->print($result);
1.39      ng       1712: 
1.154     albertel 1713:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.773     raeburn  1714: 	"\n".$table;
                   1715: 
1.561     bisitz   1716:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn  1717:     unless ($is_tool) {
                   1718:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1719:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1720:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1721:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1722:                       .&Apache::lonhtmlcommon::row_closure();
                   1723:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1724:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1725:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1726:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1727:                       .&Apache::lonhtmlcommon::row_closure();
                   1728:     }
1.485     albertel 1729: 
1.442     banghart 1730:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1731:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1732:     $env{'form.Status'} = $saveStatus;
1.745     raeburn  1733:     my %optiontext;
                   1734:     if ($is_tool) {
                   1735:         %optiontext = &Apache::lonlocal::texthash (
                   1736:                           lastonly => 'last transaction',
                   1737:                           last     => 'last transaction with details',
                   1738:                           datesub  => 'all transactions',
                   1739:                           all      => 'all transactions with details',
                   1740:                       );
                   1741:     } else {
                   1742:         %optiontext = &Apache::lonlocal::texthash (
                   1743:                           lastonly => 'last submission',
                   1744:                           last     => 'last submission with details',
                   1745:                           datesub  => 'all submissions',
                   1746:                           all      => 'all submissions with details',
                   1747:                       );
                   1748:     }
1.773     raeburn  1749:     my $submission_options =
1.592     bisitz   1750:         '<span class="LC_nobreak">'.
1.624     www      1751:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  1752:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1753:         '<span class="LC_nobreak">'.
                   1754:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  1755:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1756:         '<span class="LC_nobreak">'.
1.628     www      1757:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  1758:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1759:         '<span class="LC_nobreak">'.
                   1760:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  1761:         $optiontext{'all'}.'</label></span>';
                   1762:     my $viewtitle;
                   1763:     if ($is_tool) {
                   1764:         $viewtitle = &mt('View Transactions');
                   1765:     } else {
                   1766:         $viewtitle = &mt('View Submissions');
                   1767:     }
1.773     raeburn  1768:     my ($compmsg,$nocompmsg);
                   1769:     $nocompmsg = ' checked="checked"';
                   1770:     if ($numessay) {
                   1771:         $compmsg = $nocompmsg;
                   1772:         $nocompmsg = '';
                   1773:     }
1.745     raeburn  1774:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.780     raeburn  1775:                   .$submission_options;
                   1776: # Check if any gradable
                   1777:     my $showmore;
                   1778:     if ($perm{'mgr'}) {
                   1779:         my @sections;
                   1780:         if ($env{'request.course.sec'} ne '') {
                   1781:             @sections = ($env{'request.course.sec'});
1.783     raeburn  1782:         } elsif ($env{'form.section'} eq '') {
                   1783:             @sections = ('all');
1.780     raeburn  1784:         } else {
                   1785:             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1786:         }
                   1787:         if (grep(/^all$/,@sections)) {
                   1788:             $showmore = 1;
                   1789:         } else {
                   1790:             foreach my $sec (@sections) {
                   1791:                 if (&canmodify($sec)) {
                   1792:                     $showmore = 1;
                   1793:                     last;
                   1794:                 }
                   1795:             }
                   1796:         }
                   1797:     }
                   1798: 
                   1799:     if ($showmore) {
                   1800:         $gradeTable .=
                   1801:                    &Apache::lonhtmlcommon::row_closure()
1.773     raeburn  1802:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   1803:                   .'<span class="LC_nobreak">'
                   1804:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   1805:                   .&mt('No').('&nbsp;'x2).'</label>'
                   1806:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   1807:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1808:                   .&Apache::lonhtmlcommon::row_closure();
                   1809: 
1.780     raeburn  1810:         $gradeTable .= 
                   1811:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   1812:                   .'<select name="increment">'
                   1813:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1814:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1815:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1816:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773     raeburn  1817:                   .'</select>';
1.780     raeburn  1818:     }
1.485     albertel 1819:     $gradeTable .= 
1.432     banghart 1820:         &build_section_inputs().
1.45      ng       1821: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1822: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1823: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      1824:     if (exists($env{'form.Status'})) {
1.784     raeburn  1825: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng       1826:     } else {
1.773     raeburn  1827:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1828:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1829:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773     raeburn  1830:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1831:     }
1.773     raeburn  1832:     if ($numessay) {
                   1833:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1834:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1835:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  1836:     }
1.773     raeburn  1837:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
                   1838:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  1839:     my $regrademsg;
                   1840:     if ($is_tool) {
                   1841:         $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.");
                   1842:     } else {
                   1843:         $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.");
                   1844:     }
1.561     bisitz   1845:     $gradeTable .= '<p>'
1.745     raeburn  1846:                   .$regrademsg."\n"
1.561     bisitz   1847:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1848:                   .'</p>';
1.249     albertel 1849: 
                   1850: # checkall buttons
                   1851:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1852:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1853:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1854:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1855:     $gradeTable.=&check_buttons();
1.450     banghart 1856:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1857:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1858: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1859:     my $loop = 0;
                   1860:     while ($loop < 2) {
1.485     albertel 1861: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1862: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1863: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1864: 	    foreach my $part (sort(@$partlist)) {
                   1865: 		my $display_part=
                   1866: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1867: 		$gradeTable.=
                   1868: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1869: 	    }
1.301     albertel 1870: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1871: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1872: 	}
                   1873: 	$loop++;
1.126     ng       1874: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1875:     }
1.474     albertel 1876:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1877: 
1.45      ng       1878:     my $ctr = 0;
1.294     albertel 1879:     foreach my $student (sort 
                   1880: 			 {
                   1881: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1882: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1883: 			     }
                   1884: 			     return $a cmp $b;
                   1885: 			 }
                   1886: 			 (keys(%$fullname))) {
1.41      ng       1887: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1888: 
1.110     ng       1889: 	my %status = ();
1.301     albertel 1890: 
                   1891: 	if ($submitonly eq 'queued') {
                   1892: 	    my %queue_status = 
                   1893: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1894: 							$udom,$uname);
                   1895: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1896: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1897: 	}
                   1898: 
1.618     www      1899: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1900: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1901: 	    my $submitted = 0;
1.164     albertel 1902: 	    my $graded = 0;
1.248     albertel 1903: 	    my $incorrect = 0;
1.110     ng       1904: 	    foreach (keys(%status)) {
1.145     albertel 1905: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1906: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1907: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1908: 		
1.110     ng       1909: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1910: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1911: 		    $submitted = 0;
1.150     albertel 1912: 		    my ($part)=split(/\./,$partid);
1.110     ng       1913: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1914: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1915: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1916: 		}
1.41      ng       1917: 	    }
1.248     albertel 1918: 	    
1.156     albertel 1919: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1920: 				     $submitonly eq 'incorrect' ||
                   1921: 				     $submitonly eq 'graded'));
1.248     albertel 1922: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1923: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1924: 	}
1.34      ng       1925: 
1.45      ng       1926: 	$ctr++;
1.249     albertel 1927: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1928:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1929: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1930: 	    if ($ctr%2 ==1) {
                   1931: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1932: 	    }
1.126     ng       1933: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1934:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1935:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1936: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1937: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1938: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1939: 
1.618     www      1940: 	    if ($submitonly ne 'all') {
1.524     raeburn  1941: 		foreach (sort(keys(%status))) {
1.485     albertel 1942: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1943: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1944: 		}
1.41      ng       1945: 	    }
1.126     ng       1946: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1947: 	    if ($ctr%2 ==0) {
                   1948: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1949: 	    }
1.41      ng       1950: 	}
                   1951:     }
1.110     ng       1952:     if ($ctr%2 ==1) {
1.126     ng       1953: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1954: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1955: 		foreach (@$partlist) {
                   1956: 		    $gradeTable.='<td>&nbsp;</td>';
                   1957: 		}
1.301     albertel 1958: 	    } elsif ($submitonly eq 'queued') {
                   1959: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1960: 	    }
1.474     albertel 1961: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1962:     }
                   1963: 
1.474     albertel 1964:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1965:         '<input type="button" '.
                   1966:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1967:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1968:     if ($ctr == 0) {
1.96      albertel 1969: 	my $num_students=(scalar(keys(%$fullname)));
                   1970: 	if ($num_students eq 0) {
1.485     albertel 1971: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1972: 	} else {
1.171     albertel 1973: 	    my $submissions='submissions';
                   1974: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1975: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1976: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1977: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1978: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1979: 		    $num_students).
                   1980: 		'</span><br />';
1.96      albertel 1981: 	}
1.46      ng       1982:     } elsif ($ctr == 1) {
1.474     albertel 1983: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1984:     }
                   1985:     $request->print($gradeTable);
1.44      ng       1986:     return '';
1.10      ng       1987: }
                   1988: 
1.796     raeburn  1989: #---- Called from the listStudents and the names_for_passback routines.
                   1990: 
                   1991: sub checkselect_js {
                   1992:     my ($formname) = @_;
                   1993:     if ($formname eq '') {
                   1994:         $formname = 'gradesub';
                   1995:     }
                   1996:     my %js_lt;
                   1997:     if ($formname eq 'passbackusers') {
                   1998:         %js_lt = &Apache::lonlocal::texthash (
                   1999:                      'multiple' => 'Please select a student or group of students before pushing the Save Scores button.',
                   2000:                      'single'   => 'Please select the student before pushing the Save Scores button.',
                   2001:                  );
                   2002:     } else {
                   2003:         %js_lt = &Apache::lonlocal::texthash (
                   2004:                      'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   2005:                      'single'   => 'Please select the student before clicking on the Next button.',
                   2006:                  );
                   2007:     }
                   2008:     &js_escape(\%js_lt);
                   2009:     return &Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT);
                   2010: 
                   2011:     function checkSelect(checkBox) {
                   2012:         var ctr=0;
                   2013:         var sense="";
                   2014:         var len = checkBox.length;
                   2015:         if (len == undefined) len = 1;
                   2016:         if (len > 1) {
                   2017:             for (var i=0; i<len; i++) {
                   2018:                 if (checkBox[i].checked) {
                   2019:                     ctr++;
                   2020:                 }
                   2021:             }
                   2022:             sense = '$js_lt{'multiple'}';
                   2023:         } else {
                   2024:             if (checkBox.checked) {
                   2025:                 ctr = 1;
                   2026:             }
                   2027:             sense = '$js_lt{'single'}';
                   2028:         }
                   2029:         if (ctr == 0) {
                   2030:             alert(sense);
                   2031:             return false;
                   2032:         }
                   2033:         document.$formname.submit();
                   2034:     }
                   2035: LISTJAVASCRIPT
                   2036: 
                   2037: }
1.249     albertel 2038: 
                   2039: sub check_script {
1.766     raeburn  2040:     my ($form,$type) = @_;
                   2041:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 2042:     function checkall() {
                   2043:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2044:             ele = document.forms.'.$form.'.elements[i];
                   2045:             if (ele.name == "'.$type.'") {
                   2046:             document.forms.'.$form.'.elements[i].checked=true;
                   2047:                                        }
                   2048:         }
                   2049:     }
                   2050: 
                   2051:     function checksec() {
                   2052:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2053:             ele = document.forms.'.$form.'.elements[i];
                   2054:            string = document.forms.'.$form.'.chksec.value;
                   2055:            if
                   2056:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   2057:               document.forms.'.$form.'.elements[i].checked=true;
                   2058:             }
                   2059:         }
                   2060:     }
                   2061: 
                   2062: 
                   2063:     function uncheckall() {
                   2064:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   2065:             ele = document.forms.'.$form.'.elements[i];
                   2066:             if (ele.name == "'.$type.'") {
                   2067:             document.forms.'.$form.'.elements[i].checked=false;
                   2068:                                        }
                   2069:         }
                   2070:     }
                   2071: 
1.597     wenzelju 2072: '."\n");
1.249     albertel 2073:     return $chkallscript;
                   2074: }
                   2075: 
                   2076: sub check_buttons {
1.485     albertel 2077:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   2078:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   2079:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 2080:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   2081:     return $buttons;
                   2082: }
                   2083: 
1.44      ng       2084: #     Displays the submissions for one student or a group of students
1.34      ng       2085: sub processGroup {
1.766     raeburn  2086:     my ($request,$symb) = @_;
1.41      ng       2087:     my $ctr        = 0;
1.155     albertel 2088:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       2089:     my $total      = scalar(@stuchecked)-1;
1.45      ng       2090: 
1.396     banghart 2091:     foreach my $student (@stuchecked) {
                   2092: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 2093: 	$env{'form.student'}        = $uname;
                   2094: 	$env{'form.userdom'}        = $udom;
                   2095: 	$env{'form.fullname'}       = $fullname;
1.619     www      2096: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2097: 	$ctr++;
                   2098:     }
                   2099:     return '';
1.35      ng       2100: }
1.34      ng       2101: 
1.44      ng       2102: #------------------------------------------------------------------------------------
                   2103: #
                   2104: #-------------------------- Next few routines handles grading by student, essentially
                   2105: #                           handles essay response type problem/part
                   2106: #
                   2107: #--- Javascript to handle the submission page functionality ---
                   2108: sub sub_page_js {
                   2109:     my $request = shift;
1.736     damieng  2110:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   2111:     &js_escape(\$alertmsg);
1.597     wenzelju 2112:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       2113:     function updateRadio(formname,id,weight) {
1.125     ng       2114: 	var gradeBox = formname["GD_BOX"+id];
                   2115: 	var radioButton = formname["RADVAL"+id];
                   2116: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       2117: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       2118: 	gradeBox.value = pts;
                   2119: 	var resetbox = false;
                   2120: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  2121: 	    alert("$alertmsg"+pts);
1.71      ng       2122: 	    for (var i=0; i<radioButton.length; i++) {
                   2123: 		if (radioButton[i].checked) {
                   2124: 		    gradeBox.value = i;
                   2125: 		    resetbox = true;
                   2126: 		}
                   2127: 	    }
                   2128: 	    if (!resetbox) {
                   2129: 		formtextbox.value = "";
                   2130: 	    }
                   2131: 	    return;
1.44      ng       2132: 	}
1.71      ng       2133: 
                   2134: 	if (pts > weight) {
                   2135: 	    var resp = confirm("You entered a value ("+pts+
                   2136: 			       ") greater than the weight for the part. Accept?");
                   2137: 	    if (resp == false) {
1.125     ng       2138: 		gradeBox.value = oldpts;
1.71      ng       2139: 		return;
                   2140: 	    }
1.44      ng       2141: 	}
1.13      albertel 2142: 
1.71      ng       2143: 	for (var i=0; i<radioButton.length; i++) {
                   2144: 	    radioButton[i].checked=false;
                   2145: 	    if (pts == i && pts != "") {
                   2146: 		radioButton[i].checked=true;
                   2147: 	    }
                   2148: 	}
                   2149: 	updateSelect(formname,id);
1.125     ng       2150: 	formname["stores"+id].value = "0";
1.41      ng       2151:     }
1.5       albertel 2152: 
1.72      ng       2153:     function writeBox(formname,id,pts) {
1.125     ng       2154: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2155: 	if (checkSolved(formname,id) == 'update') {
                   2156: 	    gradeBox.value = pts;
                   2157: 	} else {
1.125     ng       2158: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       2159: 	    gradeBox.value = oldpts;
1.125     ng       2160: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       2161: 	    for (var i=0; i<radioButton.length; i++) {
                   2162: 		radioButton[i].checked=false;
1.72      ng       2163: 		if (i == oldpts) {
1.71      ng       2164: 		    radioButton[i].checked=true;
                   2165: 		}
                   2166: 	    }
1.41      ng       2167: 	}
1.125     ng       2168: 	formname["stores"+id].value = "0";
1.71      ng       2169: 	updateSelect(formname,id);
                   2170: 	return;
1.41      ng       2171:     }
1.44      ng       2172: 
1.71      ng       2173:     function clearRadBox(formname,id) {
                   2174: 	if (checkSolved(formname,id) == 'noupdate') {
                   2175: 	    updateSelect(formname,id);
                   2176: 	    return;
                   2177: 	}
1.125     ng       2178: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       2179: 	for (var i=0; i<gradeSelect.length; i++) {
                   2180: 	    if (gradeSelect[i].selected) {
                   2181: 		var selectx=i;
                   2182: 	    }
                   2183: 	}
1.125     ng       2184: 	var stores = formname["stores"+id];
1.71      ng       2185: 	if (selectx == stores.value) { return };
1.125     ng       2186: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       2187: 	gradeBox.value = "";
1.125     ng       2188: 	var radioButton = formname["RADVAL"+id];
1.71      ng       2189: 	for (var i=0; i<radioButton.length; i++) {
                   2190: 	    radioButton[i].checked=false;
                   2191: 	}
                   2192: 	stores.value = selectx;
                   2193:     }
1.5       albertel 2194: 
1.71      ng       2195:     function checkSolved(formname,id) {
1.125     ng       2196: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       2197: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   2198: 	    if (!reply) {return "noupdate";}
1.120     ng       2199: 	    formname.overRideScore.value = 'yes';
1.41      ng       2200: 	}
1.71      ng       2201: 	return "update";
1.13      albertel 2202:     }
1.71      ng       2203: 
                   2204:     function updateSelect(formname,id) {
1.125     ng       2205: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       2206: 	return;
1.41      ng       2207:     }
1.33      ng       2208: 
1.121     ng       2209: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       2210:     function checksubmit(formname,val,total,parttot) {
1.121     ng       2211: 	formname.gradeOpt.value = val;
1.71      ng       2212: 	if (val == "Save & Next") {
                   2213: 	    for (i=0;i<=total;i++) {
                   2214: 		for (j=0;j<parttot;j++) {
1.125     ng       2215: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       2216: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2217: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       2218: 			if (points == "") {
1.125     ng       2219: 			    var name = formname["name"+i].value;
1.129     ng       2220: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   2221: 			    var resp = confirm("You did not assign a score for "+studentID+
                   2222: 					       ", part "+partid+". Continue?");
1.71      ng       2223: 			    if (resp == false) {
1.125     ng       2224: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       2225: 				return false;
                   2226: 			    }
                   2227: 			}
                   2228: 		    }
                   2229: 		}
                   2230: 	    }
                   2231: 	}
1.120     ng       2232: 	formname.submit();
                   2233:     }
                   2234: 
1.71      ng       2235: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   2236:     function checkSubmitPage(formname,total) {
                   2237: 	noscore = new Array(100);
                   2238: 	var ptr = 0;
                   2239: 	for (i=1;i<total;i++) {
1.125     ng       2240: 	    var partid = formname["q_"+i].value;
1.127     ng       2241: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       2242: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   2243: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       2244: 		if (points == "" && status != "correct_by_student") {
                   2245: 		    noscore[ptr] = i;
                   2246: 		    ptr++;
                   2247: 		}
                   2248: 	    }
                   2249: 	}
                   2250: 	if (ptr != 0) {
                   2251: 	    var sense = ptr == 1 ? ": " : "s: ";
                   2252: 	    var prolist = "";
                   2253: 	    if (ptr == 1) {
                   2254: 		prolist = noscore[0];
                   2255: 	    } else {
                   2256: 		var i = 0;
                   2257: 		while (i < ptr-1) {
                   2258: 		    prolist += noscore[i]+", ";
                   2259: 		    i++;
                   2260: 		}
                   2261: 		prolist += "and "+noscore[i];
                   2262: 	    }
                   2263: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   2264: 	    if (resp == false) {
                   2265: 		return false;
                   2266: 	    }
                   2267: 	}
1.45      ng       2268: 
1.71      ng       2269: 	formname.submit();
                   2270:     }
                   2271: SUBJAVASCRIPT
                   2272: }
1.45      ng       2273: 
1.773     raeburn  2274: #--- javascript for grading message center
                   2275: sub sub_grademessage_js {
1.71      ng       2276:     my $request = shift;
1.80      ng       2277:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       2278:     &commonJSfunctions($request);
1.350     albertel 2279: 
1.629     www      2280:     my $inner_js_msg_central= (<<INNERJS);
                   2281: <script type="text/javascript">
1.350     albertel 2282:     function checkInput() {
                   2283:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   2284:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   2285:       var usrctr = document.msgcenter.usrctr.value;
                   2286:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   2287:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   2288: 
                   2289:       var msgchk = "";
                   2290:       if (document.msgcenter.subchk.checked) {
                   2291:          msgchk = "msgsub,";
                   2292:       }
                   2293:       var includemsg = 0;
                   2294:       for (var i=1; i<=nmsg; i++) {
                   2295:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   2296:           var frmmsg = document.msgcenter["msg"+i];
                   2297:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   2298:           var showflg = opener.document.SCORE["shownOnce"+i];
                   2299:           showflg.value = "1";
                   2300:           var chkbox = document.msgcenter["msgn"+i];
                   2301:           if (chkbox.checked) {
                   2302:              msgchk += "savemsg"+i+",";
                   2303:              includemsg = 1;
                   2304:           }
                   2305:       }
                   2306:       if (document.msgcenter.newmsgchk.checked) {
                   2307:          msgchk += "newmsg"+usrctr;
                   2308:          includemsg = 1;
                   2309:       }
                   2310:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   2311:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   2312:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   2313:       includemsg.value = msgchk;
                   2314: 
                   2315:       self.close()
                   2316: 
                   2317:     }
1.629     www      2318: </script>
1.350     albertel 2319: INNERJS
                   2320: 
1.773     raeburn  2321:     my $start_page_msg_central =
1.351     albertel 2322:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   2323: 				       {'js_ready'  => 1,
                   2324: 					'only_body' => 1,
                   2325: 					'bgcolor'   =>'#FFFFFF',});
1.773     raeburn  2326:     my $end_page_msg_central =
1.350     albertel 2327: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   2328: 
1.219     www      2329:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 2330:     $docopen=~s/^document\.//;
1.773     raeburn  2331: 
1.736     damieng  2332:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  2333:                 comp => 'Compose Message for: ',
                   2334:                 incl => 'Include',
1.656     raeburn  2335:                 type => 'Type',
1.652     raeburn  2336:                 subj => 'Subject',
                   2337:                 mesa => 'Message',
                   2338:                 new  => 'New',
                   2339:                 save => 'Save',
                   2340:                 canc => 'Cancel',
                   2341:              );
1.736     damieng  2342:     &html_escape(\%html_js_lt);
                   2343:     &js_escape(\%html_js_lt);
1.597     wenzelju 2344:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       2345: 
1.44      ng       2346: //===================== Script to view submitted by ==================
                   2347:   function viewSubmitter(submitter) {
                   2348:     document.SCORE.refresh.value = "on";
                   2349:     document.SCORE.NCT.value = "1";
                   2350:     document.SCORE.unamedom0.value = submitter;
                   2351:     document.SCORE.submit();
                   2352:     return;
                   2353:   }
                   2354: 
                   2355: //====================== Script for composing message ==============
1.80      ng       2356:    // preload images
                   2357:    img1 = new Image();
                   2358:    img1.src = "$iconpath/mailbkgrd.gif";
                   2359:    img2 = new Image();
                   2360:    img2.src = "$iconpath/mailto.gif";
                   2361: 
1.44      ng       2362:   function msgCenter(msgform,usrctr,fullname) {
                   2363:     var Nmsg  = msgform.savemsgN.value;
                   2364:     savedMsgHeader(Nmsg,usrctr,fullname);
                   2365:     var subject = msgform.msgsub.value;
1.127     ng       2366:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       2367:     re = /msgsub/;
                   2368:     var shwsel = "";
                   2369:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       2370:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   2371:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       2372:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       2373: 	var testmsg = "savemsg"+i+",";
                   2374: 	re = new RegExp(testmsg,"g");
1.44      ng       2375: 	shwsel = "";
                   2376: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       2377: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       2378: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       2379: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   2380: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       2381:     }
1.125     ng       2382:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       2383:     shwsel = "";
                   2384:     re = /newmsg/;
                   2385:     if (re.test(msgchk)) { shwsel = "checked" }
                   2386:     newMsg(newmsg,shwsel);
                   2387:     msgTail(); 
                   2388:     return;
                   2389:   }
                   2390: 
1.123     ng       2391:   function checkEntities(strx) {
                   2392:     if (strx.length == 0) return strx;
                   2393:     var orgStr = ["&", "<", ">", '"']; 
                   2394:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   2395:     var counter = 0;
                   2396:     while (counter < 4) {
                   2397: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   2398: 	counter++;
                   2399:     }
                   2400:     return strx;
                   2401:   }
                   2402: 
                   2403:   function strReplace(strx, orgStr, newStr) {
                   2404:     return strx.split(orgStr).join(newStr);
                   2405:   }
                   2406: 
1.44      ng       2407:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       2408:     var height = 70*Nmsg+250;
1.44      ng       2409:     if (height > 600) {
                   2410: 	height = 600;
                   2411:     }
1.118     ng       2412:     var xpos = (screen.width-600)/2;
                   2413:     xpos = (xpos < 0) ? '0' : xpos;
                   2414:     var ypos = (screen.height-height)/2-30;
                   2415:     ypos = (ypos < 0) ? '0' : ypos;
                   2416: 
1.668     www      2417:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       2418:     pWin.focus();
                   2419:     pDoc = pWin.document;
1.219     www      2420:     pDoc.$docopen;
1.351     albertel 2421:     pDoc.write('$start_page_msg_central');
1.76      ng       2422: 
                   2423:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   2424:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  2425:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       2426: 
1.676     golterma 2427:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  2428:     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       2429: }
                   2430:     function displaySubject(msg,shwsel) {
1.76      ng       2431:     pDoc = pWin.document;
1.676     golterma 2432:     pDoc.write("<tr>");
                   2433:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2434:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 2435:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       2436: }
                   2437: 
1.72      ng       2438:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       2439:     pDoc = pWin.document;
1.676     golterma 2440:     pDoc.write("<tr>");
                   2441:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 2442:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   2443:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2444: }
                   2445: 
                   2446:   function newMsg(newmsg,shwsel) {
1.76      ng       2447:     pDoc = pWin.document;
1.676     golterma 2448:     pDoc.write("<tr>");
                   2449:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  2450:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 2451:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       2452: }
                   2453: 
                   2454:   function msgTail() {
1.76      ng       2455:     pDoc = pWin.document;
1.676     golterma 2456:     //pDoc.write("<\\/table>");
1.465     albertel 2457:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  2458:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   2459:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 2460:     pDoc.write("<\\/form>");
1.351     albertel 2461:     pDoc.write('$end_page_msg_central');
1.128     ng       2462:     pDoc.close();
1.44      ng       2463: }
                   2464: 
1.773     raeburn  2465: SUBJAVASCRIPT
                   2466: }
                   2467: 
                   2468: #--- javascript for essay type problem --
                   2469: sub sub_page_kw_js {
                   2470:     my $request = shift;
                   2471: 
                   2472:     unless ($env{'form.compmsg'}) {
                   2473:         &commonJSfunctions($request);
                   2474:     }
                   2475: 
                   2476:     my $inner_js_highlight_central= (<<INNERJS);
                   2477: <script type="text/javascript">
                   2478:     function updateChoice(flag) {
                   2479:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   2480:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   2481:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   2482:       opener.document.SCORE.refresh.value = "on";
                   2483:       if (opener.document.SCORE.keywords.value!=""){
                   2484:          opener.document.SCORE.submit();
                   2485:       }
                   2486:       self.close()
                   2487:     }
                   2488: </script>
                   2489: INNERJS
                   2490: 
                   2491:     my $start_page_highlight_central =
                   2492:         &Apache::loncommon::start_page('Highlight Central',
                   2493:                                        $inner_js_highlight_central,
                   2494:                                        {'js_ready'  => 1,
                   2495:                                         'only_body' => 1,
                   2496:                                         'bgcolor'   =>'#FFFFFF',});
                   2497:     my $end_page_highlight_central =
                   2498:         &Apache::loncommon::end_page({'js_ready' => 1});
                   2499: 
                   2500:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   2501:     $docopen=~s/^document\.//;
                   2502: 
                   2503:     my %js_lt = &Apache::lonlocal::texthash(
                   2504:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   2505:                 plse => 'Please select a word or group of words from document and then click this link.',
                   2506:                 adds => 'Add selection to keyword list? Edit if desired.',
                   2507:                 col1 => 'red',
                   2508:                 col2 => 'green',
                   2509:                 col3 => 'blue',
                   2510:                 siz1 => 'normal',
                   2511:                 siz2 => '+1',
                   2512:                 siz3 => '+2',
                   2513:                 sty1 => 'normal',
                   2514:                 sty2 => 'italic',
                   2515:                 sty3 => 'bold',
                   2516:              );
                   2517:     my %html_js_lt = &Apache::lonlocal::texthash(
                   2518:                 save => 'Save',
                   2519:                 canc => 'Cancel',
                   2520:                 kehi => 'Keyword Highlight Options',
                   2521:                 txtc => 'Text Color',
                   2522:                 font => 'Font Size',
                   2523:                 fnst => 'Font Style',
                   2524:              );
                   2525:     &js_escape(\%js_lt);
                   2526:     &html_escape(\%html_js_lt);
                   2527:     &js_escape(\%html_js_lt);
                   2528:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   2529: 
                   2530: //===================== Show list of keywords ====================
                   2531:   function keywords(formname) {
                   2532:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   2533:     if (nret==null) return;
                   2534:     formname.keywords.value = nret;
                   2535: 
                   2536:     if (formname.keywords.value != "") {
                   2537:         formname.refresh.value = "on";
                   2538:         formname.submit();
                   2539:     }
                   2540:     return;
                   2541:   }
                   2542: 
                   2543: //===================== Script to add keyword(s) ==================
                   2544:   function getSel() {
                   2545:     if (document.getSelection) txt = document.getSelection();
                   2546:     else if (document.selection) txt = document.selection.createRange().text;
                   2547:     else return;
                   2548:     if (typeof(txt) != 'string') {
                   2549:         txt = String(txt);
                   2550:     }
                   2551:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   2552:     if (cleantxt=="") {
                   2553:         alert("$js_lt{'plse'}");
                   2554:         return;
                   2555:     }
                   2556:     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   2557:     if (nret==null) return;
                   2558:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   2559:     if (document.SCORE.keywords.value != "") {
                   2560:         document.SCORE.refresh.value = "on";
                   2561:         document.SCORE.submit();
                   2562:     }
                   2563:     return;
                   2564:   }
                   2565: 
1.44      ng       2566: //====================== Script for keyword highlight options ==============
                   2567:   function kwhighlight() {
                   2568:     var kwclr    = document.SCORE.kwclr.value;
                   2569:     var kwsize   = document.SCORE.kwsize.value;
                   2570:     var kwstyle  = document.SCORE.kwstyle.value;
                   2571:     var redsel = "";
                   2572:     var grnsel = "";
                   2573:     var blusel = "";
1.736     damieng  2574:     var txtcol1 = "$js_lt{'col1'}";
                   2575:     var txtcol2 = "$js_lt{'col2'}";
                   2576:     var txtcol3 = "$js_lt{'col3'}";
                   2577:     var txtsiz1 = "$js_lt{'siz1'}";
                   2578:     var txtsiz2 = "$js_lt{'siz2'}";
                   2579:     var txtsiz3 = "$js_lt{'siz3'}";
                   2580:     var txtsty1 = "$js_lt{'sty1'}";
                   2581:     var txtsty2 = "$js_lt{'sty2'}";
                   2582:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   2583:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   2584:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   2585:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       2586:     var sznsel = "";
                   2587:     var sz1sel = "";
                   2588:     var sz2sel = "";
1.718     bisitz   2589:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   2590:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   2591:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       2592:     var synsel = "";
                   2593:     var syisel = "";
                   2594:     var sybsel = "";
1.718     bisitz   2595:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   2596:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   2597:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       2598:     highlightCentral();
1.718     bisitz   2599:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   2600:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   2601:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       2602:     highlightend();
                   2603:     return;
                   2604:   }
                   2605: 
                   2606:   function highlightCentral() {
1.76      ng       2607: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       2608:     var xpos = (screen.width-400)/2;
                   2609:     xpos = (xpos < 0) ? '0' : xpos;
                   2610:     var ypos = (screen.height-330)/2-30;
                   2611:     ypos = (ypos < 0) ? '0' : ypos;
                   2612: 
1.206     albertel 2613:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       2614:     hwdWin.focus();
                   2615:     var hDoc = hwdWin.document;
1.219     www      2616:     hDoc.$docopen;
1.351     albertel 2617:     hDoc.write('$start_page_highlight_central');
1.76      ng       2618:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  2619:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       2620: 
1.718     bisitz   2621:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  2622:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       2623:   }
                   2624: 
                   2625:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       2626:     var hDoc = hwdWin.document;
1.718     bisitz   2627:     hDoc.write("<tr>");
1.76      ng       2628:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2629:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       2630:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2631:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       2632:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   2633:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 2634:     hDoc.write("<\\/tr>");
1.44      ng       2635:   }
                   2636: 
                   2637:   function highlightend() { 
1.76      ng       2638:     var hDoc = hwdWin.document;
1.718     bisitz   2639:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  2640:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   2641:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 2642:     hDoc.write("<\\/form>");
1.351     albertel 2643:     hDoc.write('$end_page_highlight_central');
1.128     ng       2644:     hDoc.close();
1.44      ng       2645:   }
                   2646: 
                   2647: SUBJAVASCRIPT
                   2648: }
                   2649: 
1.349     albertel 2650: sub get_increment {
1.348     bowersj2 2651:     my $increment = $env{'form.increment'};
                   2652:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   2653:         $increment != .1) {
                   2654:         $increment = 1;
                   2655:     }
                   2656:     return $increment;
                   2657: }
                   2658: 
1.585     bisitz   2659: sub gradeBox_start {
                   2660:     return (
                   2661:         &Apache::loncommon::start_data_table()
                   2662:        .&Apache::loncommon::start_data_table_header_row()
                   2663:        .'<th>'.&mt('Part').'</th>'
                   2664:        .'<th>'.&mt('Points').'</th>'
                   2665:        .'<th>&nbsp;</th>'
                   2666:        .'<th>'.&mt('Assign Grade').'</th>'
                   2667:        .'<th>'.&mt('Weight').'</th>'
                   2668:        .'<th>'.&mt('Grade Status').'</th>'
                   2669:        .&Apache::loncommon::end_data_table_header_row()
                   2670:     );
                   2671: }
                   2672: 
                   2673: sub gradeBox_end {
                   2674:     return (
                   2675:         &Apache::loncommon::end_data_table()
                   2676:     );
                   2677: }
1.71      ng       2678: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   2679: sub gradeBox {
1.322     albertel 2680:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 2681:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2682: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2683:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2684:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2685:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2686:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2687:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2688: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   2689:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2690:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2691:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2692: 				       [$partid]);
                   2693:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2694:     if ($last_resets{$partid}) {
                   2695:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2696:     }
1.695     bisitz   2697:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2698:     my $ctr = 0;
1.348     bowersj2 2699:     my $thisweight = 0;
1.349     albertel 2700:     my $increment = &get_increment();
1.485     albertel 2701: 
                   2702:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2703:     while ($thisweight<=$wgt) {
1.532     bisitz   2704: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2705:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2706: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2707: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2708: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2709:         $thisweight += $increment;
1.71      ng       2710: 	$ctr++;
                   2711:     }
1.485     albertel 2712:     $radio.='</tr></table>';
                   2713: 
                   2714:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2715: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2716: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2717: 	$wgt.')" /></td>'."\n";
1.485     albertel 2718:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2719: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2720: 	' </td>'."\n";
                   2721:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2722: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2723:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2724: 	$line.='<option></option>'.
                   2725: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2726:     } else {
1.485     albertel 2727: 	$line.='<option selected="selected"></option>'.
                   2728: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2729:     }
1.485     albertel 2730:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2731: 
                   2732: 
                   2733:     $result .= 
1.695     bisitz   2734: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   2735:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   2736:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2737:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2738: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2739: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2740: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2741:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2742:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2743:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2744:         $aggtries.'" />'."\n";
1.582     raeburn  2745:     my $res_error;
                   2746:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   2747:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2748:     if ($res_error) {
                   2749:         return &navmap_errormsg();
                   2750:     }
1.318     banghart 2751:     return $result;
                   2752: }
1.322     albertel 2753: 
                   2754: sub handback_box {
1.623     www      2755:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773     raeburn  2756:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   2757:     return unless ($numessay);
1.323     banghart 2758:     my (@respids);
1.652     raeburn  2759:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2760:     foreach my $part_response_id (@part_response_id) {
                   2761:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2762:         if ($part eq $partid) {
1.375     albertel 2763:             push(@respids,$resp);
1.323     banghart 2764:         }
                   2765:     }
1.318     banghart 2766:     my $result;
1.323     banghart 2767:     foreach my $respid (@respids) {
1.322     albertel 2768: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2769: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2770: 	next if (!@$files);
1.654     raeburn  2771: 	my $file_counter = 0;
1.313     banghart 2772: 	foreach my $file (@$files) {
1.368     banghart 2773: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  2774:                 $file_counter++;
1.368     banghart 2775:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  2776:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 2777:     	        $file_disp = "$name.$ext";
                   2778:     	        $file = $file_path.$file_disp;
                   2779:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2780:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2781:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  2782:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2783: 	    }
1.322     albertel 2784: 	}
1.654     raeburn  2785:         if ($file_counter) {
                   2786:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2787:                        '<span class="LC_info">'.
                   2788:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2789:         }
1.313     banghart 2790:     }
1.318     banghart 2791:     return $result;    
1.71      ng       2792: }
1.44      ng       2793: 
1.58      albertel 2794: sub show_problem {
1.382     albertel 2795:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2796:     my $rendered;
1.382     albertel 2797:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2798:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2799:     if ($mode eq 'both' or $mode eq 'text') {
                   2800: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2801: 						       $env{'request.course.id'},
                   2802: 						       undef,\%form);
1.144     albertel 2803:     }
1.58      albertel 2804:     if ($removeform) {
                   2805: 	$rendered=~s|<form(.*?)>||g;
                   2806: 	$rendered=~s|</form>||g;
1.374     albertel 2807: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2808:     }
1.144     albertel 2809:     my $companswer;
                   2810:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2811: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2812: 	$companswer=
                   2813: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2814: 						    $env{'request.course.id'},
                   2815: 						    %form);
1.144     albertel 2816:     }
1.58      albertel 2817:     if ($removeform) {
                   2818: 	$companswer=~s|<form(.*?)>||g;
                   2819: 	$companswer=~s|</form>||g;
1.144     albertel 2820: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2821:     }
1.671     raeburn  2822:     my $renderheading = &mt('View of the problem');
                   2823:     my $answerheading = &mt('Correct answer');
                   2824:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2825:         my $stu_fullname = $env{'form.fullname'};
                   2826:         if ($stu_fullname eq '') {
                   2827:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2828:         }
                   2829:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2830:         if ($forwhom ne '') {
                   2831:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2832:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2833:         }
                   2834:     }
1.468     albertel 2835:     $rendered=
1.588     bisitz   2836:         '<div class="LC_Box">'
1.671     raeburn  2837:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2838:        .$rendered
                   2839:        .'</div>';
1.468     albertel 2840:     $companswer=
1.588     bisitz   2841:         '<div class="LC_Box">'
1.671     raeburn  2842:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2843:        .$companswer
                   2844:        .'</div>';
1.468     albertel 2845:     my $result;
1.144     albertel 2846:     if ($mode eq 'both') {
1.588     bisitz   2847:         $result=$rendered.$companswer;
1.144     albertel 2848:     } elsif ($mode eq 'text') {
1.588     bisitz   2849:         $result=$rendered;
1.144     albertel 2850:     } elsif ($mode eq 'answer') {
1.588     bisitz   2851:         $result=$companswer;
1.144     albertel 2852:     }
1.71      ng       2853:     return $result;
1.58      albertel 2854: }
1.397     albertel 2855: 
1.396     banghart 2856: sub files_exist {
                   2857:     my ($r, $symb) = @_;
                   2858:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2859:     foreach my $student (@students) {
                   2860:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2861:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2862: 					      $udom,$uname);
1.792     raeburn  2863:         my ($string)= &get_last_submission(\%record);
1.397     albertel 2864:         foreach my $submission (@$string) {
                   2865:             my ($partid,$respid) =
                   2866: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2867:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2868: 					   \%record);
                   2869:             return 1 if (@$files);
1.396     banghart 2870:         }
                   2871:     }
1.397     albertel 2872:     return 0;
1.396     banghart 2873: }
1.397     albertel 2874: 
1.394     banghart 2875: sub download_all_link {
                   2876:     my ($r,$symb) = @_;
1.621     www      2877:     unless (&files_exist($r, $symb)) {
1.766     raeburn  2878:         $r->print(&mt('There are currently no submitted documents.'));
                   2879:         return;
1.621     www      2880:     }
1.395     albertel 2881:     my $all_students = 
                   2882: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2883: 
                   2884:     my $parts =
                   2885: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2886: 
1.394     banghart 2887:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2888:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2889:                              'cgi.'.$identifier.'.symb' => $symb,
                   2890:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2891:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2892: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2893:     return;
                   2894: }
                   2895: 
                   2896: sub submit_download_link {
                   2897:     my ($request,$symb) = @_;
                   2898:     if (!$symb) { return ''; }
1.750     raeburn  2899:     my $res_error;
1.773     raeburn  2900:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   2901:         &response_type($symb,\$res_error);
                   2902:     if ($res_error) {
                   2903:         $request->print(&mt('An error occurred retrieving response types'));
                   2904:         return;
                   2905:     }
                   2906:     unless ($numessay) {
                   2907:         $request->print(&mt('No essayresponse items found'));
                   2908:         return;
1.750     raeburn  2909:     }
1.773     raeburn  2910:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2911:     if (@chosenparts) {
                   2912:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   2913:                                           undef,undef,1));
1.750     raeburn  2914:     }
1.773     raeburn  2915:     if ($numessay) {
1.750     raeburn  2916:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2917:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2918:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2919:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2920:         if (ref($fullname) eq 'HASH') {
                   2921:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2922:             if (@students) {
                   2923:                 @{$env{'form.stuinfo'}} = @students;
1.773     raeburn  2924:                 if ($numdropbox) {
1.750     raeburn  2925:                     &download_all_link($request,$symb);
1.773     raeburn  2926:                 } else {
                   2927:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  2928:                 }
1.773     raeburn  2929: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  2930: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2931:             } else {
                   2932:                 $request->print(&mt('No students match the criteria you selected'));
                   2933:             }
                   2934:         } else {
                   2935:             $request->print(&mt('Could not retrieve student information'));
                   2936:         }
                   2937:     } else {
                   2938:         $request->print(&mt('No essayresponse items found'));
                   2939:     }
                   2940:     return;
1.394     banghart 2941: }
1.395     albertel 2942: 
1.432     banghart 2943: sub build_section_inputs {
                   2944:     my $section_inputs;
                   2945:     if ($env{'form.section'} eq '') {
                   2946:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2947:     } else {
                   2948:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2949:         foreach my $section (@sections) {
1.432     banghart 2950:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2951:         }
                   2952:     }
                   2953:     return $section_inputs;
                   2954: }
                   2955: 
1.44      ng       2956: # --------------------------- show submissions of a student, option to grade 
                   2957: sub submission {
1.773     raeburn  2958:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2959:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2960:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2961:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2962:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2963: 
1.324     albertel 2964:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773     raeburn  2965:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  2966:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  2967:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2968: 
                   2969:     if (!&canview($usec)) {
1.712     bisitz   2970:         $request->print(
                   2971:             '<span class="LC_warning">'.
1.713     bisitz   2972:             &mt('Unable to view requested student.').
1.712     bisitz   2973:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2974:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2975:             '</span>');
1.104     albertel 2976: 	return;
                   2977:     }
                   2978: 
1.773     raeburn  2979:     my $res_error;
                   2980:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   2981:         &response_type($symb,\$res_error);
                   2982:     if ($res_error) {
                   2983:         $request->print(&navmap_errormsg());
                   2984:         return;
                   2985:     }
                   2986: 
1.257     albertel 2987:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2988:     unless ($is_tool) { 
                   2989:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2990:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2991:     }
1.773     raeburn  2992:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   2993:         $env{'form.compmsg'} = 1;
                   2994:     }
1.257     albertel 2995:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2996:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2997: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2998: 	'/check.gif" height="16" border="0" />';
1.41      ng       2999: 
                   3000:     # header info
                   3001:     if ($counter == 0) {
1.773     raeburn  3002:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   3003:         if (@chosenparts) {
                   3004:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   3005:         } elsif ($divforres) {
                   3006:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   3007:         } else {
                   3008:             $request->print('<br clear="all" />');
                   3009:         }
1.41      ng       3010: 	&sub_page_js($request);
1.773     raeburn  3011:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   3012: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       3013: 
1.44      ng       3014: 	# option to display problem, only once else it cause problems 
                   3015:         # with the form later since the problem has a form.
1.257     albertel 3016: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 3017: 	    my $mode;
1.257     albertel 3018: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 3019: 		$mode='both';
1.257     albertel 3020: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 3021: 		$mode='text';
1.257     albertel 3022: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 3023: 		$mode='answer';
                   3024: 	    }
1.329     albertel 3025: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 3026: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       3027: 	}
1.441     www      3028: 
1.41      ng       3029: 	my %keyhash = ();
1.773     raeburn  3030: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       3031: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 3032: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   3033: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773     raeburn  3034: 	}
                   3035: 	# kwclr is the only variable that is guaranteed not to be blank
                   3036: 	# if this subroutine has been called once.
                   3037: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 3038: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3039: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   3040: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   3041: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   3042: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773     raeburn  3043: 	}
                   3044: 	if ($env{'form.compmsg'}) {
                   3045: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      3046: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 3047: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       3048: 	}
1.773     raeburn  3049: 
1.257     albertel 3050: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 3051: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 3052: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       3053: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 3054: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       3055: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       3056: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       3057: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   3058: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 3059: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3060: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   3061: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   3062: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773     raeburn  3063: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 3064: 			&build_section_inputs().
1.326     albertel 3065: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       3066: 			'<input type="hidden" name="NCT"'.
1.257     albertel 3067: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773     raeburn  3068: 	if ($env{'form.compmsg'}) {
                   3069: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   3070: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   3071: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   3072: 	}
                   3073: 	if ($numessay) {
1.257     albertel 3074: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   3075: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   3076: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773     raeburn  3077: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       3078: 	}
1.773     raeburn  3079: 
1.41      ng       3080: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 3081: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       3082: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       3083: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 3084: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       3085: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       3086: 		'" />'."\n".
                   3087: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       3088: 	    $cts++;
                   3089: 	}
                   3090: 	$request->print($prnmsg);
1.32      ng       3091: 
1.773     raeburn  3092: 	if ($numessay) {
1.652     raeburn  3093: 
                   3094:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   3095:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  3096:                           keyw => 'Keyword Options',
1.655     raeburn  3097:                           list => 'List',
1.652     raeburn  3098:                           past => 'Paste Selection to List',
1.661     www      3099:                           high => 'Highlight Attribute',
1.773     raeburn  3100:                      );
1.88      www      3101: #
                   3102: # Print out the keyword options line
                   3103: #
1.718     bisitz   3104: 	    $request->print(
                   3105:                 '<div class="LC_columnSection">'
                   3106:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   3107:                .&Apache::lonhtmlcommon::funclist_from_array(
                   3108:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   3109:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   3110:  class="page">'.$lt{'past'}.'</a>',
                   3111:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   3112:                     {legend => $lt{'keyw'}})
                   3113:                .'</fieldset></div>'
                   3114:             );
                   3115: 
1.88      www      3116: #
                   3117: # Load the other essays for similarity check
                   3118: #
1.753     raeburn  3119:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   3120:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3121:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3122:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3123:                 if ($cdom ne '' && $cnum ne '') {
                   3124:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   3125:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   3126:                         my $apath = $1.'_'.$id;
                   3127:                         $apath=~s/\W/\_/gs;
                   3128:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   3129:                     }
                   3130:                 }
                   3131:             } else {
                   3132: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   3133: 	        $apath=&escape($apath);
                   3134: 	        $apath=~s/\W/\_/gs;
                   3135:                 &init_old_essays($symb,$apath,$adom,$aname);
                   3136:             }
1.41      ng       3137:         }
                   3138:     }
1.44      ng       3139: 
1.441     www      3140: # This is where output for one specific student would start
1.592     bisitz   3141:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   3142:     $request->print(
                   3143:         "\n\n"
                   3144:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   3145:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   3146:        ."\n"
                   3147:     );
1.441     www      3148: 
1.592     bisitz   3149:     # Show additional functions if allowed
                   3150:     if ($perm{'vgr'}) {
                   3151:         $request->print(
                   3152:             &Apache::loncommon::track_student_link(
1.708     bisitz   3153:                 'View recent activity',
1.592     bisitz   3154:                 $uname,$udom,'check')
                   3155:            .' '
                   3156:         );
                   3157:     }
                   3158:     if ($perm{'opa'}) {
                   3159:         $request->print(
                   3160:             &Apache::loncommon::pprmlink(
                   3161:                 &mt('Set/Change parameters'),
                   3162:                 $uname,$udom,$symb,'check'));
                   3163:     }
                   3164: 
                   3165:     # Show Problem
1.257     albertel 3166:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 3167: 	my $mode;
1.257     albertel 3168: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 3169: 	    $mode='both';
1.257     albertel 3170: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 3171: 	    $mode='text';
1.257     albertel 3172: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 3173: 	    $mode='answer';
                   3174: 	}
1.329     albertel 3175: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 3176: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 3177:     }
1.144     albertel 3178: 
1.257     albertel 3179:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       3180: 
1.44      ng       3181:     # Display student info
1.41      ng       3182:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   3183: 
1.745     raeburn  3184:     my $boxtitle = &mt('Submissions');
                   3185:     if ($is_tool) {
                   3186:         $boxtitle = &mt('Transactions')
                   3187:     }
1.590     bisitz   3188:     my $result='<div class="LC_Box">'
1.745     raeburn  3189:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       3190:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   3191:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773     raeburn  3192:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   3193:         $result.='<p class="LC_info">'
                   3194:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   3195:                 ."</p>\n";
1.469     albertel 3196:     }
                   3197: 
1.773     raeburn  3198:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 3199:     my $fullname;
                   3200:     my $col_fullnames = [];
1.773     raeburn  3201:     if ($numessay) {
1.464     albertel 3202: 	(my $sub_result,$fullname,$col_fullnames)=
                   3203: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   3204: 				 $counter);
                   3205: 	$result.=$sub_result;
1.41      ng       3206:     }
1.44      ng       3207:     $request->print($result."\n");
1.773     raeburn  3208: 
1.44      ng       3209:     # print student answer/submission
1.773     raeburn  3210:     # Options are (1) Last submission only
                   3211:     #             (2) Last submission (with detailed information for that submission)
                   3212:     #             (3) All transactions (by date)
                   3213:     #             (4) The whole record (with detailed information for all transactions)
                   3214: 
1.793     raeburn  3215:     my ($lastsubonly,$partinfo) =
                   3216:         &show_last_submission($uname,$udom,$symb,$essayurl,$responseType,$env{'form.lastSub'},
                   3217:                               $is_tool,$fullname,\%record,\%coursedesc_by_cid);
                   3218:     $request->print($partinfo);
                   3219:     $request->print($lastsubonly);
                   3220: 
                   3221:     if ($env{'form.lastSub'} eq 'datesub') {
                   3222:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3223: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
                   3224:     }
                   3225:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   3226:         my $identifier = (&canmodify($usec)? $counter : '');
                   3227:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
                   3228: 								 $env{'request.course.id'},
                   3229: 								 $last,'.submission',
                   3230: 								 'Apache::grades::keywords_highlight',
                   3231:                                                                  $usec,$identifier));
                   3232:     }
                   3233:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   3234: 	.$udom.'" />'."\n");
                   3235:     # return if view submission with no grading option
                   3236:     if (!&canmodify($usec)) {
                   3237: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   3238: 	return;
                   3239:     } else {
                   3240: 	$request->print('</div>'."\n");
                   3241:     }
                   3242: 
                   3243:     # grading message center
                   3244: 
                   3245:     if ($env{'form.compmsg'}) {
                   3246:         my $result='<div class="LC_Box">'.
                   3247:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   3248:                    '<div class="LC_grade_message_center_body">';
                   3249:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   3250:         my $msgfor = $givenn.' '.$lastname;
                   3251:         if (scalar(@$col_fullnames) > 0) {
                   3252:             my $lastone = pop(@$col_fullnames);
                   3253:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   3254:         }
                   3255:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   3256:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   3257:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   3258:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   3259:                  ',\''.$msgfor.'\');" target="_self">'.
                   3260:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   3261:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   3262:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   3263:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   3264:                  '<br />&nbsp;('.
                   3265:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   3266:                  '</div></div>';
                   3267:         $request->print($result);
                   3268:     }
                   3269: 
                   3270:     my %seen = ();
                   3271:     my @partlist;
                   3272:     my @gradePartRespid;
                   3273:     my @part_response_id;
                   3274:     if ($is_tool) {
                   3275:         @part_response_id = ([0,'']);
                   3276:     } else {
                   3277:         @part_response_id = &flatten_responseType($responseType);
                   3278:     }
                   3279:     $request->print(
                   3280:         '<div class="LC_Box">'
                   3281:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
                   3282:     );
                   3283:     $request->print(&gradeBox_start());
                   3284:     foreach my $part_response_id (@part_response_id) {
                   3285:     	my ($partid,$respid) = @{ $part_response_id };
                   3286: 	my $part_resp = join('_',@{ $part_response_id });
                   3287: 	next if ($seen{$partid} > 0);
                   3288: 	$seen{$partid}++;
                   3289: 	push(@partlist,$partid);
                   3290: 	push(@gradePartRespid,$partid.'.'.$respid);
                   3291: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
                   3292:     }
                   3293:     $request->print(&gradeBox_end()); # </div>
                   3294:     $request->print('</div>');
                   3295: 
                   3296:     $request->print('<div class="LC_grade_info_links">');
                   3297:     $request->print('</div>');
                   3298: 
                   3299:     $result='<input type="hidden" name="partlist'.$counter.
                   3300: 	'" value="'.(join ":",@partlist).'" />'."\n";
                   3301:     $result.='<input type="hidden" name="gradePartRespid'.
                   3302: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
                   3303:     my $ctr = 0;
                   3304:     while ($ctr < scalar(@partlist)) {
                   3305: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   3306: 	    $partlist[$ctr].'" />'."\n";
                   3307: 	$ctr++;
                   3308:     }
                   3309:     $request->print($result.''."\n");
                   3310: 
                   3311: # Done with printing info for one student
                   3312: 
                   3313:     $request->print('</div>');#LC_grade_show_user
                   3314: 
                   3315: 
                   3316:     # print end of form
                   3317:     if ($counter == $total) {
                   3318:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
                   3319: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
                   3320: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
                   3321: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
                   3322: 	my $ntstu ='<select name="NTSTU">'.
                   3323: 	    '<option>1</option><option>2</option>'.
                   3324: 	    '<option>3</option><option>5</option>'.
                   3325: 	    '<option>7</option><option>10</option></select>'."\n";
                   3326: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
                   3327: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
                   3328:         $endform.=&mt('[_1]student(s)',$ntstu);
                   3329: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
                   3330: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
                   3331: 	    '<input type="button" value="'.&mt('Next').'" '.
                   3332: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
                   3333:         $endform.='<span class="LC_warning">'.
                   3334:                   &mt('(Next and Previous (student) do not save the scores.)').
                   3335:                   '</span>'."\n" ;
                   3336:         $endform.="<input type='hidden' value='".&get_increment().
                   3337:             "' name='increment' />";
                   3338: 	$endform.='</td></tr></table></form>';
                   3339: 	$request->print($endform);
                   3340:     }
                   3341:     return '';
                   3342: }
                   3343: 
                   3344: sub show_last_submission {
                   3345:     my ($uname,$udom,$symb,$essayurl,$responseType,$viewtype,$is_tool,$fullname,
                   3346:         $record,$coursedesc_by_cid) = @_;
1.792     raeburn  3347:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
1.793     raeburn  3348:         &get_last_submission($record,$is_tool);
1.468     albertel 3349: 
1.793     raeburn  3350:     my ($lastsubonly,$partinfo);
1.792     raeburn  3351:     if ($timestamp eq '') {
1.793     raeburn  3352:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>';
1.745     raeburn  3353:     } elsif ($is_tool) {
                   3354:         $lastsubonly =
                   3355:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3356:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$timestamp."</div>\n";
1.702     kruse    3357:     } else {
1.792     raeburn  3358:         my ($shownsubmdate,$showngradedate);
                   3359:         if ($lastsubmittime && $lastgradetime) {
                   3360:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
                   3361:             if ($lastgradetime > $lastsubmittime) {
                   3362:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
                   3363:              }
                   3364:         } else {
                   3365:             $shownsubmdate = $timestamp;
                   3366:         }
1.702     kruse    3367:         $lastsubonly =
                   3368:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  3369:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
                   3370:         if ($showngradedate) {
                   3371:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
                   3372:         }
1.702     kruse    3373: 
1.793     raeburn  3374:         my %seenparts;
                   3375:         my @part_response_id = &flatten_responseType($responseType);
                   3376:         foreach my $part (@part_response_id) {
                   3377:             my ($partid,$respid) = @{ $part };
                   3378:             my $display_part=&get_display_part($partid,$symb);
                   3379:             if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   3380:                 if (exists($seenparts{$partid})) { next; }
                   3381:                 $seenparts{$partid}=1;
                   3382:                 $partinfo .=
1.702     kruse    3383:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3384:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   3385:                                '<a href="javascript:viewSubmitter(\''.
                   3386:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   3387:                                '\');" target="_self">'.
                   3388:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
1.793     raeburn  3389:                     '<br />';
                   3390:                 next;
                   3391:             }
                   3392:             my $responsetype = $responseType->{$partid}->{$respid};
                   3393:             if (!exists($record->{"resource.$partid.$respid.submission"})) {
1.702     kruse    3394:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   3395:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3396:                     ' <span class="LC_internal_info">'.
                   3397:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   3398:                     '</span>&nbsp; &nbsp;'.
1.793     raeburn  3399:                     '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   3400:                 next;
                   3401:             }
                   3402:             foreach my $submission (@$string) {
                   3403:                 my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   3404:                 if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   3405:                 my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   3406:                 # Similarity check
1.702     kruse    3407:                 my $similar='';
                   3408:                 my ($type,$trial,$rndseed);
                   3409:                 if ($hide eq 'rand') {
                   3410:                     $type = 'randomizetry';
1.793     raeburn  3411:                     $trial = $record->{"resource.$partid.tries"};
                   3412:                     $rndseed = $record->{"resource.$partid.rndseed"};
1.702     kruse    3413:                 }
1.793     raeburn  3414:                 if ($env{'form.checkPlag'}) {
                   3415:                     my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   3416:                     &most_similar($uname,$udom,$symb,$subval);
                   3417:                     if ($osim) {
                   3418:                         $osim=int($osim*100.0);
1.702     kruse    3419:                         if ($hide eq 'anon') {
                   3420:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   3421:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   3422:                         } else {
1.793     raeburn  3423:                             $similar='<hr />';
1.753     raeburn  3424:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   3425:                                 $similar .= '<h3><span class="LC_warning">'.
                   3426:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   3427:                                                 $osim,
                   3428:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3429:                                             '</span></h3>';
                   3430:                             } else {
                   3431:                                 my %old_course_desc;
                   3432:                                 if ($ocrsid ne '') {
1.793     raeburn  3433:                                     if (ref($coursedesc_by_cid->{$ocrsid}) eq 'HASH') {
                   3434:                                         %old_course_desc = %{$coursedesc_by_cid->{$ocrsid}};
1.753     raeburn  3435:                                     } else {
                   3436:                                         my $args;
                   3437:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   3438:                                             $args = {'one_time' => 1};
                   3439:                                         }
                   3440:                                         %old_course_desc =
                   3441:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
1.793     raeburn  3442:                                         $coursedesc_by_cid->{$ocrsid} = \%old_course_desc;
1.753     raeburn  3443:                                     }
                   3444:                                     $similar .=
                   3445:                                         '<h3><span class="LC_warning">'.
                   3446:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   3447:                                             $osim,
                   3448:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   3449:                                             $old_course_desc{'description'},
                   3450:                                             $old_course_desc{'num'},
                   3451:                                             $old_course_desc{'domain'}).
                   3452:                                         '</span></h3>';
                   3453:                                 } else {
                   3454:                                     $similar .=
                   3455:                                         '<h3><span class="LC_warning">'.
                   3456:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   3457:                                             $osim,
                   3458:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   3459:                                         '</span></h3>';
                   3460:                                 }
                   3461:                             }
                   3462:                             $similar .= '<blockquote><i>'.
                   3463:                                         &keywords_highlight($oessay).
                   3464:                                         '</i></blockquote><hr />';
1.702     kruse    3465:                         }
1.793     raeburn  3466:                     }
                   3467:                 }
                   3468:                 my $order=&get_order($partid,$respid,$symb,$uname,$udom,
1.702     kruse    3469:                                      undef,$type,$trial,$rndseed);
1.793     raeburn  3470:                 if (($viewtype eq 'lastonly') ||
                   3471:                     ($viewtype eq 'datesub')  ||
                   3472:                     ($viewtype =~ /^(last|all)$/)) {
                   3473:                     my $display_part=&get_display_part($partid,$symb);
1.702     kruse    3474:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   3475:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   3476:                         ' <span class="LC_internal_info">'.
                   3477:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   3478:                         '</span>&nbsp; &nbsp;';
1.793     raeburn  3479:                     my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   3480:                     if (@$files) {
1.702     kruse    3481:                         if ($hide eq 'anon') {
                   3482:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   3483:                         } else {
                   3484:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   3485:                                         .'<br /><span class="LC_warning">';
                   3486:                             if(@$files == 1) {
                   3487:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  3488:                             } else {
1.702     kruse    3489:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   3490:                             }
1.774     raeburn  3491:                             $lastsubonly .= '</span>';
1.702     kruse    3492:                             foreach my $file (@$files) {
                   3493:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   3494:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  3495:                             }
                   3496:                         }
1.793     raeburn  3497:                         $lastsubonly.='<br />';
1.702     kruse    3498:                     }
                   3499:                     if ($hide eq 'anon') {
1.793     raeburn  3500:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
1.702     kruse    3501:                     } else {
1.774     raeburn  3502:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  3503:                         if ($draft) {
                   3504:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   3505:                         }
                   3506:                         $subval =
1.793     raeburn  3507:                             &cleanRecord($subval,$responsetype,$symb,$partid,
                   3508:                                          $respid,$record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  3509:                         if ($responsetype eq 'essay') {
                   3510:                             $subval =~ s{\n}{<br />}g;
                   3511:                         }
                   3512:                         $lastsubonly.=$subval."\n";
1.702     kruse    3513:                     }
1.774     raeburn  3514:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.793     raeburn  3515:                     $lastsubonly.='</div>';
                   3516:                 }
1.702     kruse    3517:             }
1.773     raeburn  3518:         }
1.793     raeburn  3519:         $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.118     ng       3520:     }
1.793     raeburn  3521:     return ($lastsubonly,$partinfo);
1.38      ng       3522: }
                   3523: 
1.464     albertel 3524: sub check_collaborators {
                   3525:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   3526:     my ($result,@col_fullnames);
                   3527:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   3528:     foreach my $part (keys(%$handgrade)) {
                   3529: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   3530: 					'.maxcollaborators',
                   3531: 					$symb,$udom,$uname);
                   3532: 	next if ($ncol <= 0);
                   3533: 	$part =~ s/\_/\./g;
                   3534: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   3535: 	my (@good_collaborators, @bad_collaborators);
                   3536: 	foreach my $possible_collaborator
1.630     www      3537: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 3538: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   3539: 	    next if ($possible_collaborator eq '');
1.631     www      3540: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 3541: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   3542: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   3543: 	    # Doing this grep allows 'fuzzy' specification
                   3544: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   3545: 			       keys(%$classlist));
                   3546: 	    if (! scalar(@matches)) {
                   3547: 		push(@bad_collaborators, $possible_collaborator);
                   3548: 	    } else {
                   3549: 		push(@good_collaborators, @matches);
                   3550: 	    }
                   3551: 	}
                   3552: 	if (scalar(@good_collaborators) != 0) {
1.630     www      3553: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 3554: 	    foreach my $name (@good_collaborators) {
                   3555: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   3556: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      3557: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 3558: 	    }
1.630     www      3559: 	    $result.='</ol><br />'."\n";
1.466     albertel 3560: 	    my ($part)=split(/\./,$part);
1.464     albertel 3561: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   3562: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   3563: 		"\n";
                   3564: 	}
                   3565: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 3566: 	    $result.='<div class="LC_warning">';
1.464     albertel 3567: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   3568: 	    $result .= '</div>';
                   3569: 	}         
                   3570: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 3571: 	    $result .= '<div class="LC_warning">';
1.464     albertel 3572: 	    $result .= &mt('This student has submitted too many '.
                   3573: 		'collaborators.  Maximum is [_1].',$ncol);
                   3574: 	    $result .= '</div>';
                   3575: 	}
                   3576:     }
                   3577:     return ($result,$fullname,\@col_fullnames);
                   3578: }
                   3579: 
1.44      ng       3580: #--- Retrieve the last submission for all the parts
1.38      ng       3581: sub get_last_submission {
1.745     raeburn  3582:     my ($returnhash,$is_tool)=@_;
1.792     raeburn  3583:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
1.119     ng       3584:     if ($$returnhash{'version'}) {
1.46      ng       3585: 	my %lasthash=();
1.792     raeburn  3586:         my %prevsolved=();
                   3587:         my %solved=();
                   3588: 	my $version;
1.119     ng       3589: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.792     raeburn  3590:             my %handgraded = ();
1.397     albertel 3591: 	    foreach my $key (sort(split(/\:/,
                   3592: 					$$returnhash{$version.':keys'}))) {
                   3593: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
1.792     raeburn  3594:                 if ($key =~ /\.([^.]+)\.regrader$/) {
                   3595:                     $handgraded{$1} = 1;
                   3596:                 } elsif ($key =~ /\.portfiles$/) {
                   3597:                     if (($$returnhash{$version.':'.$key} ne '') &&
                   3598:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
                   3599:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3600:                     }
                   3601:                 } elsif ($key =~ /\.submission$/) {
                   3602:                     if ($$returnhash{$version.':'.$key} ne '') {
                   3603:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   3604:                     }
                   3605:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
                   3606:                     $prevsolved{$1} = $solved{$1};
                   3607:                     $solved{$1} = $lasthash{$key};
                   3608:                 }
                   3609:             }
                   3610:             foreach my $partid (keys(%handgraded)) {
                   3611:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
                   3612:                     (($solved{$partid} eq 'incorrect_by_override') ||
                   3613:                      ($solved{$partid} eq 'correct_by_override'))) {
                   3614:                     $lastgradetime = $$returnhash{$version.':timestamp'};
                   3615:                 }
                   3616:                 if ($solved{$partid} ne '') {
                   3617:                     $prevsolved{$partid} = $solved{$partid};
                   3618:                 }
1.46      ng       3619: 	    }
                   3620: 	}
1.795     raeburn  3621: #
                   3622: # Timestamp is for last transaction for this resource, which does not
                   3623: # necessarily correspond to the time of last submission for problem (or part).
                   3624: #
                   3625:         if ($lasthash{'timestamp'} ne '') {
                   3626:             $timestamp = &Apache::lonlocal::locallocaltime($lasthash{'timestamp'});
                   3627:         }
1.640     raeburn  3628:         my (%typeparts,%randombytry);
1.596     raeburn  3629:         my $showsurv = 
                   3630:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   3631:         foreach my $key (sort(keys(%lasthash))) {
                   3632:             if ($key =~ /\.type$/) {
                   3633:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  3634:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   3635:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  3636:                     my ($ign,@parts) = split(/\./,$key);
                   3637:                     pop(@parts);
1.641     raeburn  3638:                     my $id = join('.',@parts);
1.640     raeburn  3639:                     if ($lasthash{$key} eq 'randomizetry') {
                   3640:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   3641:                     } else {
                   3642:                         unless ($showsurv) {
                   3643:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   3644:                         }
1.596     raeburn  3645:                     }
                   3646:                     delete($lasthash{$key});
                   3647:                 }
                   3648:             }
                   3649:         }
                   3650:         my @hidden = keys(%typeparts);
1.640     raeburn  3651:         my @randomize = keys(%randombytry);
1.397     albertel 3652: 	foreach my $key (keys(%lasthash)) {
                   3653: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  3654:             my $hide;
                   3655:             if (@hidden) {
                   3656:                 foreach my $id (@hidden) {
                   3657:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  3658:                         $hide = 'anon';
1.596     raeburn  3659:                         last;
                   3660:                     }
                   3661:                 }
                   3662:             }
1.640     raeburn  3663:             unless ($hide) {
                   3664:                 if (@randomize) {
1.732     raeburn  3665:                     foreach my $id (@randomize) {
1.640     raeburn  3666:                         if ($key =~ /^\Q$id\E/) {
                   3667:                             $hide = 'rand';
                   3668:                             last;
                   3669:                         }
                   3670:                     }
                   3671:                 }
                   3672:             }
1.397     albertel 3673: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  3674: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   3675:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   3676:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   3677:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       3678: 	}
                   3679:     }
1.397     albertel 3680:     if (!@string) {
1.745     raeburn  3681:         my $msg;
                   3682:         if ($is_tool) {
1.747     raeburn  3683:             $msg = &mt('No grade passed back.');
1.745     raeburn  3684:         } else {
                   3685:             $msg = &mt('Nothing submitted - no attempts.');
                   3686:         }
1.397     albertel 3687: 	$string[0] =
1.745     raeburn  3688: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 3689:     }
1.792     raeburn  3690:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       3691: }
1.35      ng       3692: 
1.44      ng       3693: #--- High light keywords, with style choosen by user.
1.38      ng       3694: sub keywords_highlight {
1.44      ng       3695:     my $string    = shift;
1.257     albertel 3696:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   3697:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       3698:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 3699:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 3700:     foreach my $keyword (@keylist) {
                   3701: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       3702:     }
                   3703:     return $string;
1.38      ng       3704: }
1.36      ng       3705: 
1.671     raeburn  3706: # For Tasks provide a mechanism to display previous version for one specific student
                   3707: 
                   3708: sub show_previous_task_version {
                   3709:     my ($request,$symb) = @_;
                   3710:     if ($symb eq '') {
1.717     bisitz   3711:         $request->print(
                   3712:             '<span class="LC_error">'.
                   3713:             &mt('Unable to handle ambiguous references.').
                   3714:             '</span>');
1.671     raeburn  3715:         return '';
                   3716:     }
                   3717:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3718:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3719:     if (!&canview($usec)) {
1.712     bisitz   3720:         $request->print(
                   3721:             '<span class="LC_warning">'.
1.713     bisitz   3722:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   3723:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3724:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3725:             '</span>');
1.671     raeburn  3726:         return;
                   3727:     }
                   3728:     my $mode = 'both';
                   3729:     my $isTask = ($symb =~/\.task$/);
                   3730:     if ($isTask) {
                   3731:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   3732:             if ($env{'form.fullname'} eq '') {
                   3733:                 $env{'form.fullname'} =
                   3734:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3735:             }
                   3736:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   3737:             $request->print("\n\n".
                   3738:                             '<div class="LC_grade_show_user">'.
                   3739:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   3740:                             '</h2>'."\n");
                   3741:             &Apache::lonxml::clear_problem_counter();
                   3742:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   3743:                             {'previousversion' => $env{'form.previousversion'} }));
                   3744:             $request->print("\n</div>");
                   3745:         }
                   3746:     }
                   3747:     return;
                   3748: }
                   3749: 
                   3750: sub choose_task_version_form {
                   3751:     my ($symb,$uname,$udom,$nomenu) = @_;
                   3752:     my $isTask = ($symb =~/\.task$/);
                   3753:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   3754:     if ($isTask) {
                   3755:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3756:                                               $udom,$uname);
                   3757:         if (($record{'resource.0.version'} eq '') ||
                   3758:             ($record{'resource.0.version'} < 2)) {
                   3759:             return ($record{'resource.0.version'},
                   3760:                     $record{'resource.0.version'},$result,$js);
                   3761:         } else {
                   3762:             $current = $record{'resource.0.version'};
                   3763:         }
                   3764:         if ($env{'form.previousversion'}) {
                   3765:             $displayed = $env{'form.previousversion'};
                   3766:             $rowtitle = &mt('Choose another version:')
                   3767:         } else {
                   3768:             $displayed = $current;
                   3769:             $rowtitle = &mt('Show earlier version:');
                   3770:         }
                   3771:         $result = '<div class="LC_left_float">';
                   3772:         my $list;
                   3773:         my $numversions = 0;
                   3774:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3775:             if ($i == $current) {
                   3776:                 if (!$env{'form.previousversion'} || $nomenu) {
                   3777:                     next;
                   3778:                 } else {
                   3779:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3780:                     $numversions ++;
                   3781:                 }
                   3782:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3783:                 unless ($i == $env{'form.previousversion'}) {
                   3784:                     $numversions ++;
                   3785:                 }
                   3786:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3787:             }
                   3788:         }
                   3789:         if ($numversions) {
                   3790:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3791:             $result .=
                   3792:                 '<form name="getprev" method="post" action=""'.
                   3793:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3794:                 &Apache::loncommon::start_data_table().
                   3795:                 &Apache::loncommon::start_data_table_row().
                   3796:                 '<th align="left">'.$rowtitle.'</th>'.
                   3797:                 '<td><select name="version">'.
                   3798:                 '<option>'.&mt('Select').'</option>'.
                   3799:                 $list.
                   3800:                 '</select></td>'.
                   3801:                 &Apache::loncommon::end_data_table_row();
                   3802:             unless ($nomenu) {
                   3803:                 $result .= &Apache::loncommon::start_data_table_row().
                   3804:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3805:                 '<td><span class="LC_nobreak">'.
                   3806:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3807:                 &mt('Yes').'</label>'.
                   3808:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3809:                 '</span></td>'.
                   3810:                 &Apache::loncommon::end_data_table_row();
                   3811:             }
                   3812:             $result .=
                   3813:                 &Apache::loncommon::start_data_table_row().
                   3814:                 '<th align="left">&nbsp;</th>'.
                   3815:                 '<td>'.
                   3816:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3817:                 '</td>'.
                   3818:                 &Apache::loncommon::end_data_table_row().
                   3819:                 &Apache::loncommon::end_data_table().
                   3820:                 '</form>';
                   3821:             $js = &previous_display_javascript($nomenu,$current);
                   3822:         } elsif ($displayed && $nomenu) {
                   3823:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3824:         } else {
                   3825:             $result .= &mt('No previous versions to show for this student');
                   3826:         }
                   3827:         $result .= '</div>';
                   3828:     }
                   3829:     return ($current,$displayed,$result,$js);
                   3830: }
                   3831: 
                   3832: sub previous_display_javascript {
                   3833:     my ($nomenu,$current) = @_;
                   3834:     my $js = <<"JSONE";
                   3835: <script type="text/javascript">
                   3836: // <![CDATA[
                   3837: function previousVersion(uname,udom,symb) {
                   3838:     var current = '$current';
                   3839:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3840:     var prevstr = new RegExp("^\\\\d+\$");
                   3841:     if (!prevstr.test(version)) {
                   3842:         return false;
                   3843:     }
                   3844:     var url = '';
                   3845:     if (version == current) {
                   3846:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3847:     } else {
                   3848:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3849:     }
                   3850: JSONE
                   3851:     if ($nomenu) {
                   3852:         $js .= <<"JSTWO";
                   3853:     document.location.href = url;
                   3854: JSTWO
                   3855:     } else {
                   3856:         $js .= <<"JSTHREE";
                   3857:     var newwin = 0;
                   3858:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3859:         if (document.getprev.prevwin[i].checked == true) {
                   3860:             newwin = document.getprev.prevwin[i].value;
                   3861:         }
                   3862:     }
                   3863:     if (newwin == 1) {
                   3864:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3865:         url = url+'&inhibitmenu=yes';
                   3866:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3867:             previousWin = window.open(url,'',options,1);
                   3868:         } else {
                   3869:             previousWin.location.href = url;
                   3870:         }
                   3871:         previousWin.focus();
                   3872:         return false;
                   3873:     } else {
                   3874:         document.location.href = url;
                   3875:         return false;
                   3876:     }
                   3877: JSTHREE
                   3878:     }
                   3879:     $js .= <<"ENDJS";
                   3880:     return false;
                   3881: }
                   3882: // ]]>
                   3883: </script>
                   3884: ENDJS
                   3885: 
                   3886: }
                   3887: 
1.44      ng       3888: #--- Called from submission routine
1.38      ng       3889: sub processHandGrade {
1.608     www      3890:     my ($request,$symb) = @_;
1.324     albertel 3891:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3892:     my $button = $env{'form.gradeOpt'};
                   3893:     my $ngrade = $env{'form.NCT'};
                   3894:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3895:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3896:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.786     raeburn  3897:     my ($res_error,%queueable);
                   3898:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3899:     if ($res_error) {
                   3900:         $request->print(&navmap_errormsg());
                   3901:         return;
                   3902:     } else {
                   3903:         foreach my $part (@{$partlist}) {
                   3904:             if (ref($responseType->{$part}) eq 'HASH') {
                   3905:                 foreach my $id (keys(%{$responseType->{$part}})) {
                   3906:                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   3907:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   3908:                         $queueable{$part} = 1;
                   3909:                         last;
                   3910:                     }
                   3911:                 }
                   3912:             }
                   3913:         }
                   3914:     }
1.301     albertel 3915: 
1.44      ng       3916:     if ($button eq 'Save & Next') {
                   3917: 	my $ctr = 0;
                   3918: 	while ($ctr < $ngrade) {
1.257     albertel 3919: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  3920: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
1.786     raeburn  3921:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
1.71      ng       3922: 	    if ($errorflag eq 'no_score') {
                   3923: 		$ctr++;
                   3924: 		next;
                   3925: 	    }
1.104     albertel 3926: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3927: 		$request->print(
                   3928:                     '<span class="LC_error">'
                   3929:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3930:                    .'</span>');
1.104     albertel 3931: 		$ctr++;
                   3932: 		next;
                   3933: 	    }
1.726     raeburn  3934:             if ($numhidden) {
                   3935:                 $request->print(
                   3936:                     '<span class="LC_info">'
                   3937:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3938:                    .'</span><br />');
                   3939:             }
1.257     albertel 3940: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3941: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3942: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3943:             my ($feedurl,$showsymb) =
                   3944: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3945: 	    my $messagetail;
1.62      albertel 3946: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3947: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3948: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3949: 		$subject.=' ['.$restitle.']';
1.44      ng       3950: 		my (@msgnum) = split(/,/,$includemsg);
                   3951: 		foreach (@msgnum) {
1.257     albertel 3952: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3953: 		}
1.80      ng       3954: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3955: 		if ($env{'form.withgrades'.$ctr}) {
                   3956: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3957: 		    $messagetail = " for <a href=\"".
1.605     www      3958: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3959: 		}
                   3960: 		$msgstatus = 
                   3961:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3962: 						     $message.$messagetail,
1.418     albertel 3963:                                                      undef,$feedurl,undef,
1.386     raeburn  3964:                                                      undef,undef,$showsymb,
                   3965:                                                      $restitle);
1.574     bisitz   3966: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3967: 				$msgstatus.'<br />');
1.44      ng       3968: 	    }
1.257     albertel 3969: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3970: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3971: 		foreach my $collabstr (@collabstrs) {
                   3972: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3973: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3974: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3975: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.786     raeburn  3976: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 3977: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3978: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3979: 			    next;
1.418     albertel 3980: 			} elsif ($message ne '') {
                   3981: 			    my ($baseurl,$showsymb) = 
                   3982: 				&get_feedurl_and_symb($symb,$collaborator,
                   3983: 						      $udom);
                   3984: 			    if ($env{'form.withgrades'.$ctr}) {
                   3985: 				$messagetail = " for <a href=\"".
1.605     www      3986:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3987: 			    }
1.418     albertel 3988: 			    $msgstatus = 
                   3989: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3990: 			}
1.44      ng       3991: 		    }
                   3992: 		}
                   3993: 	    }
                   3994: 	    $ctr++;
                   3995: 	}
                   3996:     }
                   3997: 
1.773     raeburn  3998:     my %keyhash = ();
                   3999:     if ($numessay) {
1.119     ng       4000: 	# Keywords sorted in alphabatical order
1.257     albertel 4001: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   4002: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  4003: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 4004: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   4005: 	$env{'form.keywords'} = join(' ',@keywords);
                   4006: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   4007: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   4008: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   4009: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   4010: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  4011:     }
1.119     ng       4012: 
1.773     raeburn  4013:     if ($env{'form.compmsg'}) {
1.119     ng       4014: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 4015: 	# New messages are saved in env for the next student.
1.119     ng       4016: 	# All messages are saved in nohist_handgrade.db
                   4017: 	my ($ctr,$idx) = (1,1);
1.257     albertel 4018: 	while ($ctr <= $env{'form.savemsgN'}) {
                   4019: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   4020: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       4021: 		$idx++;
                   4022: 	    }
                   4023: 	    $ctr++;
1.41      ng       4024: 	}
1.119     ng       4025: 	$ctr = 0;
                   4026: 	while ($ctr < $ngrade) {
1.257     albertel 4027: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  4028: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4029: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   4030: 	        $idx++;
1.119     ng       4031: 	    }
                   4032: 	    $ctr++;
1.41      ng       4033: 	}
1.257     albertel 4034: 	$env{'form.savemsgN'} = --$idx;
                   4035: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       4036:     }
1.773     raeburn  4037:     if (($numessay) || ($env{'form.compmsg'})) {
                   4038:         my $putresult = &Apache::lonnet::put
                   4039:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   4040:     }
                   4041: 
1.44      ng       4042:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 4043:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   4044:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       4045: 	my ($ctr,$total) = (0,0);
                   4046: 	while ($ctr < $ngrade) {
1.257     albertel 4047: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       4048: 	    $ctr++;
                   4049: 	}
1.257     albertel 4050: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       4051: 	$ctr = 0;
                   4052: 	while ($ctr < $total) {
1.257     albertel 4053: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   4054: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   4055: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      4056: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       4057: 	    $ctr++;
                   4058: 	}
                   4059: 	return '';
                   4060:     }
1.36      ng       4061: 
1.44      ng       4062:     # Get the next/previous one or group of students
1.257     albertel 4063:     my $firststu = $env{'form.unamedom0'};
                   4064:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       4065:     my $ctr = 2;
1.41      ng       4066:     while ($laststu eq '') {
1.257     albertel 4067: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       4068: 	$ctr++;
                   4069: 	$laststu = $firststu if ($ctr > $ngrade);
                   4070:     }
1.44      ng       4071: 
1.41      ng       4072:     my (@parsedlist,@nextlist);
                   4073:     my ($nextflg) = 0;
1.524     raeburn  4074:     foreach my $item (sort 
1.294     albertel 4075: 	     {
                   4076: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4077: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4078: 		 }
                   4079: 		 return $a cmp $b;
                   4080: 	     } (keys(%$fullname))) {
1.41      ng       4081: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  4082: 	    push(@parsedlist,$item);
1.41      ng       4083: 	}
1.524     raeburn  4084: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       4085: 	if ($button eq 'Previous') {
1.524     raeburn  4086: 	    last if ($item eq $firststu);
                   4087: 	    push(@parsedlist,$item);
1.41      ng       4088: 	}
                   4089:     }
                   4090:     $ctr = 0;
                   4091:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   4092:     foreach my $student (@parsedlist) {
1.257     albertel 4093: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       4094: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 4095: 	
                   4096: 	if ($submitonly eq 'queued') {
                   4097: 	    my %queue_status = 
                   4098: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4099: 							$udom,$uname);
                   4100: 	    next if (!defined($queue_status{'gradingqueue'}));
                   4101: 	}
                   4102: 
1.156     albertel 4103: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 4104: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 4105: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 4106: 	    my $submitted = 0;
1.248     albertel 4107: 	    my $ungraded = 0;
                   4108: 	    my $incorrect = 0;
1.524     raeburn  4109: 	    foreach my $item (keys(%status)) {
                   4110: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   4111: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   4112: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   4113: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 4114: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   4115: 		    $submitted = 0;
                   4116: 		}
1.41      ng       4117: 	    }
1.156     albertel 4118: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   4119: 				     $submitonly eq 'incorrect' ||
                   4120: 				     $submitonly eq 'graded'));
1.248     albertel 4121: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   4122: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       4123: 	}
1.524     raeburn  4124: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       4125: 	last if ($ctr == $ntstu);
1.41      ng       4126: 	$ctr++;
                   4127:     }
1.36      ng       4128: 
1.41      ng       4129:     $ctr = 0;
                   4130:     my $total = scalar(@nextlist)-1;
1.39      ng       4131: 
1.524     raeburn  4132:     foreach (sort(@nextlist)) {
1.41      ng       4133: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 4134: 	$env{'form.student'}  = $uname;
                   4135: 	$env{'form.userdom'}  = $udom;
                   4136: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      4137: 	&submission($request,$ctr,$total,$symb);
1.41      ng       4138: 	$ctr++;
                   4139:     }
                   4140:     if ($total < 0) {
1.653     raeburn  4141: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       4142: 	$request->print($the_end);
                   4143:     }
                   4144:     return '';
1.38      ng       4145: }
1.36      ng       4146: 
1.44      ng       4147: #---- Save the score and award for each student, if changed
1.38      ng       4148: sub saveHandGrade {
1.786     raeburn  4149:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
1.342     banghart 4150:     my @version_parts;
1.104     albertel 4151:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 4152: 					   $env{'request.course.id'});
1.104     albertel 4153:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 4154:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 4155:     my @parts_graded;
1.77      ng       4156:     my %newrecord  = ();
1.726     raeburn  4157:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  4158:     my %aggregate = ();
                   4159:     my $aggregateflag = 0;
1.726     raeburn  4160:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  4161:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  4162:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  4163:         $totchg += $numchgs;
                   4164:     }
1.301     albertel 4165:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   4166:     foreach my $new_part (@parts) {
1.337     banghart 4167: 	#collaborator ($submi may vary for different parts
1.259     banghart 4168: 	if ($submitter && $new_part ne $part) { next; }
                   4169: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       4170: 	if ($dropMenu eq 'excused') {
1.259     banghart 4171: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   4172: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   4173: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   4174: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 4175: 		}
1.364     banghart 4176: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 4177: 	    }
1.125     ng       4178: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 4179: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  4180: 	    foreach my $key (keys(%record)) {
1.259     banghart 4181: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 4182: 	    }
1.259     banghart 4183: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4184: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 4185:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   4186: 
                   4187:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   4188: 					       [$new_part]);
                   4189:             my $aggtries =$totaltries;
1.269     raeburn  4190:             if ($last_resets{$new_part}) {
1.270     albertel 4191:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   4192: 					   $new_part);
1.269     raeburn  4193:             }
1.270     albertel 4194: 
                   4195:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  4196:             if ($aggtries > 0) {
1.327     albertel 4197:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  4198:                 $aggregateflag = 1;
                   4199:             }
1.125     ng       4200: 	} elsif ($dropMenu eq '') {
1.259     banghart 4201: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   4202: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   4203: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   4204: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 4205: 		next;
                   4206: 	    }
1.259     banghart 4207: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   4208: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       4209: 	    my $partial= $pts/$wgt;
1.259     banghart 4210: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 4211: 		#do not update score for part if not changed.
1.346     banghart 4212:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 4213: 		next;
1.251     banghart 4214: 	    } else {
1.524     raeburn  4215: 	        push(@parts_graded,$new_part);
1.153     albertel 4216: 	    }
1.259     banghart 4217: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   4218: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 4219: 	    }
1.259     banghart 4220: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       4221: 	    if ($partial == 0) {
1.153     albertel 4222: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   4223: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   4224: 		}
1.41      ng       4225: 	    } else {
1.153     albertel 4226: 		if ($record{$reckey} ne 'correct_by_override') {
                   4227: 		    $newrecord{$reckey} = 'correct_by_override';
                   4228: 		}
                   4229: 	    }	    
                   4230: 	    if ($submitter && 
1.259     banghart 4231: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   4232: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       4233: 	    }
1.259     banghart 4234: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 4235: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       4236: 	}
1.259     banghart 4237: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 4238: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   4239: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   4240: 	        $dropMenu eq 'reset status')
                   4241: 	   {
1.524     raeburn  4242: 	    push(@version_parts,$new_part);
1.259     banghart 4243: 	}
1.41      ng       4244:     }
1.301     albertel 4245:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4246:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4247: 
1.344     albertel 4248:     if (%newrecord) {
                   4249:         if (@version_parts) {
1.364     banghart 4250:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   4251:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 4252: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 4253: 	    foreach my $new_part (@version_parts) {
                   4254: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   4255: 				$new_part,\%newrecord);
                   4256: 	    }
1.259     banghart 4257:         }
1.44      ng       4258: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 4259: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 4260: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.786     raeburn  4261: 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       4262:     }
1.269     raeburn  4263:     if ($aggregateflag) {
                   4264:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4265: 			      $cdom,$cnum);
1.269     raeburn  4266:     }
1.726     raeburn  4267:     return ('',$pts,$wgt,$totchg);
                   4268: }
                   4269: 
                   4270: sub makehidden {
1.728     raeburn  4271:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  4272:     return unless (ref($record) eq 'HASH');
                   4273:     my %modified;
                   4274:     my $numchanged = 0;
                   4275:     if (exists($record->{$version.':keys'})) {
                   4276:         my $partsregexp = $parts;
                   4277:         $partsregexp =~ s/,/|/g;
                   4278:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   4279:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   4280:                  my $item = $1;
                   4281:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   4282:                      $modified{$key} = $record->{$version.':'.$key};
                   4283:                  }
                   4284:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   4285:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   4286:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   4287:                 $modified{$key} = $record->{$version.':'.$key};
                   4288:             }
                   4289:         }
                   4290:         if (keys(%modified)) {
                   4291:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  4292:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  4293:                 $numchanged ++;
                   4294:             }
                   4295:         }
                   4296:     }
                   4297:     return $numchanged;
1.36      ng       4298: }
1.322     albertel 4299: 
1.380     albertel 4300: sub check_and_remove_from_queue {
1.786     raeburn  4301:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 4302:     my @ungraded_parts;
                   4303:     foreach my $part (@{$parts}) {
                   4304: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   4305: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   4306: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   4307: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   4308: 		) {
1.786     raeburn  4309:             if ($queueable->{$part}) {
                   4310: 	        push(@ungraded_parts, $part);
                   4311:             }
1.380     albertel 4312: 	}
                   4313:     }
                   4314:     if ( !@ungraded_parts ) {
                   4315: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   4316: 					       $cnum,$domain,$stuname);
                   4317:     }
                   4318: }
                   4319: 
1.337     banghart 4320: sub handback_files {
                   4321:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  4322:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  4323:     my $res_error;
                   4324:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4325:     if ($res_error) {
                   4326:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   4327:         return;
                   4328:     }
1.654     raeburn  4329:     my @handedback;
                   4330:     my $file_msg;
1.375     albertel 4331:     my @part_response_id = &flatten_responseType($responseType);
                   4332:     foreach my $part_response_id (@part_response_id) {
                   4333:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   4334: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  4335:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   4336:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   4337:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   4338:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   4339:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 4340:                     my ($directory,$answer_file) = 
1.654     raeburn  4341:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 4342:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  4343: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 4344: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  4345:                     my $getpropath = 1;
1.773     raeburn  4346:                     my ($dir_list,$listerror) =
1.662     raeburn  4347:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   4348:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  4349: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   4350:                     # fix filename
1.355     banghart 4351:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   4352:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  4353:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 4354:             	                                $save_file_name);
1.337     banghart 4355:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  4356:                         $request->print('<br /><span class="LC_error">'.
                   4357:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  4358:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  4359:                                         '</span>');
1.356     banghart 4360:                     } else {
1.360     banghart 4361:                         # mark the file as read only
1.654     raeburn  4362:                         push(@handedback,$save_file_name);
1.367     albertel 4363: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   4364: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   4365: 			}
                   4366:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  4367: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 4368:                     }
1.686     bisitz   4369:                     $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 4370:                 }
                   4371:             }
                   4372:         }
1.654     raeburn  4373:     }
                   4374:     if (@handedback > 0) {
                   4375:         $request->print('<br />');
                   4376:         my @what = ($symb,$env{'request.course.id'},'handback');
                   4377:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   4378:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   4379:         my ($subject,$message);
                   4380:         if (scalar(@handedback) == 1) {
                   4381:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   4382:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   4383:         } else {
                   4384:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   4385:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   4386:         }
                   4387:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   4388:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   4389:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   4390:         my ($feedurl,$showsymb) =
                   4391:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   4392:         my $restitle = &Apache::lonnet::gettitle($symb);
                   4393:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   4394:         my $msgstatus =
                   4395:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   4396:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   4397:                  $restitle);
                   4398:         if ($msgstatus) {
                   4399:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   4400:         }
                   4401:     }
1.338     banghart 4402:     return;
1.337     banghart 4403: }
                   4404: 
1.418     albertel 4405: sub get_feedurl_and_symb {
                   4406:     my ($symb,$uname,$udom) = @_;
                   4407:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   4408:     $url = &Apache::lonnet::clutter($url);
                   4409:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   4410: 					$symb,$udom,$uname);
                   4411:     if ($encrypturl =~ /^yes$/i) {
                   4412: 	&Apache::lonenc::encrypted(\$url,1);
                   4413: 	&Apache::lonenc::encrypted(\$symb,1);
                   4414:     }
                   4415:     return ($url,$symb);
                   4416: }
                   4417: 
1.313     banghart 4418: sub get_submitted_files {
                   4419:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   4420:     my @files;
                   4421:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   4422:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   4423:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   4424:     	    push(@files,$file_url.$file);
                   4425:         }
                   4426:     }
                   4427:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   4428:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   4429:     }
                   4430:     return (\@files);
                   4431: }
1.322     albertel 4432: 
1.269     raeburn  4433: # ----------- Provides number of tries since last reset.
                   4434: sub get_num_tries {
                   4435:     my ($record,$last_reset,$part) = @_;
                   4436:     my $timestamp = '';
                   4437:     my $num_tries = 0;
                   4438:     if ($$record{'version'}) {
                   4439:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   4440:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   4441:                 $timestamp = $$record{$version.':timestamp'};
                   4442:                 if ($timestamp > $last_reset) {
                   4443:                     $num_tries ++;
                   4444:                 } else {
                   4445:                     last;
                   4446:                 }
                   4447:             }
                   4448:         }
                   4449:     }
                   4450:     return $num_tries;
                   4451: }
                   4452: 
                   4453: # ----------- Determine decrements required in aggregate totals 
                   4454: sub decrement_aggs {
                   4455:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   4456:     my %decrement = (
                   4457:                         attempts => 0,
                   4458:                         users => 0,
                   4459:                         correct => 0
                   4460:                     );
                   4461:     $decrement{'attempts'} = $aggtries;
                   4462:     if ($solvedstatus =~ /^correct/) {
                   4463:         $decrement{'correct'} = 1;
                   4464:     }
                   4465:     if ($aggtries == $totaltries) {
                   4466:         $decrement{'users'} = 1;
                   4467:     }
1.524     raeburn  4468:     foreach my $type (keys(%decrement)) {
1.269     raeburn  4469:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   4470:     }
                   4471:     return;
                   4472: }
                   4473: 
                   4474: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   4475: sub get_last_resets {
1.270     albertel 4476:     my ($symb,$courseid,$partids) =@_;
                   4477:     my %last_resets;
1.269     raeburn  4478:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   4479:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 4480:     my @keys;
                   4481:     foreach my $part (@{$partids}) {
                   4482: 	push(@keys,"$symb\0$part\0resettime");
                   4483:     }
                   4484:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   4485: 				     $cdom,$cname);
                   4486:     foreach my $part (@{$partids}) {
                   4487: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  4488:     }
1.270     albertel 4489:     return %last_resets;
1.269     raeburn  4490: }
                   4491: 
1.251     banghart 4492: # ----------- Handles creating versions for portfolio files as answers
                   4493: sub version_portfiles {
1.343     banghart 4494:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 4495:     my $version_parts = join('|',@$v_flag);
1.343     banghart 4496:     my @returned_keys;
1.255     banghart 4497:     my $parts = join('|', @$parts_graded);
1.277     albertel 4498:     foreach my $key (keys(%$record)) {
1.259     banghart 4499:         my $new_portfiles;
1.263     banghart 4500:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 4501:             my @versioned_portfiles;
1.367     albertel 4502:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  4503:             if (@portfiles) {
                   4504:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   4505:                                                       \@versioned_portfiles);
1.252     banghart 4506:             }
1.343     banghart 4507:             $$record{$key} = join(',',@versioned_portfiles);
                   4508:             push(@returned_keys,$key);
1.251     banghart 4509:         }
1.794     raeburn  4510:     }
                   4511:     return (@returned_keys);
1.305     banghart 4512: }
                   4513: 
1.44      ng       4514: #--------------------------------------------------------------------------------------
                   4515: #
                   4516: #-------------------------- Next few routines handles grading by section or whole class
                   4517: #
                   4518: #--- Javascript to handle grading by section or whole class
1.42      ng       4519: sub viewgrades_js {
                   4520:     my ($request) = shift;
                   4521: 
1.539     riegler  4522:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  4523:     &js_escape(\$alertmsg);
1.597     wenzelju 4524:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       4525:    function writePoint(partid,weight,point) {
1.125     ng       4526: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   4527: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       4528: 	if (point == "textval") {
1.125     ng       4529: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  4530: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4531: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       4532: 		var resetbox = false;
                   4533: 		for (var i=0; i<radioButton.length; i++) {
                   4534: 		    if (radioButton[i].checked) {
                   4535: 			textbox.value = i;
                   4536: 			resetbox = true;
                   4537: 		    }
                   4538: 		}
                   4539: 		if (!resetbox) {
                   4540: 		    textbox.value = "";
                   4541: 		}
                   4542: 		return;
                   4543: 	    }
1.109     matthew  4544: 	    if (parseFloat(point) > parseFloat(weight)) {
                   4545: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4546: 				   ") greater than the weight for the part. Accept?");
                   4547: 		if (resp == false) {
                   4548: 		    textbox.value = "";
                   4549: 		    return;
                   4550: 		}
                   4551: 	    }
1.42      ng       4552: 	    for (var i=0; i<radioButton.length; i++) {
                   4553: 		radioButton[i].checked=false;
1.109     matthew  4554: 		if (parseFloat(point) == i) {
1.42      ng       4555: 		    radioButton[i].checked=true;
                   4556: 		}
                   4557: 	    }
1.41      ng       4558: 
1.42      ng       4559: 	} else {
1.125     ng       4560: 	    textbox.value = parseFloat(point);
1.42      ng       4561: 	}
1.41      ng       4562: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4563: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 4564: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4565: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4566: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4567: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4568: 	    if (saveval != "correct") {
                   4569: 		scorename.value = point;
1.43      ng       4570: 		if (selname[0].selected != true) {
                   4571: 		    selname[0].selected = true;
                   4572: 		}
1.42      ng       4573: 	    }
                   4574: 	}
1.125     ng       4575: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       4576:     }
                   4577: 
                   4578:     function writeRadText(partid,weight) {
1.125     ng       4579: 	var selval   = document.classgrade["SELVAL_"+partid];
                   4580: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      4581:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       4582: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   4583: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       4584: 	    for (var i=0; i<radioButton.length; i++) {
                   4585: 		radioButton[i].checked=false;
                   4586: 
                   4587: 	    }
                   4588: 	    textbox.value = "";
                   4589: 
                   4590: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4591: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4592: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4593: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4594: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4595: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4596: 		if ((saveval != "correct") || override) {
1.42      ng       4597: 		    scorename.value = "";
1.125     ng       4598: 		    if (selval[1].selected) {
                   4599: 			selname[1].selected = true;
                   4600: 		    } else {
                   4601: 			selname[2].selected = true;
                   4602: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   4603: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   4604: 		    }
1.42      ng       4605: 		}
                   4606: 	    }
1.43      ng       4607: 	} else {
                   4608: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4609: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4610: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4611: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4612: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4613: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4614: 		if ((saveval != "correct") || override) {
1.125     ng       4615: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       4616: 		    selname[0].selected = true;
                   4617: 		}
                   4618: 	    }
                   4619: 	}	    
1.42      ng       4620:     }
                   4621: 
                   4622:     function changeSelect(partid,user) {
1.125     ng       4623: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4624: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       4625: 	var point  = textbox.value;
1.125     ng       4626: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       4627: 
1.109     matthew  4628: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4629: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       4630: 	    textbox.value = "";
                   4631: 	    return;
                   4632: 	}
1.109     matthew  4633: 	if (parseFloat(point) > parseFloat(weight)) {
                   4634: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4635: 			       ") greater than the weight of the part. Accept?");
                   4636: 	    if (resp == false) {
                   4637: 		textbox.value = "";
                   4638: 		return;
                   4639: 	    }
                   4640: 	}
1.42      ng       4641: 	selval[0].selected = true;
                   4642:     }
                   4643: 
                   4644:     function changeOneScore(partid,user) {
1.125     ng       4645: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4646: 	if (selval[1].selected || selval[2].selected) {
                   4647: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   4648: 	    if (selval[2].selected) {
                   4649: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   4650: 	    }
1.269     raeburn  4651:         }
1.42      ng       4652:     }
                   4653: 
                   4654:     function resetEntry(numpart) {
                   4655: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       4656: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   4657: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   4658: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   4659: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       4660: 	    for (var i=0; i<radioButton.length; i++) {
                   4661: 		radioButton[i].checked=false;
                   4662: 
                   4663: 	    }
                   4664: 	    textbox.value = "";
                   4665: 	    selval[0].selected = true;
                   4666: 
                   4667: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4668: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4669: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4670: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4671: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   4672: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   4673: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   4674: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4675: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4676: 		if (saveselval == "excused") {
1.43      ng       4677: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       4678: 		} else {
1.43      ng       4679: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       4680: 		}
                   4681: 	    }
1.41      ng       4682: 	}
1.42      ng       4683:     }
                   4684: 
1.41      ng       4685: VIEWJAVASCRIPT
1.42      ng       4686: }
                   4687: 
1.44      ng       4688: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       4689: sub viewgrades {
1.608     www      4690:     my ($request,$symb) = @_;
1.745     raeburn  4691:     my ($is_tool,$toolsymb);
                   4692:     if ($symb =~ /ext\.tool$/) {
                   4693:         $is_tool = 1;
                   4694:         $toolsymb = $symb;
                   4695:     }
1.42      ng       4696:     &viewgrades_js($request);
1.41      ng       4697: 
1.168     albertel 4698:     #need to make sure we have the correct data for later EXT calls, 
                   4699:     #thus invalidate the cache
                   4700:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4701:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4702:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4703:     &Apache::lonnet::clear_EXT_cache_status();
                   4704: 
1.398     albertel 4705:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       4706: 
                   4707:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 4708:     $result.=&jscriptNform($symb);
1.41      ng       4709: 
1.44      ng       4710:     #beginning of class grading form
1.442     banghart 4711:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       4712:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 4713: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       4714: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 4715: 	&build_section_inputs().
1.442     banghart 4716: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       4717: 
1.738     raeburn  4718:     #retrieve selected groups
                   4719:     my (@groups,$group_display);
                   4720:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   4721:     if (grep(/^all$/,@groups)) {
                   4722:         @groups = ('all');
                   4723:     } elsif (grep(/^none$/,@groups)) {
                   4724:         @groups = ('none');
                   4725:     } elsif (@groups > 0) {
                   4726:         $group_display = join(', ',@groups);
                   4727:     }
                   4728: 
                   4729:     my ($common_header,$specific_header,@sections,$section_display);
1.780     raeburn  4730:     if ($env{'request.course.sec'} ne '') {
                   4731:         @sections = ($env{'request.course.sec'});
                   4732:     } else {
                   4733:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   4734:     }
                   4735: 
                   4736: # Check if Save button should be usable
                   4737:     my $disabled = ' disabled="disabled"';
                   4738:     if ($perm{'mgr'}) {
                   4739:         if (grep(/^all$/,@sections)) {
                   4740:             undef($disabled);
                   4741:         } else {
                   4742:             foreach my $sec (@sections) {
                   4743:                 if (&canmodify($sec)) {
                   4744:                     undef($disabled);
                   4745:                     last;
                   4746:                 }
                   4747:             }
                   4748:         }
                   4749:     }
1.738     raeburn  4750:     if (grep(/^all$/,@sections)) {
                   4751:         @sections = ('all');
                   4752:         if ($group_display) {
                   4753:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4754:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4755:         } elsif (grep(/^none$/,@groups)) {
                   4756:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4757:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4758:         } else {
                   4759: 	    $common_header = &mt('Assign Common Grade to Class');
                   4760:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4761:         }
                   4762:     } elsif (grep(/^none$/,@sections)) {
                   4763:         @sections = ('none');
                   4764:         if ($group_display) {
                   4765:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4766:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4767:         } elsif (grep(/^none$/,@groups)) {
                   4768:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4769:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4770:         } else {
                   4771:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4772: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4773:         }
                   4774:     } else {
                   4775:         $section_display = join (", ",@sections);
                   4776:         if ($group_display) {
                   4777:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4778:                                  $section_display,$group_display);
                   4779:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4780:                                    $section_display,$group_display);
                   4781:         } elsif (grep(/^none$/,@groups)) {
                   4782:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4783:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4784:         } else {
                   4785:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4786: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4787:         }
                   4788:     }
                   4789:     my %submit_types = &substatus_options();
                   4790:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4791: 
                   4792:     if ($env{'form.submitonly'} eq 'all') {
                   4793:         $result.= '<h3>'.$common_header.'</h3>';
                   4794:     } else {
1.745     raeburn  4795:         my $text;
                   4796:         if ($is_tool) {
                   4797:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4798:         } else {
                   4799:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4800:         }
                   4801:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 4802:     }
1.738     raeburn  4803:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4804:     #radio buttons/text box for assigning points for a section or class.
                   4805:     #handles different parts of a problem
1.582     raeburn  4806:     my $res_error;
                   4807:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4808:     if ($res_error) {
                   4809:         return &navmap_errormsg();
                   4810:     }
1.42      ng       4811:     my %weight = ();
                   4812:     my $ctsparts = 0;
1.45      ng       4813:     my %seen = ();
1.745     raeburn  4814:     my @part_response_id;
                   4815:     if ($is_tool) {
                   4816:         @part_response_id = ([0,'']);
                   4817:     } else {
                   4818:         @part_response_id = &flatten_responseType($responseType);
                   4819:     }
1.375     albertel 4820:     foreach my $part_response_id (@part_response_id) {
                   4821:     	my ($partid,$respid) = @{ $part_response_id };
                   4822: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4823: 	next if $seen{$partid};
                   4824: 	$seen{$partid}++;
1.42      ng       4825: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4826: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4827: 
1.324     albertel 4828: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4829: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4830: 	my $ctr = 0;
1.42      ng       4831: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4832: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4833: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4834: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4835: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4836: 	    $ctr++;
                   4837: 	}
1.485     albertel 4838: 	$radio.='</tr></table>';
                   4839: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4840: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4841: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4842: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   4843:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4844:             '<select name="SELVAL_'.$partid.'" '.
                   4845:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   4846:                 $weight{$partid}.')"> '.
1.401     albertel 4847: 	    '<option selected="selected"> </option>'.
1.485     albertel 4848: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4849: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4850: 	    '</select></td>'.
                   4851:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4852: 	$line.='<input type="hidden" name="partid_'.
                   4853: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4854: 	$line.='<input type="hidden" name="weight_'.
                   4855: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4856: 
                   4857: 	$result.=
                   4858: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4859: 	    '<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 4860: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4861: 	$ctsparts++;
1.41      ng       4862:     }
1.474     albertel 4863:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4864: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4865:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4866: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4867: 
1.44      ng       4868:     #table listing all the students in a section/class
                   4869:     #header of table
1.738     raeburn  4870:     if ($env{'form.submitonly'} eq 'all') {
                   4871:         $result.= '<h3>'.$specific_header.'</h3>';
                   4872:     } else {
1.745     raeburn  4873:         my $text;
                   4874:         if ($is_tool) {
                   4875:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4876:         } else {
                   4877:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4878:         }
                   4879:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  4880:     }
                   4881:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4882: 	      &Apache::loncommon::start_data_table_header_row().
                   4883: 	      '<th>'.&mt('No.').'</th>'.
                   4884: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4885:     my $partserror;
                   4886:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4887:     if ($partserror) {
                   4888:         return &navmap_errormsg();
                   4889:     }
1.324     albertel 4890:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4891:     my @partids = ();
1.41      ng       4892:     foreach my $part (@parts) {
1.745     raeburn  4893: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  4894:         my $narrowtext = &mt('Tries');
                   4895: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  4896: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 4897: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4898:         push(@partids,$partid);
1.628     www      4899: #
                   4900: # FIXME: Looks like $display looks at English text
                   4901: #
1.324     albertel 4902: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4903: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4904: 	    $result.='<th>'.
1.697     bisitz   4905: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   4906: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4907: 	    next;
1.485     albertel 4908: 	    
1.207     albertel 4909: 	} else {
1.485     albertel 4910: 	    if ($display =~ /Problem Status/) {
                   4911: 		my $grade_status_mt = &mt('Grade Status');
                   4912: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4913: 	    }
                   4914: 	    my $part_mt = &mt('Part:');
                   4915: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4916: 	}
1.485     albertel 4917: 
1.474     albertel 4918: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4919:     }
1.474     albertel 4920:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4921: 
1.270     albertel 4922:     my %last_resets = 
                   4923: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4924: 
1.41      ng       4925:     #get info for each student
1.44      ng       4926:     #list all the students - with points and grade status
1.738     raeburn  4927:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4928:     my $ctr = 0;
1.294     albertel 4929:     foreach (sort 
                   4930: 	     {
                   4931: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4932: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4933: 		 }
                   4934: 		 return $a cmp $b;
                   4935: 	     } (keys(%$fullname))) {
1.324     albertel 4936: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  4937: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4938:     }
1.474     albertel 4939:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4940:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.780     raeburn  4941:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   4942: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4943:     if ($ctr == 0) {
1.442     banghart 4944:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4945:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4946:                 '<span class="LC_warning">';
                   4947:         if ($env{'form.submitonly'} eq 'all') {
                   4948:             if (grep(/^all$/,@sections)) {
                   4949:                 if (grep(/^all$/,@groups)) {
                   4950:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4951:                                    $stu_status);
                   4952:                 } elsif (grep(/^none$/,@groups)) {
                   4953:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4954:                                    $stu_status); 
                   4955:                 } else {
                   4956:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4957:                                    $group_display,$stu_status);
                   4958:                 }
                   4959:             } elsif (grep(/^none$/,@sections)) {
                   4960:                 if (grep(/^all$/,@groups)) {
                   4961:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4962:                                    $stu_status);
                   4963:                 } elsif (grep(/^none$/,@groups)) {
                   4964:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4965:                                    $stu_status);
                   4966:                 } else {
                   4967:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4968:                                    $group_display,$stu_status);
                   4969:                 }
                   4970:             } else {
                   4971:                 if (grep(/^all$/,@groups)) {
                   4972:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4973:                                    $section_display,$stu_status);
                   4974:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4975:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4976:                                    $section_display,$stu_status);
                   4977:                 } else {
                   4978:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4979:                                    $section_display,$group_display,$stu_status);
                   4980:                 }
                   4981:             }
                   4982:         } else {
                   4983:             if (grep(/^all$/,@sections)) {
                   4984:                 if (grep(/^all$/,@groups)) {
                   4985:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4986:                                    $stu_status,$submission_status);
                   4987:                 } elsif (grep(/^none$/,@groups)) {
                   4988:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4989:                                    $stu_status,$submission_status);
                   4990:                 } else {
                   4991:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4992:                                    $group_display,$stu_status,$submission_status);
                   4993:                 }
                   4994:             } elsif (grep(/^none$/,@sections)) {
                   4995:                 if (grep(/^all$/,@groups)) {
                   4996:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4997:                                    $stu_status,$submission_status);
                   4998:                 } elsif (grep(/^none$/,@groups)) {
                   4999:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   5000:                                    $stu_status,$submission_status);
                   5001:                 } else {
                   5002:                     $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.',
                   5003:                                    $group_display,$stu_status,$submission_status);
                   5004:                 }
                   5005:             } else {
                   5006:                 if (grep(/^all$/,@groups)) {
                   5007: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   5008: 	                           $section_display,$stu_status,$submission_status);
                   5009:                 } elsif (grep(/^none$/,@groups)) {
                   5010:                     $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.',
                   5011:                                    $section_display,$stu_status,$submission_status);
                   5012:                 } else {
                   5013:                     $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.',
                   5014:                                    $section_display,$group_display,$stu_status,$submission_status);
                   5015:                 }
                   5016:             }
                   5017:         }
                   5018: 	$result .= '</span><br />';
1.96      albertel 5019:     }
1.41      ng       5020:     return $result;
                   5021: }
                   5022: 
1.738     raeburn  5023: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       5024: sub viewstudentgrade {
1.745     raeburn  5025:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       5026:     my ($uname,$udom) = split(/:/,$student);
                   5027:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  5028:     my $submitonly = $env{'form.submitonly'};
                   5029:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   5030:         my %partstatus = ();
                   5031:         if (ref($parts) eq 'ARRAY') {
                   5032:             foreach my $apart (@{$parts}) {
                   5033:                 my ($part,$type) = &split_part_type($apart);
                   5034:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   5035:                 $status = 'nothing' if ($status eq '');
                   5036:                 $partstatus{$part}      = $status;
                   5037:                 my $subkey = "resource.$part.submitted_by";
                   5038:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   5039:             }
                   5040:             my $submitted = 0;
                   5041:             my $graded = 0;
                   5042:             my $incorrect = 0;
                   5043:             foreach my $key (keys(%partstatus)) {
                   5044:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   5045:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   5046:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   5047: 
                   5048:                 my $partid = (split(/\./,$key))[1];
                   5049:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   5050:                     $submitted = 0;
                   5051:                 }
                   5052:             }
                   5053:             return if (!$submitted && ($submitonly eq 'yes' ||
                   5054:                                        $submitonly eq 'incorrect' ||
                   5055:                                        $submitonly eq 'graded'));
                   5056:             return if (!$graded && ($submitonly eq 'graded'));
                   5057:             return if (!$incorrect && $submitonly eq 'incorrect');
                   5058:         }
                   5059:     }
                   5060:     if ($submitonly eq 'queued') {
                   5061:         my ($cdom,$cnum) = split(/_/,$courseid);
                   5062:         my %queue_status =
                   5063:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   5064:                                                     $udom,$uname);
                   5065:         return if (!defined($queue_status{'gradingqueue'}));
                   5066:     }
                   5067:     $$ctr++;
                   5068:     my %aggregates = ();
1.474     albertel 5069:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  5070: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   5071: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       5072: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 5073: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 5074: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 5075:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 5076:     foreach my $apart (@$parts) {
                   5077: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       5078: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 5079:         $result.='<td align="center">';
1.269     raeburn  5080:         my ($aggtries,$totaltries);
                   5081:         unless (exists($aggregates{$part})) {
1.270     albertel 5082: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   5083: 	    $aggtries = $totaltries;
1.269     raeburn  5084:             if ($$last_resets{$part}) {  
1.270     albertel 5085:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   5086: 					   $part);
                   5087:             }
1.269     raeburn  5088:             $result.='<input type="hidden" name="'.
                   5089:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   5090:             $result.='<input type="hidden" name="'.
                   5091:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   5092:             $aggregates{$part} = 1;
                   5093:         }
1.41      ng       5094: 	if ($type eq 'awarded') {
1.320     albertel 5095: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       5096: 	    $result.='<input type="hidden" name="'.
1.89      albertel 5097: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 5098: 	    $result.='<input type="text" name="'.
1.89      albertel 5099: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   5100:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       5101: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       5102: 	} elsif ($type eq 'solved') {
                   5103: 	    my ($status,$foo)=split(/_/,$score,2);
                   5104: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 5105: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 5106: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 5107: 	    $result.='&nbsp;<select name="'.
1.89      albertel 5108: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   5109:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 5110: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   5111: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   5112: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       5113: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       5114: 	} else {
                   5115: 	    $result.='<input type="hidden" name="'.
                   5116: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   5117: 		    "\n";
1.233     albertel 5118: 	    $result.='<input type="text" name="'.
1.122     ng       5119: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   5120: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       5121: 	}
                   5122:     }
1.474     albertel 5123:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       5124:     return $result;
1.38      ng       5125: }
                   5126: 
1.44      ng       5127: #--- change scores for all the students in a section/class
                   5128: #    record does not get update if unchanged
1.38      ng       5129: sub editgrades {
1.608     www      5130:     my ($request,$symb) = @_;
1.745     raeburn  5131:     my $toolsymb;
                   5132:     if ($symb =~ /ext\.tool$/) {
                   5133:         $toolsymb = $symb;
                   5134:     }
1.41      ng       5135: 
1.433     banghart 5136:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 5137:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  5138:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       5139: 
1.477     albertel 5140:     my $result= &Apache::loncommon::start_data_table().
                   5141: 	&Apache::loncommon::start_data_table_header_row().
                   5142: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   5143: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       5144:     my %scoreptr = (
                   5145: 		    'correct'  =>'correct_by_override',
                   5146: 		    'incorrect'=>'incorrect_by_override',
                   5147: 		    'excused'  =>'excused',
                   5148: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  5149:                     'credited' =>'credit_attempted',
1.43      ng       5150: 		    'nothing'  => '',
                   5151: 		    );
1.257     albertel 5152:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       5153: 
1.44      ng       5154:     my (@partid);
                   5155:     my %weight = ();
1.54      albertel 5156:     my %columns = ();
1.44      ng       5157:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 5158: 
1.582     raeburn  5159:     my $partserror;
                   5160:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   5161:     if ($partserror) {
                   5162:         return &navmap_errormsg();
                   5163:     }
1.54      albertel 5164:     my $header;
1.257     albertel 5165:     while ($ctr < $env{'form.totalparts'}) {
                   5166: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  5167: 	push(@partid,$partid);
1.257     albertel 5168: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       5169: 	$ctr++;
1.54      albertel 5170:     }
1.324     albertel 5171:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  5172:     my $totcolspan = 0;
1.54      albertel 5173:     foreach my $partid (@partid) {
1.478     albertel 5174: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   5175: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 5176: 	$columns{$partid}=2;
                   5177: 	foreach my $stores (@parts) {
                   5178: 	    my ($part,$type) = &split_part_type($stores);
                   5179: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   5180: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  5181: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  5182: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  5183:             my $narrowtext = &mt('Tries');
                   5184: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   5185: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   5186: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 5187: 	    $columns{$partid}+=2;
                   5188: 	}
1.748     raeburn  5189:         $totcolspan += $columns{$partid};
1.54      albertel 5190:     }
                   5191:     foreach my $partid (@partid) {
1.324     albertel 5192: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 5193: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   5194: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   5195: 	    '</th>';
1.54      albertel 5196: 
1.44      ng       5197:     }
1.477     albertel 5198:     $result .= &Apache::loncommon::end_data_table_header_row().
                   5199: 	&Apache::loncommon::start_data_table_header_row().
                   5200: 	$header.
                   5201: 	&Apache::loncommon::end_data_table_header_row();
                   5202:     my @noupdate;
1.126     ng       5203:     my ($updateCtr,$noupdateCtr) = (1,1);
1.786     raeburn  5204:     my ($got_types,%queueable);
1.257     albertel 5205:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   5206: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 5207: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       5208: 	my %newrecord;
                   5209: 	my $updateflag = 0;
1.108     albertel 5210: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  5211: 	my $canmodify = &canmodify($usec);
                   5212: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   5213: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   5214: 	if (!$canmodify) {
1.477     albertel 5215: 	    push(@noupdate,
1.748     raeburn  5216: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   5217: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 5218: 	    next;
                   5219: 	}
1.269     raeburn  5220:         my %aggregate = ();
                   5221:         my $aggregateflag = 0;
1.281     albertel 5222: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       5223: 	foreach (@partid) {
1.257     albertel 5224: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 5225: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   5226: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 5227: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   5228: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 5229: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   5230: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       5231: 	    my $score;
                   5232: 	    if ($partial eq '') {
1.257     albertel 5233: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       5234: 	    } elsif ($partial > 0) {
                   5235: 		$score = 'correct_by_override';
                   5236: 	    } elsif ($partial == 0) {
                   5237: 		$score = 'incorrect_by_override';
                   5238: 	    }
1.257     albertel 5239: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       5240: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   5241: 
1.292     albertel 5242: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   5243: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5244: 	    if ($dropMenu eq 'reset status' &&
                   5245: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 5246: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       5247: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   5248: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 5249: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       5250: 		$updateflag = 1;
1.269     raeburn  5251:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   5252:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   5253:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   5254:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   5255:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5256:                     $aggregateflag = 1;
                   5257:                 }
1.139     albertel 5258: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   5259: 		$updateflag = 1;
                   5260: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   5261: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   5262: 		$rec_update++;
1.125     ng       5263: 	    }
                   5264: 
1.93      albertel 5265: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       5266: 		'<td align="center">'.$awarded.
                   5267: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 5268: 
1.54      albertel 5269: 
                   5270: 	    my $partid=$_;
                   5271: 	    foreach my $stores (@parts) {
                   5272: 		my ($part,$type) = &split_part_type($stores);
                   5273: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   5274: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 5275: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   5276: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 5277: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   5278: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 5279: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 5280: 		    $updateflag=1;
                   5281: 		}
1.93      albertel 5282: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 5283: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   5284: 	    }
1.44      ng       5285: 	}
1.477     albertel 5286: 	$line.="\n";
1.301     albertel 5287: 
                   5288: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5289: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5290: 
1.44      ng       5291: 	if ($updateflag) {
                   5292: 	    $count++;
1.257     albertel 5293: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 5294: 				    $udom,$uname);
1.301     albertel 5295: 
                   5296: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   5297: 					      $cnum,$udom,$uname)) {
                   5298: 		# need to figure out if should be in queue.
                   5299: 		my %record =  
                   5300: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   5301: 					     $udom,$uname);
                   5302: 		my $all_graded = 1;
                   5303: 		my $none_graded = 1;
1.786     raeburn  5304:                 unless ($got_types) {
                   5305:                     my $error;
                   5306:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   5307:                     unless ($error) {
                   5308:                         foreach my $part (@parts) {
                   5309:                             if (ref($resptype->{$part}) eq 'HASH') {
                   5310:                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   5311:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   5312:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   5313:                                         $queueable{$part} = 1;
                   5314:                                         last;
                   5315:                                     }
                   5316:                                 }
                   5317:                             }
                   5318:                         }
                   5319:                     }
                   5320:                     $got_types = 1;
                   5321:                 }
1.301     albertel 5322: 		foreach my $part (@parts) {
1.786     raeburn  5323:                     if ($queueable{$part}) {
                   5324: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   5325: 			    $all_graded = 0;
                   5326: 		        } else {
                   5327: 			    $none_graded = 0;
                   5328: 		        }
1.301     albertel 5329: 		    }
1.786     raeburn  5330:                 }
1.301     albertel 5331: 		if ($all_graded || $none_graded) {
                   5332: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   5333: 							   $symb,$cdom,$cnum,
                   5334: 							   $udom,$uname);
                   5335: 		}
                   5336: 	    }
                   5337: 
1.477     albertel 5338: 	    $result.=&Apache::loncommon::start_data_table_row().
                   5339: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   5340: 		&Apache::loncommon::end_data_table_row();
1.126     ng       5341: 	    $updateCtr++;
1.93      albertel 5342: 	} else {
1.477     albertel 5343: 	    push(@noupdate,
                   5344: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       5345: 	    $noupdateCtr++;
1.44      ng       5346: 	}
1.269     raeburn  5347:         if ($aggregateflag) {
                   5348:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 5349: 				  $cdom,$cnum);
1.269     raeburn  5350:         }
1.93      albertel 5351:     }
1.477     albertel 5352:     if (@noupdate) {
1.748     raeburn  5353:         my $numcols=$totcolspan+2;
1.477     albertel 5354: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 5355: 	    '<td align="center" colspan="'.$numcols.'">'.
                   5356: 	    &mt('No Changes Occurred For the Students Below').
                   5357: 	    '</td>'.
1.477     albertel 5358: 	    &Apache::loncommon::end_data_table_row();
                   5359: 	foreach my $line (@noupdate) {
                   5360: 	    $result.=
                   5361: 		&Apache::loncommon::start_data_table_row().
                   5362: 		$line.
                   5363: 		&Apache::loncommon::end_data_table_row();
                   5364: 	}
1.44      ng       5365:     }
1.614     www      5366:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 5367:     my $msg = '<p><b>'.
                   5368: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   5369: 	    $rec_update,$count).'</b><br />'.
                   5370: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   5371: 	'</b></p>';
1.44      ng       5372:     return $title.$msg.$result;
1.5       albertel 5373: }
1.54      albertel 5374: 
                   5375: sub split_part_type {
                   5376:     my ($partstr) = @_;
                   5377:     my ($temp,@allparts)=split(/_/,$partstr);
                   5378:     my $type=pop(@allparts);
1.439     albertel 5379:     my $part=join('_',@allparts);
1.54      albertel 5380:     return ($part,$type);
                   5381: }
                   5382: 
1.44      ng       5383: #------------- end of section for handling grading by section/class ---------
                   5384: #
                   5385: #----------------------------------------------------------------------------
                   5386: 
1.5       albertel 5387: 
1.44      ng       5388: #----------------------------------------------------------------------------
                   5389: #
                   5390: #-------------------------- Next few routines handles grading by csv upload
                   5391: #
                   5392: #--- Javascript to handle csv upload
1.27      albertel 5393: sub csvupload_javascript_reverse_associate {
1.743     raeburn  5394:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5395:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5396:   &js_escape(\$error1);
                   5397:   &js_escape(\$error2);
1.27      albertel 5398:   return(<<ENDPICK);
                   5399:   function verify(vf) {
                   5400:     var foundsomething=0;
                   5401:     var founduname=0;
1.243     albertel 5402:     var foundID=0;
1.743     raeburn  5403:     var foundclicker=0;
1.27      albertel 5404:     for (i=0;i<=vf.nfields.value;i++) {
                   5405:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5406:       if (i==0 && tw!=0) { foundID=1; }
                   5407:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  5408:       if (i==2 && tw!=0) { foundclicker=1; }
                   5409:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 5410:     }
1.743     raeburn  5411:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 5412: 	alert('$error1');
                   5413: 	return;
1.27      albertel 5414:     }
                   5415:     if (foundsomething==0) {
1.246     albertel 5416: 	alert('$error2');
                   5417: 	return;
1.27      albertel 5418:     }
                   5419:     vf.submit();
                   5420:   }
                   5421:   function flip(vf,tf) {
                   5422:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5423:     var i;
                   5424:     for (i=0;i<=vf.nfields.value;i++) {
                   5425:       //can not pick the same destination field for both name and domain
                   5426:       if (((i ==0)||(i ==1)) && 
                   5427:           ((tf==0)||(tf==1)) && 
                   5428:           (i!=tf) &&
                   5429:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5430:         eval('vf.f'+i+'.selectedIndex=0;')
                   5431:       }
                   5432:     }
                   5433:   }
                   5434: ENDPICK
                   5435: }
                   5436: 
                   5437: sub csvupload_javascript_forward_associate {
1.743     raeburn  5438:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 5439:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  5440:   &js_escape(\$error1);
                   5441:   &js_escape(\$error2);
1.27      albertel 5442:   return(<<ENDPICK);
                   5443:   function verify(vf) {
                   5444:     var foundsomething=0;
                   5445:     var founduname=0;
1.243     albertel 5446:     var foundID=0;
1.743     raeburn  5447:     var foundclicker=0;
1.27      albertel 5448:     for (i=0;i<=vf.nfields.value;i++) {
                   5449:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 5450:       if (tw==1) { foundID=1; }
                   5451:       if (tw==2) { founduname=1; }
1.745     raeburn  5452:       if (tw==3) { foundclicker=1; }
1.743     raeburn  5453:       if (tw>4) { foundsomething=1; }
1.27      albertel 5454:     }
1.743     raeburn  5455:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 5456: 	alert('$error1');
                   5457: 	return;
1.27      albertel 5458:     }
                   5459:     if (foundsomething==0) {
1.246     albertel 5460: 	alert('$error2');
                   5461: 	return;
1.27      albertel 5462:     }
                   5463:     vf.submit();
                   5464:   }
                   5465:   function flip(vf,tf) {
                   5466:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   5467:     var i;
                   5468:     //can not pick the same destination field twice
                   5469:     for (i=0;i<=vf.nfields.value;i++) {
                   5470:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   5471:         eval('vf.f'+i+'.selectedIndex=0;')
                   5472:       }
                   5473:     }
                   5474:   }
                   5475: ENDPICK
                   5476: }
                   5477: 
1.26      albertel 5478: sub csvuploadmap_header {
1.324     albertel 5479:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       5480:     my $javascript;
1.257     albertel 5481:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       5482: 	$javascript=&csvupload_javascript_reverse_associate();
                   5483:     } else {
                   5484: 	$javascript=&csvupload_javascript_forward_associate();
                   5485:     }
1.45      ng       5486: 
1.418     albertel 5487:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      5488:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   5489:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   5490:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   5491:     my $reverse=&mt("Reverse Association");
1.41      ng       5492:     $request->print(<<ENDPICK);
1.632     www      5493: <br />
                   5494: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 5495: <input type="hidden" name="associate"  value="" />
                   5496: <input type="hidden" name="phase"      value="three" />
                   5497: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 5498: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   5499: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 5500: <input type="hidden" name="upfile_associate" 
1.257     albertel 5501:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 5502: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 5503: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 5504: <hr />
                   5505: ENDPICK
1.597     wenzelju 5506:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       5507:     return '';
1.26      albertel 5508: 
                   5509: }
                   5510: 
                   5511: sub csvupload_fields {
1.582     raeburn  5512:     my ($symb,$errorref) = @_;
1.745     raeburn  5513:     my $toolsymb;
                   5514:     if ($symb =~ /ext\.tool$/) {
                   5515:         $toolsymb = $symb;
                   5516:     }
1.582     raeburn  5517:     my (@parts) = &getpartlist($symb,$errorref);
                   5518:     if (ref($errorref)) {
                   5519:         if ($$errorref) {
                   5520:             return;
                   5521:         }
                   5522:     }
                   5523: 
1.556     weissno  5524:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 5525: 		['username','Student Username'],
1.743     raeburn  5526: 		['clicker','Clicker ID'],
1.243     albertel 5527: 		['domain','Student Domain']);
1.324     albertel 5528:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       5529:     foreach my $part (sort(@parts)) {
                   5530: 	my @datum;
1.745     raeburn  5531: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       5532: 	my $name=$part;
1.745     raeburn  5533: 	if (!$display) { $display = $name; }
1.41      ng       5534: 	@datum=($name,$display);
1.244     albertel 5535: 	if ($name=~/^stores_(.*)_awarded/) {
                   5536: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   5537: 	}
1.41      ng       5538: 	push(@fields,\@datum);
                   5539:     }
                   5540:     return (@fields);
1.26      albertel 5541: }
                   5542: 
                   5543: sub csvuploadmap_footer {
1.41      ng       5544:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   5545:     my $buttontext = &mt('Assign Grades');
1.41      ng       5546:     $request->print(<<ENDPICK);
1.26      albertel 5547: </table>
                   5548: <input type="hidden" name="nfields" value="$i" />
                   5549: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   5550: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 5551: </form>
                   5552: ENDPICK
                   5553: }
                   5554: 
1.283     albertel 5555: sub checkforfile_js {
1.638     www      5556:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  5557:     &js_escape(\$alertmsg);
1.597     wenzelju 5558:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       5559:     function checkUpload(formname) {
                   5560: 	if (formname.upfile.value == "") {
1.539     riegler  5561: 	    alert("$alertmsg");
1.86      ng       5562: 	    return false;
                   5563: 	}
                   5564: 	formname.submit();
                   5565:     }
                   5566: CSVFORMJS
1.283     albertel 5567:     return $result;
                   5568: }
                   5569: 
                   5570: sub upcsvScores_form {
1.608     www      5571:     my ($request,$symb) = @_;
1.283     albertel 5572:     if (!$symb) {return '';}
                   5573:     my $result=&checkforfile_js();
1.632     www      5574:     $result.=&Apache::loncommon::start_data_table().
                   5575:              &Apache::loncommon::start_data_table_header_row().
                   5576:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   5577:              &Apache::loncommon::end_data_table_header_row().
                   5578:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      5579:     my $upload=&mt("Upload Scores");
1.86      ng       5580:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 5581:     my $ignore=&mt('Ignore First Line');
1.418     albertel 5582:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       5583:     $result.=<<ENDUPFORM;
1.106     albertel 5584: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       5585: <input type="hidden" name="symb" value="$symb" />
                   5586: <input type="hidden" name="command" value="csvuploadmap" />
                   5587: $upfile_select
1.589     bisitz   5588: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       5589: </form>
                   5590: ENDUPFORM
1.370     www      5591:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      5592:                            &mt("How do I create a CSV file from a spreadsheet")).
                   5593:              '</td>'.
                   5594:             &Apache::loncommon::end_data_table_row().
                   5595:             &Apache::loncommon::end_data_table();
1.86      ng       5596:     return $result;
                   5597: }
                   5598: 
                   5599: 
1.26      albertel 5600: sub csvuploadmap {
1.768     raeburn  5601:     my ($request,$symb) = @_;
1.41      ng       5602:     if (!$symb) {return '';}
1.72      ng       5603: 
1.41      ng       5604:     my $datatoken;
1.257     albertel 5605:     if (!$env{'form.datatoken'}) {
1.41      ng       5606: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 5607:     } else {
1.742     raeburn  5608: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5609:         if ($datatoken ne '') {
                   5610: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5611:         }
1.26      albertel 5612:     }
1.41      ng       5613:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 5614:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       5615:     my ($i,$keyfields);
                   5616:     if (@records) {
1.582     raeburn  5617:         my $fieldserror;
                   5618: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   5619:         if ($fieldserror) {
                   5620:             $request->print(&navmap_errormsg());
                   5621:             return;
                   5622:         }
1.257     albertel 5623: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       5624: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   5625: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   5626: 							  \@fields);
                   5627: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   5628: 	    chop($keyfields);
                   5629: 	} else {
                   5630: 	    unshift(@fields,['none','']);
                   5631: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   5632: 							    \@fields);
1.311     banghart 5633:             foreach my $rec (@records) {
                   5634:                 my %temp = &Apache::loncommon::record_sep($rec);
                   5635:                 if (%temp) {
                   5636:                     $keyfields=join(',',sort(keys(%temp)));
                   5637:                     last;
                   5638:                 }
                   5639:             }
1.41      ng       5640: 	}
                   5641:     }
                   5642:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       5643: 
1.41      ng       5644:     return '';
1.27      albertel 5645: }
                   5646: 
1.246     albertel 5647: sub csvuploadoptions {
1.608     www      5648:     my ($request,$symb)= @_;
1.632     www      5649:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 5650:     $request->print(<<ENDPICK);
                   5651: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   5652: <input type="hidden" name="command"    value="csvuploadassign" />
                   5653: <p>
                   5654: <label>
                   5655:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      5656:    $overwrite
1.246     albertel 5657: </label>
                   5658: </p>
                   5659: ENDPICK
                   5660:     my %fields=&get_fields();
                   5661:     if (!defined($fields{'domain'})) {
1.257     albertel 5662: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      5663: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 5664:     }
1.257     albertel 5665:     foreach my $key (sort(keys(%env))) {
1.246     albertel 5666: 	if ($key !~ /^form\.(.*)$/) { next; }
                   5667: 	my $cleankey=$1;
                   5668: 	if ($cleankey eq 'command') { next; }
                   5669: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 5670: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 5671:     }
                   5672:     # FIXME do a check for any duplicated user ids...
                   5673:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   5674:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 5675: <hr /></form>'."\n");
1.246     albertel 5676:     return '';
                   5677: }
                   5678: 
                   5679: sub get_fields {
                   5680:     my %fields;
1.257     albertel 5681:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   5682:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   5683: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   5684: 	    if ($env{'form.f'.$i} ne 'none') {
                   5685: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       5686: 	    }
                   5687: 	} else {
1.257     albertel 5688: 	    if ($env{'form.f'.$i} ne 'none') {
                   5689: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       5690: 	    }
                   5691: 	}
1.27      albertel 5692:     }
1.246     albertel 5693:     return %fields;
                   5694: }
                   5695: 
                   5696: sub csvuploadassign {
1.766     raeburn  5697:     my ($request,$symb) = @_;
1.246     albertel 5698:     if (!$symb) {return '';}
1.345     bowersj2 5699:     my $error_msg = '';
1.742     raeburn  5700:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5701:     if ($datatoken ne '') { 
                   5702:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5703:     }
1.246     albertel 5704:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   5705:     my %fields=&get_fields();
1.257     albertel 5706:     my $courseid=$env{'request.course.id'};
1.97      albertel 5707:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 5708:     my @notallowed;
1.41      ng       5709:     my @skipped;
1.657     raeburn  5710:     my @warnings;
1.41      ng       5711:     my $countdone=0;
                   5712:     foreach my $grade (@gradedata) {
                   5713: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 5714: 	my $domain;
                   5715: 	if ($entries{$fields{'domain'}}) {
                   5716: 	    $domain=$entries{$fields{'domain'}};
                   5717: 	} else {
1.257     albertel 5718: 	    $domain=$env{'form.default_domain'};
1.246     albertel 5719: 	}
1.243     albertel 5720: 	$domain=~s/\s//g;
1.41      ng       5721: 	my $username=$entries{$fields{'username'}};
1.160     albertel 5722: 	$username=~s/\s//g;
1.243     albertel 5723: 	if (!$username) {
                   5724: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 5725: 	    $id=~s/\s//g;
1.737     raeburn  5726:             if ($id ne '') {
                   5727: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   5728: 	        $username=$ids{$id};
                   5729:             } else {
                   5730:                 if ($entries{$fields{'clicker'}}) {
                   5731:                     my $clicker = $entries{$fields{'clicker'}};
                   5732:                     $clicker=~s/\s//g;
                   5733:                     if ($clicker ne '') {
                   5734:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   5735:                         if ($clickers{$clicker} ne '') {  
                   5736:                             my $match = 0;
                   5737:                             my @inclass;
                   5738:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   5739:                                 if (exists($$classlist{"$poss:$domain"})) {
                   5740:                                     $username = $poss;
                   5741:                                     push(@inclass,$poss);
                   5742:                                     $match ++;
                   5743:                                     
                   5744:                                 }
                   5745:                             }
                   5746:                             if ($match > 1) {
                   5747:                                 undef($username); 
                   5748:                                 $request->print('<p class="LC_warning">'.
                   5749:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   5750:                                                 $clicker,join(', ',@inclass)).'</p>');
                   5751:                             }
                   5752:                         }
                   5753:                     }
                   5754:                 }
                   5755:             }
1.243     albertel 5756: 	}
1.41      ng       5757: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 5758: 	    my $id=$entries{$fields{'ID'}};
                   5759: 	    $id=~s/\s//g;
1.737     raeburn  5760:             my $clicker = $entries{$fields{'clicker'}};
                   5761:             $clicker=~s/\s//g;
                   5762:             if ($clicker) {
                   5763:                 push(@skipped,"$clicker:$domain");
                   5764: 	    } elsif ($id) {
1.247     albertel 5765: 		push(@skipped,"$id:$domain");
                   5766: 	    } else {
                   5767: 		push(@skipped,"$username:$domain");
                   5768: 	    }
1.41      ng       5769: 	    next;
                   5770: 	}
1.108     albertel 5771: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 5772: 	if (!&canmodify($usec)) {
                   5773: 	    push(@notallowed,"$username:$domain");
                   5774: 	    next;
                   5775: 	}
1.244     albertel 5776: 	my %points;
1.41      ng       5777: 	my %grades;
                   5778: 	foreach my $dest (keys(%fields)) {
1.244     albertel 5779: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   5780: 		$dest eq 'domain') { next; }
                   5781: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   5782: 	    if ($dest=~/stores_(.*)_points/) {
                   5783: 		my $part=$1;
                   5784: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   5785: 					      $symb,$domain,$username);
1.345     bowersj2 5786:                 if ($wgt) {
                   5787:                     $entries{$fields{$dest}}=~s/\s//g;
                   5788:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5789:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5790:                                           : 'correct_by_override';
1.638     www      5791:                     if ($pcr>1) {
1.657     raeburn  5792:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      5793:                     }
1.345     bowersj2 5794:                     $grades{"resource.$part.awarded"}=$pcr;
                   5795:                     $grades{"resource.$part.solved"}=$award;
                   5796:                     $points{$part}=1;
                   5797:                 } else {
                   5798:                     $error_msg = "<br />" .
                   5799:                         &mt("Some point values were assigned"
                   5800:                             ." for problems with a weight "
                   5801:                             ."of zero. These values were "
                   5802:                             ."ignored.");
                   5803:                 }
1.244     albertel 5804: 	    } else {
                   5805: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5806: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5807: 		my $store_key=$dest;
                   5808: 		$store_key=~s/^stores/resource/;
                   5809: 		$store_key=~s/_/\./g;
                   5810: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5811: 	    }
1.41      ng       5812: 	}
1.766     raeburn  5813: 	if (! %grades) {
1.508     www      5814:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5815:         } else {
                   5816: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5817: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5818: 					   $env{'request.course.id'},
                   5819: 					   $domain,$username);
1.508     www      5820: 	   if ($result eq 'ok') {
1.627     www      5821: # Successfully stored
1.508     www      5822: 	      $request->print('.');
1.627     www      5823: # Remove from grading queue
                   5824:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5825:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5826:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5827:                                              $domain,$username);
                   5828:               $countdone++;
                   5829:            } else {
1.508     www      5830: 	      $request->print("<p><span class=\"LC_error\">".
                   5831:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5832:                                   "$username:$domain",$result)."</span></p>");
                   5833: 	   }
                   5834: 	   $request->rflush();
                   5835:         }
1.41      ng       5836:     }
1.570     www      5837:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  5838:     if (@warnings) {
                   5839:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5840:         $request->print(join(', ',@warnings));
                   5841:     }
1.41      ng       5842:     if (@skipped) {
1.571     www      5843: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5844:         $request->print(join(', ',@skipped));
1.106     albertel 5845:     }
                   5846:     if (@notallowed) {
1.571     www      5847: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5848: 	$request->print(join(', ',@notallowed));
1.41      ng       5849:     }
1.106     albertel 5850:     $request->print("<br />\n");
1.345     bowersj2 5851:     return $error_msg;
1.26      albertel 5852: }
1.44      ng       5853: #------------- end of section for handling csv file upload ---------
                   5854: #
                   5855: #-------------------------------------------------------------------
                   5856: #
1.122     ng       5857: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5858: #
                   5859: #--- Select a page/sequence and a student to grade
1.68      ng       5860: sub pickStudentPage {
1.608     www      5861:     my ($request,$symb) = @_;
1.68      ng       5862: 
1.539     riegler  5863:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  5864:     &js_escape(\$alertmsg);
1.597     wenzelju 5865:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5866: 
                   5867: function checkPickOne(formname) {
1.76      ng       5868:     if (radioSelection(formname.student) == null) {
1.539     riegler  5869: 	alert("$alertmsg");
1.68      ng       5870: 	return;
                   5871:     }
1.125     ng       5872:     ptr = pullDownSelection(formname.selectpage);
                   5873:     formname.page.value = formname["page"+ptr].value;
                   5874:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5875:     formname.submit();
                   5876: }
                   5877: 
                   5878: LISTJAVASCRIPT
1.118     ng       5879:     &commonJSfunctions($request);
1.608     www      5880: 
1.257     albertel 5881:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5882:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5883:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  5884:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5885: 
1.398     albertel 5886:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5887: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5888: 
1.80      ng       5889:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5890:     my $map_error;
                   5891:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5892:     if ($map_error) {
                   5893:         $request->print(&navmap_errormsg());
                   5894:         return; 
                   5895:     }
1.137     albertel 5896:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5897: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5898: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   5899: 
                   5900:     # Collection of hidden fields
1.70      ng       5901:     my $ctr=0;
1.68      ng       5902:     foreach (@$titles) {
1.700     bisitz   5903:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5904:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5905:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5906:         $ctr++;
1.68      ng       5907:     }
1.700     bisitz   5908:     $result.='<input type="hidden" name="page" />'."\n".
                   5909:         '<input type="hidden" name="title" />'."\n";
                   5910: 
                   5911:     $result.=&build_section_inputs();
                   5912:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5913:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   5914: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   5915: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 5916: 
1.700     bisitz   5917:     # Show grading options
                   5918:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5919:     my $select = '<select name="selectpage">'."\n";
1.70      ng       5920:     $ctr=0;
                   5921:     foreach (@$titles) {
                   5922: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   5923: 	$select.='<option value="'.$ctr.'"'.
                   5924: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5925: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       5926: 	$ctr++;
                   5927:     }
1.700     bisitz   5928:     $select.= '</select>';
1.68      ng       5929: 
1.700     bisitz   5930:     $result.=
                   5931:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5932:        .$select
                   5933:        .&Apache::lonhtmlcommon::row_closure();
                   5934: 
                   5935:     $result.=
                   5936:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5937:        .'<label><input type="radio" name="vProb" value="no"'
                   5938:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5939:        .'<label><input type="radio" name="vProb" value="yes" />'
                   5940:            .&mt('yes').'</label>'."\n"
                   5941:        .&Apache::lonhtmlcommon::row_closure();
                   5942: 
                   5943:     $result.=
                   5944:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5945:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5946:            .&mt('none').' </label>'."\n"
                   5947:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5948:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5949:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5950:            .&mt('all submissions with details').' </label>'
                   5951:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 5952:     
1.700     bisitz   5953:     $result.=
                   5954:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5955:        .'<input type="text" name="CODE" value="" />'
                   5956:        .&Apache::lonhtmlcommon::row_closure(1)
                   5957:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5958: 
1.700     bisitz   5959:     # Show list of students to select for grading
                   5960:     $result.='<br /><input type="button" '.
1.589     bisitz   5961:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5962: 
1.68      ng       5963:     $request->print($result);
                   5964: 
1.485     albertel 5965:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5966: 	&Apache::loncommon::start_data_table().
                   5967: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5968: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5969: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5970: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5971: 	'<th>'.&nameUserString('header').'</th>'.
                   5972: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5973:  
1.761     raeburn  5974:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5975:     my $ptr = 1;
1.294     albertel 5976:     foreach my $student (sort 
                   5977: 			 {
                   5978: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5979: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5980: 			     }
                   5981: 			     return $a cmp $b;
                   5982: 			 } (keys(%$fullname))) {
1.68      ng       5983: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5984: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5985:                                   : '</td>');
1.126     ng       5986: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5987: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5988: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5989: 	$studentTable.=
                   5990: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5991:                          : '');
1.68      ng       5992: 	$ptr++;
                   5993:     }
1.484     albertel 5994:     if ($ptr%2 == 0) {
                   5995: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5996: 	    &Apache::loncommon::end_data_table_row();
                   5997:     }
                   5998:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5999:     $studentTable.='<input type="button" '.
1.589     bisitz   6000:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       6001: 
                   6002:     $request->print($studentTable);
                   6003: 
                   6004:     return '';
                   6005: }
                   6006: 
                   6007: sub getSymbMap {
1.582     raeburn  6008:     my ($map_error) = @_;
1.132     bowersj2 6009:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6010:     unless (ref($navmap)) {
                   6011:         if (ref($map_error)) {
                   6012:             $$map_error = 'navmap';
                   6013:         }
                   6014:         return;
                   6015:     }
1.68      ng       6016:     my %symbx = ();
                   6017:     my @titles = ();
1.117     bowersj2 6018:     my $minder = 0;
                   6019: 
                   6020:     # Gather every sequence that has problems.
1.240     albertel 6021:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   6022: 					       1,0,1);
1.117     bowersj2 6023:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  6024: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 6025: 	    my $title = $minder.'.'.
                   6026: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   6027: 	    push(@titles, $title); # minder in case two titles are identical
                   6028: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 6029: 	    $minder++;
1.241     albertel 6030: 	}
1.68      ng       6031:     }
                   6032:     return \@titles,\%symbx;
                   6033: }
                   6034: 
1.72      ng       6035: #
                   6036: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       6037: sub displayPage {
1.608     www      6038:     my ($request,$symb) = @_;
1.257     albertel 6039:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6040:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6041:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6042:     my $pageTitle = $env{'form.page'};
1.103     albertel 6043:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6044:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6045:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 6046: 
                   6047:     #need to make sure we have the correct data for later EXT calls, 
                   6048:     #thus invalidate the cache
                   6049:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 6050:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   6051:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 6052:     &Apache::lonnet::clear_EXT_cache_status();
                   6053: 
1.103     albertel 6054:     if (!&canview($usec)) {
1.712     bisitz   6055:         $request->print(
                   6056:             '<span class="LC_warning">'.
                   6057:             &mt('Unable to view requested student. ([_1])',
                   6058:                     $env{'form.student'}).
                   6059:             '</span>');
                   6060:         return;
1.103     albertel 6061:     }
1.398     albertel 6062:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 6063:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       6064: 	'</h3>'."\n";
1.500     albertel 6065:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     6066:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 6067: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 6068:     } else {
                   6069: 	delete($env{'form.CODE'});
                   6070:     }
1.71      ng       6071:     &sub_page_js($request);
                   6072:     $request->print($result);
                   6073: 
1.132     bowersj2 6074:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6075:     unless (ref($navmap)) {
                   6076:         $request->print(&navmap_errormsg());
                   6077:         return;
                   6078:     }
1.257     albertel 6079:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       6080:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6081:     if (!$map) {
1.485     albertel 6082: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 6083: 	return; 
                   6084:     }
1.68      ng       6085:     my $iterator = $navmap->getIterator($map->map_start(),
                   6086: 					$map->map_finish());
                   6087: 
1.71      ng       6088:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       6089: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 6090: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   6091: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       6092: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 6093: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 6094: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      6095: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       6096: 
1.382     albertel 6097:     if (defined($env{'form.CODE'})) {
                   6098: 	$studentTable.=
                   6099: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   6100:     }
1.381     albertel 6101:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 6102: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       6103: 
1.594     bisitz   6104:     $studentTable.='&nbsp;<span class="LC_info">'.
                   6105:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   6106:         '</span>'."\n".
1.484     albertel 6107: 	&Apache::loncommon::start_data_table().
                   6108: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   6109: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 6110: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 6111: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6112: 
1.329     albertel 6113:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 6114:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       6115:     $iterator->next(); # skip the first BEGIN_MAP
                   6116:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 6117:     while ($depth > 0) {
1.68      ng       6118:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6119:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       6120: 
1.745     raeburn  6121:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 6122: 	    my $parts = $curRes->parts();
1.68      ng       6123:             my $title = $curRes->compTitle();
1.71      ng       6124: 	    my $symbx = $curRes->symb();
1.746     raeburn  6125:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 6126: 	    $studentTable.=
                   6127: 		&Apache::loncommon::start_data_table_row().
                   6128: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6129: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  6130: 		                        : '<br />('.&mt('[_1]parts',
                   6131: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 6132: 		 ).
                   6133: 		 '</td>';
1.71      ng       6134: 	    $studentTable.='<td valign="top">';
1.382     albertel 6135: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  6136:             if ($is_tool) {
                   6137:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   6138:             } else {
1.745     raeburn  6139: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   6140: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   6141: 					         undef,'both',\%form);
                   6142: 	        } else {
                   6143: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   6144: 		    $companswer =~ s|<form(.*?)>||g;
                   6145: 		    $companswer =~ s|</form>||g;
                   6146: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   6147: #		        $companswer =~ s/$1/ /ms;
                   6148: #		        $request->print('match='.$1."<br />\n");
                   6149: #		    }
                   6150: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   6151: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   6152: 		}
1.71      ng       6153: 	    }
                   6154: 
1.257     albertel 6155: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       6156: 
1.257     albertel 6157: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       6158: 		if ($record{'version'} eq '') {
1.745     raeburn  6159:                     my $msg = &mt('No recorded submission for this problem.');
                   6160:                     if ($is_tool) {
                   6161:                         $msg = &mt('No recorded transactions for this external tool');
                   6162:                     }
                   6163: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       6164: 		} else {
1.116     ng       6165: 		    my %responseType = ();
                   6166: 		    foreach my $partid (@{$parts}) {
1.147     albertel 6167: 			my @responseIds =$curRes->responseIds($partid);
                   6168: 			my @responseType =$curRes->responseType($partid);
                   6169: 			my %responseIds;
                   6170: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   6171: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   6172: 			}
                   6173: 			$responseType{$partid} = \%responseIds;
1.116     ng       6174: 		    }
1.148     albertel 6175: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       6176: 		}
1.257     albertel 6177: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   6178: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  6179:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       6180: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 6181: 									$env{'request.course.id'},
1.726     raeburn  6182: 									'','.submission',undef,
                   6183:                                                                         $usec,$identifier);
1.71      ng       6184:  
                   6185: 	    }
1.103     albertel 6186: 	    if (&canmodify($usec)) {
1.585     bisitz   6187:             $studentTable.=&gradeBox_start();
1.103     albertel 6188: 		foreach my $partid (@{$parts}) {
                   6189: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   6190: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   6191: 		    $question++;
                   6192: 		}
1.585     bisitz   6193:             $studentTable.=&gradeBox_end();
1.196     albertel 6194: 		$prob++;
1.71      ng       6195: 	    }
                   6196: 	    $studentTable.='</td></tr>';
1.68      ng       6197: 
1.103     albertel 6198: 	}
1.68      ng       6199:         $curRes = $iterator->next();
                   6200:     }
1.780     raeburn  6201:     my $disabled;
                   6202:     unless (&canmodify($usec)) {
                   6203:         $disabled = ' disabled="disabled"';
                   6204:     }
1.68      ng       6205: 
1.589     bisitz   6206:     $studentTable.=
                   6207:         '</table>'."\n".
1.780     raeburn  6208:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   6209:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   6210:         '</form>'."\n";
1.71      ng       6211:     $request->print($studentTable);
                   6212: 
                   6213:     return '';
1.119     ng       6214: }
                   6215: 
                   6216: sub displaySubByDates {
1.148     albertel 6217:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 6218:     my $isCODE=0;
1.335     albertel 6219:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  6220:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 6221:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 6222:     my $studentTable=&Apache::loncommon::start_data_table().
                   6223: 	&Apache::loncommon::start_data_table_header_row().
                   6224: 	'<th>'.&mt('Date/Time').'</th>'.
                   6225: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  6226:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  6227: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 6228: 	'<th>'.&mt('Status').'</th>'.
                   6229: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       6230:     my ($version);
                   6231:     my %mark;
1.148     albertel 6232:     my %orders;
1.119     ng       6233:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 6234:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  6235:         if ($is_tool) {
                   6236:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   6237:         } else {
                   6238:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   6239:         }
1.147     albertel 6240:     }
1.335     albertel 6241: 
                   6242:     my $interaction;
1.525     raeburn  6243:     my $no_increment = 1;
1.735     raeburn  6244:     my (%lastrndseed,%lasttype);
1.119     ng       6245:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 6246: 	my $timestamp = 
                   6247: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 6248: 	if (exists($$record{$version.':resource.0.version'})) {
                   6249: 	    $interaction = $$record{$version.':resource.0.version'};
                   6250: 	}
1.671     raeburn  6251:         if ($isTask && $env{'form.previousversion'}) {
                   6252:             next unless ($interaction == $env{'form.previousversion'});
                   6253:         }
1.335     albertel 6254: 	my $where = ($isTask ? "$version:resource.$interaction"
                   6255: 		             : "$version:resource");
1.467     albertel 6256: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   6257: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 6258: 	if ($isCODE) {
                   6259: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   6260: 	}
1.671     raeburn  6261:         if ($isTask) {
                   6262:             $studentTable.='<td>'.$interaction.'</td>';
                   6263:         }
1.119     ng       6264: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   6265: 	my @displaySub = ();
                   6266: 	foreach my $partid (@{$parts}) {
1.640     raeburn  6267:             my ($hidden,$type);
                   6268:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   6269:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  6270:                 $hidden = 1;
                   6271:             }
1.749     raeburn  6272:             my @matchKey;
                   6273:             if ($isTask) {
1.769     raeburn  6274:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  6275:             } elsif ($is_tool) {
1.769     raeburn  6276:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  6277:             } else {
1.769     raeburn  6278:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  6279:             }
1.122     ng       6280: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 6281: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 6282: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 6283: 		if (exists($$record{$version.':'.$matchKey}) &&
                   6284: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  6285:                     if ($is_tool) {
                   6286:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  6287:                     } else {
1.749     raeburn  6288: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   6289: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   6290:                         $displaySub[0].='<span class="LC_nobreak">';
                   6291:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   6292:                                        .' <span class="LC_internal_info">'
                   6293:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   6294:                                        .'</span>'
                   6295:                                        .' <b>';
                   6296:                         if ($hidden) {
                   6297:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   6298:                         } else {
                   6299:                             my ($trial,$rndseed,$newvariation);
                   6300:                             if ($type eq 'randomizetry') {
                   6301:                                 $trial = $$record{"$where.$partid.tries"};
                   6302:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   6303:                             }
                   6304: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   6305: 			        $displaySub[0].=&mt('Trial not counted');
                   6306: 		            } else {
                   6307: 			        $displaySub[0].=&mt('Trial: [_1]',
                   6308: 					        $$record{"$where.$partid.tries"});
                   6309:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   6310:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   6311:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   6312:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   6313:                                     }
1.640     raeburn  6314:                                 }
1.749     raeburn  6315:                                 $lastrndseed{$partid} = $rndseed;
                   6316:                                 $lasttype{$partid} = $type;
                   6317: 		            }
                   6318: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 6319:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  6320: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   6321: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   6322: 			        $orders{$partid}->{$responseId}=
                   6323: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   6324:                                                $no_increment,$type,$trial,$rndseed);
                   6325: 		            }
                   6326: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   6327: 		            $displaySub[0].='&nbsp; '.
                   6328: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   6329:                         }
1.596     raeburn  6330:                     }
1.147     albertel 6331: 		}
                   6332: 	    }
1.335     albertel 6333: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 6334: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   6335: 				    $$record{"$where.$partid.checkedin"},
                   6336: 				    $$record{"$where.$partid.checkedin.slot"}).
                   6337: 					'<br />';
1.335     albertel 6338: 	    }
                   6339: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 6340: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 6341: 		    lc($$record{"$where.$partid.award"}).' '.
                   6342: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 6343: 		    '<br />';
1.749     raeburn  6344: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   6345: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   6346: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   6347: 		}
1.147     albertel 6348: 	    }
1.335     albertel 6349: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  6350: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   6351: 		unless ($is_tool) {
                   6352: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6353: 		}
1.335     albertel 6354: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   6355: 		$displaySub[2].=
1.749     raeburn  6356: 		    $$record{"$version:resource.$partid.regrader"};
                   6357:                 unless ($is_tool) {
                   6358: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   6359:                 }
1.147     albertel 6360: 	    }
                   6361: 	}
                   6362: 	# needed because old essay regrader has not parts info
                   6363: 	if (exists $$record{"$version:resource.regrader"}) {
                   6364: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   6365: 	}
                   6366: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   6367: 	if ($displaySub[2]) {
1.467     albertel 6368: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 6369: 	}
1.467     albertel 6370: 	$studentTable.='&nbsp;</td>'.
                   6371: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       6372:     }
1.467     albertel 6373:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       6374:     return $studentTable;
1.71      ng       6375: }
                   6376: 
                   6377: sub updateGradeByPage {
1.608     www      6378:     my ($request,$symb) = @_;
1.71      ng       6379: 
1.257     albertel 6380:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   6381:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   6382:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   6383:     my $pageTitle = $env{'form.page'};
1.103     albertel 6384:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 6385:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   6386:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 6387:     if (!&canmodify($usec)) {
1.526     raeburn  6388: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 6389: 	return;
                   6390:     }
1.398     albertel 6391:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  6392:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       6393: 	'</h3>'."\n";
1.70      ng       6394: 
1.68      ng       6395:     $request->print($result);
                   6396: 
1.582     raeburn  6397: 
1.132     bowersj2 6398:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  6399:     unless (ref($navmap)) {
                   6400:         $request->print(&navmap_errormsg());
                   6401:         return;
                   6402:     }
1.257     albertel 6403:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       6404:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 6405:     if (!$map) {
1.527     raeburn  6406: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 6407: 	return; 
                   6408:     }
1.71      ng       6409:     my $iterator = $navmap->getIterator($map->map_start(),
                   6410: 					$map->map_finish());
1.70      ng       6411: 
1.484     albertel 6412:     my $studentTable=
                   6413: 	&Apache::loncommon::start_data_table().
                   6414: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 6415: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   6416: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   6417: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   6418: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 6419: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       6420: 
                   6421:     $iterator->next(); # skip the first BEGIN_MAP
                   6422:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  6423:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 6424:     while ($depth > 0) {
1.71      ng       6425:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 6426:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       6427: 
1.385     albertel 6428:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 6429: 	    my $parts = $curRes->parts();
1.71      ng       6430:             my $title = $curRes->compTitle();
                   6431: 	    my $symbx = $curRes->symb();
1.484     albertel 6432: 	    $studentTable.=
                   6433: 		&Apache::loncommon::start_data_table_row().
                   6434: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 6435: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  6436:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  6437: 		.')').'</td>';
1.71      ng       6438: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   6439: 
                   6440: 	    my %newrecord=();
                   6441: 	    my @displayPts=();
1.269     raeburn  6442:             my %aggregate = ();
                   6443:             my $aggregateflag = 0;
1.787     raeburn  6444:             my %queueable;
1.726     raeburn  6445:             if ($env{'form.HIDE'.$prob}) {
                   6446:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  6447:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  6448:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  6449:                 $hideflag += $numchgs;
                   6450:             }
1.71      ng       6451: 	    foreach my $partid (@{$parts}) {
1.257     albertel 6452: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   6453: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.787     raeburn  6454:                 my @types = $curRes->responseType($partid);
1.786     raeburn  6455:                 if (grep(/^essay$/,@types)) {
                   6456:                     $queueable{$partid} = 1;
                   6457:                 } else {
1.787     raeburn  6458:                     my @ids = $curRes->responseIds($partid);
1.786     raeburn  6459:                     for (my $i=0; $i < scalar(@ids); $i++) {
1.787     raeburn  6460:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
1.786     raeburn  6461:                                                           '.handgrade',$symb);
                   6462:                         if (lc($hndgrd) eq 'yes') {
                   6463:                             $queueable{$partid} = 1;
                   6464:                             last;
                   6465:                         }
                   6466:                     }
                   6467:                 }
1.257     albertel 6468: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   6469: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       6470: 		my $partial = $newpts/$wgt;
                   6471: 		my $score;
                   6472: 		if ($partial > 0) {
                   6473: 		    $score = 'correct_by_override';
1.125     ng       6474: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       6475: 		    $score = 'incorrect_by_override';
                   6476: 		}
1.257     albertel 6477: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       6478: 		if ($dropMenu eq 'excused') {
1.71      ng       6479: 		    $partial = '';
                   6480: 		    $score = 'excused';
1.125     ng       6481: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 6482: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       6483: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   6484: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   6485: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   6486: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 6487: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       6488: 		    $changeflag++;
                   6489: 		    $newpts = '';
1.269     raeburn  6490:                     
                   6491:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   6492:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   6493:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   6494:                     if ($aggtries > 0) {
                   6495:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   6496:                         $aggregateflag = 1;
                   6497:                     }
1.71      ng       6498: 		}
1.324     albertel 6499: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 6500: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  6501: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       6502: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 6503: 		    '&nbsp;<br />';
1.526     raeburn  6504: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       6505: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 6506: 		    '&nbsp;<br />';
1.71      ng       6507: 		$question++;
1.380     albertel 6508: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       6509: 
1.71      ng       6510: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       6511: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 6512: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       6513: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       6514: 
                   6515: 		$changeflag++;
                   6516: 	    }
                   6517: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 6518: 		my %record = 
                   6519: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   6520: 					     $udom,$uname);
                   6521: 
                   6522: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   6523: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   6524: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   6525: 		    $newrecord{'resource.CODE'} = '';
                   6526: 		}
1.257     albertel 6527: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       6528: 					$udom,$uname);
1.382     albertel 6529: 		%record = &Apache::lonnet::restore($symbx,
                   6530: 						   $env{'request.course.id'},
                   6531: 						   $udom,$uname);
1.380     albertel 6532: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.786     raeburn  6533: 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       6534: 	    }
1.380     albertel 6535: 	    
1.269     raeburn  6536:             if ($aggregateflag) {
                   6537:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   6538:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   6539:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   6540:             }
1.125     ng       6541: 
1.71      ng       6542: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   6543: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 6544: 		&Apache::loncommon::end_data_table_row();
1.68      ng       6545: 
1.196     albertel 6546: 	    $prob++;
1.68      ng       6547: 	}
1.71      ng       6548:         $curRes = $iterator->next();
1.68      ng       6549:     }
1.98      albertel 6550: 
1.484     albertel 6551:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  6552:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   6553: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  6554: 		  $changeflag).'<br />');
                   6555:     my $hidemsg=($hideflag == 0 ? '' :
                   6556:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   6557:                      $hideflag).'<br />');
                   6558:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       6559: 
1.70      ng       6560:     return '';
                   6561: }
                   6562: 
1.72      ng       6563: #-------- end of section for handling grading by page/sequence ---------
                   6564: #
                   6565: #-------------------------------------------------------------------
                   6566: 
1.581     www      6567: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 6568: #
                   6569: #------ start of section for handling grading by page/sequence ---------
                   6570: 
1.423     albertel 6571: =pod
                   6572: 
                   6573: =head1 Bubble sheet grading routines
                   6574: 
1.424     albertel 6575:   For this documentation:
                   6576: 
                   6577:    'scanline' refers to the full line of characters
                   6578:    from the file that we are parsing that represents one entire sheet
                   6579: 
                   6580:    'bubble line' refers to the data
1.659     raeburn  6581:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 6582: 
                   6583: 
1.659     raeburn  6584: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 6585: into a course. When a user wants to grade, they select a
1.659     raeburn  6586: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 6587: one of the predefined configurations for what each scanline looks
                   6588: like.
                   6589: 
                   6590: Next each scanline is checked for any errors of either 'missing
1.435     foxr     6591: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 6592: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   6593: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  6594: invalid student/employee ID
1.424     albertel 6595: 
                   6596: If the CODE option is used that determines the randomization of the
1.556     weissno  6597: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 6598: username:domain.
                   6599: 
                   6600: During the validation phase the instructor can choose to skip scanlines. 
                   6601: 
1.659     raeburn  6602: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 6603: 
                   6604:   scantron_original_filename (unmodified original file)
                   6605:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   6606:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   6607: 
                   6608: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  6609: correction information that isn't representable in the bubblesheet
1.424     albertel 6610: file (see &scantron_getfile() for more information)
                   6611: 
                   6612: After all scanlines are either valid, marked as valid or skipped, then
                   6613: foreach line foreach problem in the picked sequence, an ssi request is
                   6614: made that simulates a user submitting their selected letter(s) against
                   6615: the homework problem.
1.423     albertel 6616: 
                   6617: =over 4
                   6618: 
                   6619: 
                   6620: 
                   6621: =item defaultFormData
                   6622: 
                   6623:   Returns html hidden inputs used to hold context/default values.
                   6624: 
                   6625:  Arguments:
                   6626:   $symb - $symb of the current resource 
                   6627: 
                   6628: =cut
1.422     foxr     6629: 
1.81      albertel 6630: sub defaultFormData {
1.324     albertel 6631:     my ($symb)=@_;
1.766     raeburn  6632:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 6633: }
                   6634: 
1.447     foxr     6635: 
1.423     albertel 6636: =pod 
                   6637: 
                   6638: =item getSequenceDropDown
                   6639: 
                   6640:    Return html dropdown of possible sequences to grade
                   6641:  
                   6642:  Arguments:
1.582     raeburn  6643:    $symb - $symb of the current resource
                   6644:    $map_error - ref to scalar which will container error if
                   6645:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 6646: 
                   6647: =cut
1.422     foxr     6648: 
1.75      albertel 6649: sub getSequenceDropDown {
1.582     raeburn  6650:     my ($symb,$map_error)=@_;
1.75      albertel 6651:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  6652:     my ($titles,$symbx) = &getSymbMap($map_error);
                   6653:     if (ref($map_error)) {
                   6654:         return if ($$map_error);
                   6655:     }
1.137     albertel 6656:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 6657:     my $ctr=0;
                   6658:     foreach (@$titles) {
                   6659: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   6660: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 6661: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 6662: 	    '>'.$showtitle.'</option>'."\n";
                   6663: 	$ctr++;
                   6664:     }
                   6665:     $result.= '</select>';
                   6666:     return $result;
                   6667: }
                   6668: 
1.495     albertel 6669: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  6670:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 6671: 
                   6672: my %first_bubble_line;             # First bubble line no. for each bubble.
                   6673: 
1.509     raeburn  6674: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   6675:                                    # matchresponse or rankresponse, where 
                   6676:                                    # an individual response can have multiple 
                   6677:                                    # lines
1.503     raeburn  6678: 
                   6679: my %responsetype_per_response;     # responsetype for each response
                   6680: 
1.691     raeburn  6681: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   6682:                                    # numbered response. Needed when randomorder
                   6683:                                    # or randompick are in use. Key is ID, value 
                   6684:                                    # is response number.
                   6685: 
1.495     albertel 6686: # Save and restore the bubble lines array to the form env.
                   6687: 
                   6688: 
                   6689: sub save_bubble_lines {
                   6690:     foreach my $line (keys(%bubble_lines_per_response)) {
                   6691: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   6692: 	$env{"form.scantron.first_bubble_line.$line"} =
                   6693: 	    $first_bubble_line{$line};
1.503     raeburn  6694:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   6695:             $subdivided_bubble_lines{$line};
                   6696:         $env{"form.scantron.responsetype.$line"} =
                   6697:             $responsetype_per_response{$line};
1.495     albertel 6698:     }
1.691     raeburn  6699:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   6700:         my $line = $masterseq_id_responsenum{$resid};
                   6701:         $env{"form.scantron.residpart.$line"} = $resid;
                   6702:     }
1.495     albertel 6703: }
                   6704: 
                   6705: 
                   6706: sub restore_bubble_lines {
                   6707:     my $line = 0;
                   6708:     %bubble_lines_per_response = ();
1.691     raeburn  6709:     %masterseq_id_responsenum = ();
1.495     albertel 6710:     while ($env{"form.scantron.bubblelines.$line"}) {
                   6711: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   6712: 	$bubble_lines_per_response{$line} = $value;
                   6713: 	$first_bubble_line{$line}  =
                   6714: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  6715:         $subdivided_bubble_lines{$line} =
                   6716:             $env{"form.scantron.sub_bubblelines.$line"};
                   6717:         $responsetype_per_response{$line} =
                   6718:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  6719:         my $id = $env{"form.scantron.residpart.$line"};
                   6720:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 6721: 	$line++;
                   6722:     }
                   6723: }
                   6724: 
1.423     albertel 6725: =pod 
                   6726: 
                   6727: =item scantron_filenames
                   6728: 
                   6729:    Returns a list of the scantron files in the current course 
                   6730: 
                   6731: =cut
1.422     foxr     6732: 
1.202     albertel 6733: sub scantron_filenames {
1.257     albertel 6734:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6735:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  6736:     my $getpropath = 1;
1.662     raeburn  6737:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   6738:                                                         $cname,$getpropath);
1.202     albertel 6739:     my @possiblenames;
1.662     raeburn  6740:     if (ref($dirlist) eq 'ARRAY') {
                   6741:         foreach my $filename (sort(@{$dirlist})) {
                   6742: 	    ($filename)=split(/&/,$filename);
                   6743: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   6744: 	    $filename=~s/^scantron_orig_//;
                   6745: 	    push(@possiblenames,$filename);
                   6746:         }
1.202     albertel 6747:     }
                   6748:     return @possiblenames;
                   6749: }
                   6750: 
1.423     albertel 6751: =pod 
                   6752: 
                   6753: =item scantron_uploads
                   6754: 
                   6755:    Returns  html drop-down list of scantron files in current course.
                   6756: 
                   6757:  Arguments:
                   6758:    $file2grade - filename to set as selected in the dropdown
                   6759: 
                   6760: =cut
1.422     foxr     6761: 
1.202     albertel 6762: sub scantron_uploads {
1.209     ng       6763:     my ($file2grade) = @_;
1.202     albertel 6764:     my $result=	'<select name="scantron_selectfile">';
                   6765:     $result.="<option></option>";
                   6766:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 6767: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 6768:     }
                   6769:     $result.="</select>";
                   6770:     return $result;
                   6771: }
                   6772: 
1.423     albertel 6773: =pod 
                   6774: 
                   6775: =item scantron_scantab
                   6776: 
                   6777:   Returns html drop down of the scantron formats in the scantronformat.tab
                   6778:   file.
                   6779: 
                   6780: =cut
1.422     foxr     6781: 
1.82      albertel 6782: sub scantron_scantab {
                   6783:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 6784:     $result.='<option></option>'."\n";
1.754     raeburn  6785:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  6786:     if (@lines > 0) {
                   6787:         foreach my $line (@lines) {
                   6788:             next if (($line =~ /^\#/) || ($line eq ''));
                   6789: 	    my ($name,$descrip)=split(/:/,$line);
                   6790: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   6791:         }
1.82      albertel 6792:     }
                   6793:     $result.='</select>'."\n";
1.518     raeburn  6794:     return $result;
                   6795: }
                   6796: 
1.423     albertel 6797: =pod 
                   6798: 
                   6799: =item scantron_CODElist
                   6800: 
                   6801:   Returns html drop down of the saved CODE lists from current course,
                   6802:   generated from earlier printings.
                   6803: 
                   6804: =cut
1.422     foxr     6805: 
1.186     albertel 6806: sub scantron_CODElist {
1.257     albertel 6807:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6808:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 6809:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   6810:     my $namechoice='<option></option>';
1.225     albertel 6811:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 6812: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 6813: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 6814: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   6815:     }
                   6816:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6817:     return $namechoice;
                   6818: }
                   6819: 
1.423     albertel 6820: =pod 
                   6821: 
                   6822: =item scantron_CODEunique
                   6823: 
                   6824:   Returns the html for "Each CODE to be used once" radio.
                   6825: 
                   6826: =cut
1.422     foxr     6827: 
1.186     albertel 6828: sub scantron_CODEunique {
1.532     bisitz   6829:     my $result='<span class="LC_nobreak">
1.272     albertel 6830:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6831:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6832:                 </span>
1.532     bisitz   6833:                 <span class="LC_nobreak">
1.272     albertel 6834:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6835:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6836:                 </span>';
1.186     albertel 6837:     return $result;
                   6838: }
1.423     albertel 6839: 
                   6840: =pod 
                   6841: 
                   6842: =item scantron_selectphase
                   6843: 
1.659     raeburn  6844:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6845:   Allows for - starting a grading run.
1.424     albertel 6846:              - downloading existing scan data (original, corrected
1.423     albertel 6847:                                                 or skipped info)
                   6848: 
                   6849:              - uploading new scan data
                   6850: 
                   6851:  Arguments:
                   6852:   $r          - The Apache request object
                   6853:   $file2grade - name of the file that contain the scanned data to score
                   6854: 
                   6855: =cut
1.186     albertel 6856: 
1.75      albertel 6857: sub scantron_selectphase {
1.608     www      6858:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6859:     if (!$symb) {return '';}
1.582     raeburn  6860:     my $map_error;
                   6861:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6862:     if ($map_error) {
                   6863:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6864:         return;
                   6865:     }
1.324     albertel 6866:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6867:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6868:     my $format_selector=&scantron_scantab();
1.186     albertel 6869:     my $CODE_selector=&scantron_CODElist();
                   6870:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6871:     my $result;
1.422     foxr     6872: 
1.513     foxr     6873:     $ssi_error = 0;
                   6874: 
1.770     raeburn  6875:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 6876: 
                   6877: 	# Chunk of form to prompt for a scantron file upload.
                   6878: 
                   6879:         $r->print('
1.754     raeburn  6880:     <br />');
1.606     wenzelju 6881:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6882:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  6883:     my $csec= $env{'request.course.sec'};
1.736     damieng  6884:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6885:     &js_escape(\$alertmsg);
1.754     raeburn  6886:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 6887:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   6888:     function checkUpload(formname) {
                   6889: 	if (formname.upfile.value == "") {
1.736     damieng  6890: 	    alert("'.$alertmsg.'");
1.606     wenzelju 6891: 	    return false;
                   6892: 	}
                   6893: 	formname.submit();
1.756     raeburn  6894:     }'."\n".$formatjs));
1.606     wenzelju 6895:     $r->print('
                   6896:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6897:                 '.$default_form_data.'
                   6898:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  6899:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 6900:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6901:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  6902:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6903:               '.&Apache::loncommon::start_data_table_header_row().'
                   6904:                 <th>
                   6905:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6906:                 </th>
                   6907:               '.&Apache::loncommon::end_data_table_header_row().'
                   6908:               '.&Apache::loncommon::start_data_table_row().'
                   6909:             <td>
                   6910:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6911:     if ($formatoptions) {
                   6912:         $r->print('</td>
                   6913:                  '.&Apache::loncommon::end_data_table_row().'
                   6914:                  '.&Apache::loncommon::start_data_table_row().'
                   6915:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6916:                  </td>
                   6917:                  '.&Apache::loncommon::end_data_table_row().'
                   6918:                  '.&Apache::loncommon::start_data_table_row().'
                   6919:                  <td>'
                   6920:         );
                   6921:     } else {
                   6922:         $r->print(' <br />');
                   6923:     }
                   6924:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6925:               </td>
                   6926:              '.&Apache::loncommon::end_data_table_row().'
                   6927:              '.&Apache::loncommon::end_data_table().'
                   6928:              </form>'
                   6929:     );
1.606     wenzelju 6930: 
                   6931:     }
                   6932: 
1.422     foxr     6933:     # Chunk of form to prompt for a file to grade and how:
                   6934: 
1.489     albertel 6935:     $result.= '
                   6936:     <br />
                   6937:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6938:     <input type="hidden" name="command" value="scantron_warning" />
                   6939:     '.$default_form_data.'
                   6940:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6941:        '.&Apache::loncommon::start_data_table_header_row().'
                   6942:             <th colspan="2">
1.492     albertel 6943:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6944:             </th>
                   6945:        '.&Apache::loncommon::end_data_table_header_row().'
                   6946:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6947:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6948:        '.&Apache::loncommon::end_data_table_row().'
                   6949:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6950:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6951:        '.&Apache::loncommon::end_data_table_row().'
                   6952:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6953:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6954:        '.&Apache::loncommon::end_data_table_row().'
                   6955:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6956:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6957:        '.&Apache::loncommon::end_data_table_row().'
                   6958:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6959:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6960:        '.&Apache::loncommon::end_data_table_row().'
                   6961:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6962: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6963:             <td>
1.492     albertel 6964: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6965:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6966:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6967: 	    </td>
1.489     albertel 6968:        '.&Apache::loncommon::end_data_table_row().'
                   6969:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6970:             <td colspan="2">
1.572     www      6971:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6972:             </td>
1.489     albertel 6973:        '.&Apache::loncommon::end_data_table_row().'
                   6974:     '.&Apache::loncommon::end_data_table().'
                   6975:     </form>
                   6976: ';
1.162     albertel 6977:    
                   6978:     $r->print($result);
                   6979: 
1.422     foxr     6980:     # Chunk of the form that prompts to view a scoring office file,
                   6981:     # corrected file, skipped records in a file.
                   6982: 
1.489     albertel 6983:     $r->print('
                   6984:    <br />
                   6985:    <form action="/adm/grades" name="scantron_download">
                   6986:      '.$default_form_data.'
                   6987:      <input type="hidden" name="command" value="scantron_download" />
                   6988:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6989:        '.&Apache::loncommon::start_data_table_header_row().'
                   6990:               <th>
1.492     albertel 6991:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6992:               </th>
                   6993:        '.&Apache::loncommon::end_data_table_header_row().'
                   6994:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6995:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6996:                 <br />
1.492     albertel 6997:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6998:        '.&Apache::loncommon::end_data_table_row().'
                   6999:      '.&Apache::loncommon::end_data_table().'
                   7000:    </form>
                   7001:    <br />
                   7002: ');
1.162     albertel 7003: 
1.457     banghart 7004:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  7005: 
1.694     bisitz   7006:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  7007:              $default_form_data."\n".
                   7008:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   7009:              &Apache::loncommon::start_data_table_header_row()."\n".
                   7010:              '<th colspan="2">
1.572     www      7011:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  7012:              '</th>'."\n".
                   7013:               &Apache::loncommon::end_data_table_header_row()."\n".
                   7014:               &Apache::loncommon::start_data_table_row()."\n".
                   7015:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   7016:               '<td> '.$sequence_selector.' </td>'.
                   7017:               &Apache::loncommon::end_data_table_row()."\n".
                   7018:               &Apache::loncommon::start_data_table_row()."\n".
                   7019:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   7020:               '<td> '.$file_selector.' </td>'."\n".
                   7021:               &Apache::loncommon::end_data_table_row()."\n".
                   7022:               &Apache::loncommon::start_data_table_row()."\n".
                   7023:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   7024:               '<td> '.$format_selector.' </td>'."\n".
                   7025:               &Apache::loncommon::end_data_table_row()."\n".
                   7026:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  7027:               '<td> '.&mt('Options').' </td>'."\n".
                   7028:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   7029:               &Apache::loncommon::end_data_table_row()."\n".
                   7030:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  7031:               '<td colspan="2">'."\n".
                   7032:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      7033:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  7034:               '</td>'."\n".
                   7035:               &Apache::loncommon::end_data_table_row()."\n".
                   7036:               &Apache::loncommon::end_data_table()."\n".
                   7037:               '</form><br />');
                   7038:     return;
1.75      albertel 7039: }
                   7040: 
1.423     albertel 7041: =pod 
                   7042: 
                   7043: =item username_to_idmap
                   7044: 
1.556     weissno  7045:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  7046:     student username:domain. If a single ID occurs for more than one student,
                   7047:     the status of the student is checked, and if Active, the value in the hash
                   7048:     will be set to the Active student.
1.423     albertel 7049: 
                   7050:   Arguments:
                   7051: 
                   7052:     $classlist - reference to the class list hash. This is a hash
                   7053:                  keyed by student name:domain  whose elements are references
1.424     albertel 7054:                  to arrays containing various chunks of information
1.423     albertel 7055:                  about the student. (See loncoursedata for more info).
                   7056: 
                   7057:   Returns
                   7058:     %idmap - the constructed hash
                   7059: 
                   7060: =cut
                   7061: 
1.82      albertel 7062: sub username_to_idmap {
                   7063:     my ($classlist)= @_;
                   7064:     my %idmap;
                   7065:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  7066:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   7067:         unless ($id eq '') {
                   7068:             if (!exists($idmap{$id})) {
                   7069:                 $idmap{$id} = $student;
                   7070:             } else {
                   7071:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   7072:                 if ($status eq 'Active') {
                   7073:                     $idmap{$id} = $student;
                   7074:                 }
                   7075:             }
                   7076:         }
1.82      albertel 7077:     }
                   7078:     return %idmap;
                   7079: }
1.423     albertel 7080: 
                   7081: =pod
                   7082: 
1.424     albertel 7083: =item scantron_fixup_scanline
1.423     albertel 7084: 
                   7085:    Process a requested correction to a scanline.
                   7086: 
                   7087:   Arguments:
1.754     raeburn  7088:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 7089:     $scan_data         - hash of correction information 
                   7090:                           (see &scantron_getfile())
                   7091:     $line              - existing scanline
                   7092:     $whichline         - line number of the passed in scanline
                   7093:     $field             - type of change to process 
                   7094:                          (either 
1.573     bisitz   7095:                           'ID'     -> correct the student/employee ID
1.423     albertel 7096:                           'CODE'   -> correct the CODE
                   7097:                           'answer' -> fixup the submitted answers)
                   7098:     
                   7099:    $args               - hash of additional info,
                   7100:                           - 'ID' 
                   7101:                                'newid' -> studentID to use in replacement
1.424     albertel 7102:                                           of existing one
1.423     albertel 7103:                           - 'CODE' 
                   7104:                                'CODE_ignore_dup' - set to true if duplicates
                   7105:                                                    should be ignored.
                   7106: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 7107:                                         if the existing unfound code should
1.423     albertel 7108:                                         be used as is
                   7109:                           - 'answer'
                   7110:                                'response' - new answer or 'none' if blank
                   7111:                                'question' - the bubble line to change
1.503     raeburn  7112:                                'questionnum' - the question identifier,
                   7113:                                                may include subquestion. 
1.423     albertel 7114: 
                   7115:   Returns:
                   7116:     $line - the modified scanline
                   7117: 
                   7118:   Side effects: 
                   7119:     $scan_data - may be updated
                   7120: 
                   7121: =cut
                   7122: 
1.82      albertel 7123: 
1.157     albertel 7124: sub scantron_fixup_scanline {
                   7125:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   7126:     if ($field eq 'ID') {
                   7127: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 7128: 	    return ($line,1,'New value too large');
1.157     albertel 7129: 	}
                   7130: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   7131: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   7132: 				     $args->{'newid'});
                   7133: 	}
                   7134: 	substr($line,$$scantron_config{'IDstart'}-1,
                   7135: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   7136: 	if ($args->{'newid'}=~/^\s*$/) {
                   7137: 	    &scan_data($scan_data,"$whichline.user",
                   7138: 		       $args->{'username'}.':'.$args->{'domain'});
                   7139: 	}
1.186     albertel 7140:     } elsif ($field eq 'CODE') {
1.192     albertel 7141: 	if ($args->{'CODE_ignore_dup'}) {
                   7142: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   7143: 	}
                   7144: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   7145: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 7146: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   7147: 		return ($line,1,'New CODE value too large');
                   7148: 	    }
                   7149: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   7150: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   7151: 	    }
                   7152: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   7153: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 7154: 	}
1.157     albertel 7155:     } elsif ($field eq 'answer') {
1.497     foxr     7156: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 7157: 	my $off=$scantron_config->{'Qoff'};
                   7158: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     7159: 	my $answer=${off}x$length;
                   7160: 	if ($args->{'response'} eq 'none') {
                   7161: 	    &scan_data($scan_data,
1.503     raeburn  7162: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     7163: 	} else {
                   7164: 	    if ($on eq 'letter') {
                   7165: 		my @alphabet=('A'..'Z');
                   7166: 		$answer=$alphabet[$args->{'response'}];
                   7167: 	    } elsif ($on eq 'number') {
                   7168: 		$answer=$args->{'response'}+1;
                   7169: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 7170: 	    } else {
1.497     foxr     7171: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 7172: 	    }
1.497     foxr     7173: 	    &scan_data($scan_data,
1.503     raeburn  7174: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 7175: 	}
1.497     foxr     7176: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   7177: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 7178:     }
                   7179:     return $line;
                   7180: }
1.423     albertel 7181: 
                   7182: =pod
                   7183: 
                   7184: =item scan_data
                   7185: 
                   7186:     Edit or look up  an item in the scan_data hash.
                   7187: 
                   7188:   Arguments:
                   7189:     $scan_data  - The hash (see scantron_getfile)
                   7190:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 7191:                   scantronfilename_key).
1.423     albertel 7192:     $data        - New value of the hash entry.
                   7193:     $delete      - If true, the entry is removed from the hash.
                   7194: 
                   7195:   Returns:
                   7196:     The new value of the hash table field (undefined if deleted).
                   7197: 
                   7198: =cut
                   7199: 
                   7200: 
1.157     albertel 7201: sub scan_data {
                   7202:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 7203:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 7204:     if (defined($value)) {
                   7205: 	$scan_data->{$filename.'_'.$key} = $value;
                   7206:     }
                   7207:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   7208:     return $scan_data->{$filename.'_'.$key};
                   7209: }
1.423     albertel 7210: 
1.495     albertel 7211: # ----- These first few routines are general use routines.----
                   7212: 
                   7213: # Return the number of occurences of a pattern in a string.
                   7214: 
                   7215: sub occurence_count {
                   7216:     my ($string, $pattern) = @_;
                   7217: 
                   7218:     my @matches = ($string =~ /$pattern/g);
                   7219: 
                   7220:     return scalar(@matches);
                   7221: }
                   7222: 
                   7223: 
                   7224: # Take a string known to have digits and convert all the
                   7225: # digits into letters in the range J,A..I.
                   7226: 
                   7227: sub digits_to_letters {
                   7228:     my ($input) = @_;
                   7229: 
                   7230:     my @alphabet = ('J', 'A'..'I');
                   7231: 
                   7232:     my @input    = split(//, $input);
                   7233:     my $output ='';
                   7234:     for (my $i = 0; $i < scalar(@input); $i++) {
                   7235: 	if ($input[$i] =~ /\d/) {
                   7236: 	    $output .= $alphabet[$input[$i]];
                   7237: 	} else {
                   7238: 	    $output .= $input[$i];
                   7239: 	}
                   7240:     }
                   7241:     return $output;
                   7242: }
                   7243: 
1.423     albertel 7244: =pod 
                   7245: 
                   7246: =item scantron_parse_scanline
                   7247: 
1.711     bisitz   7248:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 7249: 
                   7250:  Arguments:
1.711     bisitz   7251:     line             - The text of the bubblesheet file line to process
1.423     albertel 7252:     whichline        - Line number
1.711     bisitz   7253:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 7254:     scan_data        - Hash of extra information about the scanline
                   7255:                        (see scantron_getfile for more information)
                   7256:     just_header      - True if should not process question answers but only
                   7257:                        the stuff to the left of the answers.
1.691     raeburn  7258:     randomorder      - True if randomorder in use
                   7259:     randompick       - True if randompick in use
                   7260:     sequence         - Exam folder URL
                   7261:     master_seq       - Ref to array containing symbs in exam folder
                   7262:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   7263:                        (corresponding values are resource objects)
                   7264:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   7265:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   7266:                        are refs to an array of resource objects, ordered
                   7267:                        according to order used for CODE, when randomorder
                   7268:                        and or randompick are in use.
                   7269:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   7270:                        for current line to question number used for same question
                   7271:                         in "Master Sequence" (as seen by Course Coordinator).
                   7272:     startline        - Ref to hash where key is question number (0 is first)
                   7273:                        and value is number of first bubble line for current 
                   7274:                        student or code-based randompick and/or randomorder.
                   7275:     totalref         - Ref of scalar used to score total number of bubble
                   7276:                        lines needed for responses in a scan line (used when
                   7277:                        randompick in use. 
                   7278:     
1.423     albertel 7279:  Returns:
                   7280:    Hash containing the result of parsing the scanline
                   7281: 
                   7282:    Keys are all proceeded by the string 'scantron.'
                   7283: 
                   7284:        CODE    - the CODE in use for this scanline
                   7285:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   7286:                  by the operator
                   7287:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   7288:                             CODEs were selected, but the usage has been
                   7289:                             forced by the operator
1.556     weissno  7290:        ID  - student/employee ID
1.423     albertel 7291:        PaperID - if used, the ID number printed on the sheet when the 
                   7292:                  paper was scanned
                   7293:        FirstName - first name from the sheet
                   7294:        LastName  - last name from the sheet
                   7295: 
                   7296:      if just_header was not true these key may also exist
                   7297: 
1.447     foxr     7298:        missingerror - a list of bubble ranges that are considered to be answers
                   7299:                       to a single question that don't have any bubbles filled in.
                   7300:                       Of the form questionnumber:firstbubblenumber:count.
                   7301:        doubleerror  - a list of bubble ranges that are considered to be answers
                   7302:                       to a single question that have more than one bubble filled in.
                   7303:                       Of the form questionnumber::firstbubblenumber:count
                   7304:    
                   7305:                 In the above, count is the number of bubble responses in the
                   7306:                 input line needed to represent the possible answers to the question.
                   7307:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   7308:                 per line would have count = 2.
                   7309: 
1.423     albertel 7310:        maxquest     - the number of the last bubble line that was parsed
                   7311: 
                   7312:        (<number> starts at 1)
                   7313:        <number>.answer - zero or more letters representing the selected
                   7314:                          letters from the scanline for the bubble line 
                   7315:                          <number>.
                   7316:                          if blank there was either no bubble or there where
                   7317:                          multiple bubbles, (consult the keys missingerror and
                   7318:                          doubleerror if this is an error condition)
                   7319: 
                   7320: =cut
                   7321: 
1.82      albertel 7322: sub scantron_parse_scanline {
1.691     raeburn  7323:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   7324:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   7325:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     7326: 
1.82      albertel 7327:     my %record;
1.691     raeburn  7328:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 7329:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   7330: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   7331: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   7332: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   7333: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 7334: 	    $record{'scantron.CODE'}=substr($data,
                   7335: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 7336: 					    $$scantron_config{'CODElength'});
1.191     albertel 7337: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   7338: 		$record{'scantron.useCODE'}=1;
                   7339: 	    }
1.192     albertel 7340: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   7341: 		$record{'scantron.CODE_ignore_dup'}=1;
                   7342: 	    }
1.82      albertel 7343: 	} else {
                   7344: 	    #FIXME interpret first N questions
                   7345: 	}
                   7346:     }
1.83      albertel 7347:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   7348: 				  $$scantron_config{'IDlength'});
1.157     albertel 7349:     $record{'scantron.PaperID'}=
                   7350: 	substr($data,$$scantron_config{'PaperID'}-1,
                   7351: 	       $$scantron_config{'PaperIDlength'});
                   7352:     $record{'scantron.FirstName'}=
                   7353: 	substr($data,$$scantron_config{'FirstName'}-1,
                   7354: 	       $$scantron_config{'FirstNamelength'});
                   7355:     $record{'scantron.LastName'}=
                   7356: 	substr($data,$$scantron_config{'LastName'}-1,
                   7357: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 7358:     if ($just_header) { return \%record; }
1.194     albertel 7359: 
1.82      albertel 7360:     my @alphabet=('A'..'Z');
                   7361:     my $questnum=0;
1.447     foxr     7362:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   7363: 
1.691     raeburn  7364:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   7365:     if ($randompick || $randomorder) {
                   7366:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   7367:                                          $master_seq,$symb_to_resource,
                   7368:                                          $partids_by_symb,$orderedforcode,
                   7369:                                          $respnumlookup,$startline);
                   7370:         if ($total) {
                   7371:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   7372:         }
                   7373:         if (ref($totalref)) {
                   7374:             $$totalref = $total;
                   7375:         }
                   7376:     }
                   7377:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     7378:     chomp($questions);		# Get rid of any trailing \n.
                   7379:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   7380:     while (length($questions)) {
1.691     raeburn  7381:         my $answers_needed;
                   7382:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7383:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   7384:         } else {
                   7385: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   7386:         }
1.503     raeburn  7387:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   7388:                              || 1;
                   7389:         $questnum++;
                   7390:         my $quest_id = $questnum;
                   7391:         my $currentquest = substr($questions,0,$answer_length);
                   7392:         $questions       = substr($questions,$answer_length);
                   7393:         if (length($currentquest) < $answer_length) { next; }
                   7394: 
1.691     raeburn  7395:         my $subdivided;
                   7396:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7397:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   7398:         } else {
                   7399:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   7400:         }
                   7401:         if ($subdivided =~ /,/) {
1.503     raeburn  7402:             my $subquestnum = 1;
                   7403:             my $subquestions = $currentquest;
1.691     raeburn  7404:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  7405:             foreach my $subans (@subanswers_needed) {
                   7406:                 my $subans_length =
                   7407:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   7408:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   7409:                 $subquestions   = substr($subquestions,$subans_length);
                   7410:                 $quest_id = "$questnum.$subquestnum";
                   7411:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   7412:                     ($$scantron_config{'Qon'} eq 'number')) {
                   7413:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   7414:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  7415:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7416:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7417:                 } else {
                   7418:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  7419:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   7420:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   7421:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7422:                 }
                   7423:                 $subquestnum ++;
                   7424:             }
                   7425:         } else {
                   7426:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   7427:                 ($$scantron_config{'Qon'} eq 'number')) {
                   7428:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   7429:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7430:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7431:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7432:             } else {
                   7433:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   7434:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  7435:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   7436:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  7437:             }
                   7438:         }
                   7439:     }
                   7440:     $record{'scantron.maxquest'}=$questnum;
                   7441:     return \%record;
                   7442: }
1.447     foxr     7443: 
1.691     raeburn  7444: sub get_master_seq {
1.788     raeburn  7445:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
1.691     raeburn  7446:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   7447:                    (ref($symb_to_resource) eq 'HASH'));
1.788     raeburn  7448:     if ($need_symb_in_map) {
                   7449:         return unless (ref($symb_for_examcode) eq 'HASH');
                   7450:     }
1.691     raeburn  7451:     my $resource_error;
                   7452:     foreach my $resource (@{$resources}) {
                   7453:         my $ressymb;
                   7454:         if (ref($resource)) {
                   7455:             $ressymb = $resource->symb();
                   7456:             push(@{$master_seq},$ressymb);
                   7457:             $symb_to_resource->{$ressymb} = $resource;
1.788     raeburn  7458:             if ($need_symb_in_map) {
                   7459:                 unless ($resource->is_map()) {
                   7460:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   7461:                     unless (exists($symb_for_examcode->{$map})) {
                   7462:                         $symb_for_examcode->{$map} = $ressymb;
                   7463:                     }
                   7464:                 }
                   7465:             }
1.691     raeburn  7466:         } else {
                   7467:             $resource_error = 1;
                   7468:             last;
                   7469:         }
                   7470:     }
                   7471:     return $resource_error;
                   7472: }
                   7473: 
                   7474: sub get_respnum_lookups {
                   7475:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   7476:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   7477:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   7478:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   7479:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   7480:                    (ref($startline) eq 'HASH'));
                   7481:     my ($user,$scancode);
                   7482:     if ((exists($record->{'scantron.CODE'})) &&
                   7483:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   7484:         $scancode = $record->{'scantron.CODE'};
                   7485:     } else {
                   7486:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   7487:     }
                   7488:     my @mapresources =
                   7489:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   7490:                      $orderedforcode);
                   7491:     my $total = 0;
                   7492:     my $count = 0;
                   7493:     foreach my $resource (@mapresources) {
                   7494:         my $id = $resource->id();
                   7495:         my $symb = $resource->symb();
                   7496:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   7497:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   7498:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   7499:                 if ($respnum ne '') {
                   7500:                     $respnumlookup->{$count} = $respnum;
                   7501:                     $startline->{$count} = $total;
                   7502:                     $total += $bubble_lines_per_response{$respnum};
                   7503:                     $count ++;
                   7504:                 }
                   7505:             }
                   7506:         }
                   7507:     }
                   7508:     return $total;
                   7509: }
                   7510: 
1.503     raeburn  7511: sub scantron_validator_lettnum {
                   7512:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  7513:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   7514:         $randompick,$respnumlookup) = @_;
1.503     raeburn  7515: 
                   7516:     # Qon 'letter' implies for each slot in currquest we have:
                   7517:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   7518:     #    about anything else (esp. a value of Qoff) for missing
                   7519:     #    bubbles.
                   7520:     #
                   7521:     # Qon 'number' implies each slot gives a digit that indexes the
                   7522:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   7523:     #    and * or ? for double bubbles on a single line.
                   7524:     #
1.447     foxr     7525: 
1.503     raeburn  7526:     my $matchon;
                   7527:     if ($$scantron_config{'Qon'} eq 'letter') {
                   7528:         $matchon = '[A-Z]';
                   7529:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   7530:         $matchon = '\d';
                   7531:     }
                   7532:     my $occurrences = 0;
1.691     raeburn  7533:     my $responsenum = $questnum-1;
                   7534:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7535:        $responsenum = $respnumlookup->{$questnum-1} 
                   7536:     }
                   7537:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7538:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7539:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7540:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7541:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7542:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  7543:         my @singlelines = split('',$currquest);
                   7544:         foreach my $entry (@singlelines) {
                   7545:             $occurrences = &occurence_count($entry,$matchon);
                   7546:             if ($occurrences > 1) {
                   7547:                 last;
                   7548:             }
1.691     raeburn  7549:         }
1.503     raeburn  7550:     } else {
                   7551:         $occurrences = &occurence_count($currquest,$matchon); 
                   7552:     }
                   7553:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   7554:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   7555:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   7556:             my $bubble = substr($currquest,$ans,1);
                   7557:             if ($bubble =~ /$matchon/ ) {
                   7558:                 if ($$scantron_config{'Qon'} eq 'number') {
                   7559:                     if ($bubble == 0) {
                   7560:                         $bubble = 10; 
                   7561:                     }
                   7562:                     $record->{"scantron.$ansnum.answer"} = 
                   7563:                         $alphabet->[$bubble-1];
                   7564:                 } else {
                   7565:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   7566:                 }
                   7567:             } else {
                   7568:                 $record->{"scantron.$ansnum.answer"}='';
                   7569:             }
                   7570:             $ansnum++;
                   7571:         }
                   7572:     } elsif (!defined($currquest)
                   7573:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   7574:             || (&occurence_count($currquest,$matchon) == 0)) {
                   7575:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   7576:             $record->{"scantron.$ansnum.answer"}='';
                   7577:             $ansnum++;
                   7578:         }
                   7579:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   7580:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   7581:         }
                   7582:     } else {
                   7583:         if ($$scantron_config{'Qon'} eq 'number') {
                   7584:             $currquest = &digits_to_letters($currquest);            
                   7585:         }
                   7586:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   7587:             my $bubble = substr($currquest,$ans,1);
                   7588:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   7589:             $ansnum++;
                   7590:         }
                   7591:     }
                   7592:     return $ansnum;
                   7593: }
1.447     foxr     7594: 
1.503     raeburn  7595: sub scantron_validator_positional {
                   7596:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  7597:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   7598:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     7599: 
1.503     raeburn  7600:     # Otherwise there's a positional notation;
                   7601:     # each bubble line requires Qlength items, and there are filled in
                   7602:     # bubbles for each case where there 'Qon' characters.
                   7603:     #
1.447     foxr     7604: 
1.503     raeburn  7605:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     7606: 
1.503     raeburn  7607:     # If the split only gives us one element.. the full length of the
                   7608:     # answer string, no bubbles are filled in:
1.447     foxr     7609: 
1.507     raeburn  7610:     if ($answers_needed eq '') {
                   7611:         return;
                   7612:     }
                   7613: 
1.503     raeburn  7614:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   7615:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   7616:             $record->{"scantron.$ansnum.answer"}='';
                   7617:             $ansnum++;
                   7618:         }
                   7619:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   7620:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   7621:         }
                   7622:     } elsif (scalar(@array) == 2) {
                   7623:         my $location = length($array[0]);
                   7624:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   7625:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   7626:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   7627:             if ($ans eq $line_num) {
                   7628:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   7629:             } else {
                   7630:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   7631:             }
                   7632:             $ansnum++;
                   7633:          }
                   7634:     } else {
                   7635:         #  If there's more than one instance of a bubble character
                   7636:         #  That's a double bubble; with positional notation we can
                   7637:         #  record all the bubbles filled in as well as the
                   7638:         #  fact this response consists of multiple bubbles.
                   7639:         #
1.691     raeburn  7640:         my $responsenum = $questnum-1;
                   7641:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7642:             $responsenum = $respnumlookup->{$questnum-1}
                   7643:         }
                   7644:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7645:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7646:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7647:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7648:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7649:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  7650:             my $doubleerror = 0;
                   7651:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   7652:                    (!$doubleerror)) {
                   7653:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   7654:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   7655:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   7656:                if (length(@currarray) > 2) {
                   7657:                    $doubleerror = 1;
                   7658:                } 
                   7659:             }
                   7660:             if ($doubleerror) {
                   7661:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   7662:             }
                   7663:         } else {
                   7664:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   7665:         }
                   7666:         my $item = $ansnum;
                   7667:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   7668:             $record->{"scantron.$item.answer"} = '';
                   7669:             $item ++;
                   7670:         }
1.447     foxr     7671: 
1.503     raeburn  7672:         my @ans=@array;
                   7673:         my $i=0;
                   7674:         my $increment = 0;
                   7675:         while ($#ans) {
                   7676:             $i+=length($ans[0]) + $increment;
                   7677:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   7678:             my $bubble = $i%$$scantron_config{'Qlength'};
                   7679:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   7680:             shift(@ans);
                   7681:             $increment = 1;
                   7682:         }
                   7683:         $ansnum += $answers_needed;
1.82      albertel 7684:     }
1.503     raeburn  7685:     return $ansnum;
1.82      albertel 7686: }
                   7687: 
1.423     albertel 7688: =pod
                   7689: 
                   7690: =item scantron_add_delay
                   7691: 
                   7692:    Adds an error message that occurred during the grading phase to a
                   7693:    queue of messages to be shown after grading pass is complete
                   7694: 
                   7695:  Arguments:
1.424     albertel 7696:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 7697:    $scanline    - the scanline that caused the error
                   7698:    $errormesage - the error message
                   7699:    $errorcode   - a numeric code for the error
                   7700: 
                   7701:  Side Effects:
1.424     albertel 7702:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 7703: 
                   7704: =cut
                   7705: 
1.82      albertel 7706: sub scantron_add_delay {
1.140     albertel 7707:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   7708:     push(@$delayqueue,
                   7709: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   7710: 	  'ecode' => $errorcode }
                   7711: 	 );
1.82      albertel 7712: }
                   7713: 
1.423     albertel 7714: =pod
                   7715: 
                   7716: =item scantron_find_student
                   7717: 
1.424     albertel 7718:    Finds the username for the current scanline
                   7719: 
                   7720:   Arguments:
                   7721:    $scantron_record - hash result from scantron_parse_scanline
                   7722:    $scan_data       - hash of correction information 
                   7723:                       (see &scantron_getfile() form more information)
                   7724:    $idmap           - hash from &username_to_idmap()
                   7725:    $line            - number of current scanline
                   7726:  
                   7727:   Returns:
                   7728:    Either 'username:domain' or undef if unknown
                   7729: 
1.423     albertel 7730: =cut
                   7731: 
1.82      albertel 7732: sub scantron_find_student {
1.157     albertel 7733:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 7734:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 7735:     if ($scanID =~ /^\s*$/) {
                   7736:  	return &scan_data($scan_data,"$line.user");
                   7737:     }
1.83      albertel 7738:     foreach my $id (keys(%$idmap)) {
1.157     albertel 7739:  	if (lc($id) eq lc($scanID)) {
                   7740:  	    return $$idmap{$id};
                   7741:  	}
1.83      albertel 7742:     }
                   7743:     return undef;
                   7744: }
                   7745: 
1.423     albertel 7746: =pod
                   7747: 
                   7748: =item scantron_filter
                   7749: 
1.424     albertel 7750:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   7751:    hidden resources was selected
                   7752: 
1.423     albertel 7753: =cut
                   7754: 
1.83      albertel 7755: sub scantron_filter {
                   7756:     my ($curres)=@_;
1.331     albertel 7757: 
                   7758:     if (ref($curres) && $curres->is_problem()) {
                   7759: 	# if the user has asked to not have either hidden
                   7760: 	# or 'randomout' controlled resources to be graded
                   7761: 	# don't include them
                   7762: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7763: 	    && $curres->randomout) {
                   7764: 	    return 0;
                   7765: 	}
1.83      albertel 7766: 	return 1;
                   7767:     }
                   7768:     return 0;
1.82      albertel 7769: }
                   7770: 
1.423     albertel 7771: =pod
                   7772: 
                   7773: =item scantron_process_corrections
                   7774: 
1.424     albertel 7775:    Gets correction information out of submitted form data and corrects
                   7776:    the scanline
                   7777: 
1.423     albertel 7778: =cut
                   7779: 
1.157     albertel 7780: sub scantron_process_corrections {
                   7781:     my ($r) = @_;
1.754     raeburn  7782:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7783:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7784:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 7785:     my $which=$env{'form.scantron_line'};
1.200     albertel 7786:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 7787:     my ($skip,$err,$errmsg);
1.257     albertel 7788:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 7789: 	$skip=1;
1.257     albertel 7790:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   7791: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   7792: 	    $env{'form.scantron_domain'};
1.157     albertel 7793: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   7794: 	($line,$err,$errmsg)=
                   7795: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   7796: 				     'ID',{'newid'=>$newid,
1.257     albertel 7797: 				    'username'=>$env{'form.scantron_username'},
                   7798: 				    'domain'=>$env{'form.scantron_domain'}});
                   7799:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   7800: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 7801: 	my $newCODE;
1.192     albertel 7802: 	my %args;
1.190     albertel 7803: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 7804: 	    $newCODE='use_unfound';
1.190     albertel 7805: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 7806: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 7807: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 7808: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 7809: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 7810: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 7811: 	}
1.257     albertel 7812: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 7813: 	    $args{'CODE_ignore_dup'}=1;
                   7814: 	}
                   7815: 	$args{'CODE'}=$newCODE;
1.186     albertel 7816: 	($line,$err,$errmsg)=
                   7817: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7818: 				     'CODE',\%args);
1.257     albertel 7819:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7820: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7821: 	    ($line,$err,$errmsg)=
                   7822: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7823: 					 $which,'answer',
                   7824: 					 { 'question'=>$question,
1.503     raeburn  7825: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7826:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7827: 	    if ($err) { last; }
                   7828: 	}
                   7829:     }
                   7830:     if ($err) {
1.703     bisitz   7831:         $r->print(
                   7832:             '<p class="LC_error">'
                   7833:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7834:                 $errmsg)
1.704     raeburn  7835:            .'</p>');
1.157     albertel 7836:     } else {
1.200     albertel 7837: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7838: 	&scantron_putfile($scanlines,$scan_data);
                   7839:     }
                   7840: }
                   7841: 
1.423     albertel 7842: =pod
                   7843: 
                   7844: =item reset_skipping_status
                   7845: 
1.424     albertel 7846:    Forgets the current set of remember skipped scanlines (and thus
                   7847:    reverts back to considering all lines in the
                   7848:    scantron_skipped_<filename> file)
                   7849: 
1.423     albertel 7850: =cut
                   7851: 
1.200     albertel 7852: sub reset_skipping_status {
                   7853:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7854:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7855:     &scantron_putfile(undef,$scan_data);
                   7856: }
                   7857: 
1.423     albertel 7858: =pod
                   7859: 
                   7860: =item start_skipping
                   7861: 
1.424     albertel 7862:    Marks a scanline to be skipped. 
                   7863: 
1.423     albertel 7864: =cut
                   7865: 
1.376     albertel 7866: sub start_skipping {
1.200     albertel 7867:     my ($scan_data,$i)=@_;
                   7868:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7869:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7870: 	$remembered{$i}=2;
                   7871:     } else {
                   7872: 	$remembered{$i}=1;
                   7873:     }
1.200     albertel 7874:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7875: }
                   7876: 
1.423     albertel 7877: =pod
                   7878: 
                   7879: =item should_be_skipped
                   7880: 
1.424     albertel 7881:    Checks whether a scanline should be skipped.
                   7882: 
1.423     albertel 7883: =cut
                   7884: 
1.200     albertel 7885: sub should_be_skipped {
1.376     albertel 7886:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7887:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7888: 	# not redoing old skips
1.376     albertel 7889: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7890: 	return 0;
                   7891:     }
                   7892:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7893: 
                   7894:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7895: 	return 0;
                   7896:     }
1.200     albertel 7897:     return 1;
                   7898: }
                   7899: 
1.423     albertel 7900: =pod
                   7901: 
                   7902: =item remember_current_skipped
                   7903: 
1.424     albertel 7904:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7905:    file and remembers them into scan_data for later use.
                   7906: 
1.423     albertel 7907: =cut
                   7908: 
1.200     albertel 7909: sub remember_current_skipped {
                   7910:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7911:     my %to_remember;
                   7912:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7913: 	if ($scanlines->{'skipped'}[$i]) {
                   7914: 	    $to_remember{$i}=1;
                   7915: 	}
                   7916:     }
1.376     albertel 7917: 
1.200     albertel 7918:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7919:     &scantron_putfile(undef,$scan_data);
                   7920: }
                   7921: 
1.423     albertel 7922: =pod
                   7923: 
                   7924: =item check_for_error
                   7925: 
1.424     albertel 7926:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  7927:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7928:     something went wrong.
                   7929: 
1.423     albertel 7930: =cut
                   7931: 
1.200     albertel 7932: sub check_for_error {
                   7933:     my ($r,$result)=@_;
                   7934:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7935: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7936:     }
                   7937: }
1.157     albertel 7938: 
1.423     albertel 7939: =pod
                   7940: 
                   7941: =item scantron_warning_screen
                   7942: 
1.424     albertel 7943:    Interstitial screen to make sure the operator has selected the
                   7944:    correct options before we start the validation phase.
                   7945: 
1.423     albertel 7946: =cut
                   7947: 
1.203     albertel 7948: sub scantron_warning_screen {
1.650     raeburn  7949:     my ($button_text,$symb)=@_;
1.257     albertel 7950:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  7951:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7952:     my $CODElist;
1.284     albertel 7953:     if ($scantron_config{'CODElocation'} &&
                   7954: 	$scantron_config{'CODEstart'} &&
                   7955: 	$scantron_config{'CODElength'}) {
                   7956: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   7957: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7958: 	$CODElist=
1.492     albertel 7959: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7960: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7961:     }
1.663     raeburn  7962:     my $lastbubblepoints;
                   7963:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7964:         $lastbubblepoints =
                   7965:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7966:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7967:     }
1.770     raeburn  7968:     return '
1.203     albertel 7969: <p>
1.492     albertel 7970: <span class="LC_warning">
1.705     raeburn  7971: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7972: </p>
                   7973: <table>
1.492     albertel 7974: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7975: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  7976: '.$CODElist.$lastbubblepoints.'
1.203     albertel 7977: </table>
1.680     raeburn  7978: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  7979: '.&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  7980: ';
1.203     albertel 7981: }
                   7982: 
1.423     albertel 7983: =pod
                   7984: 
                   7985: =item scantron_do_warning
                   7986: 
1.424     albertel 7987:    Check if the operator has picked something for all required
                   7988:    fields. Error out if something is missing.
                   7989: 
1.423     albertel 7990: =cut
                   7991: 
1.203     albertel 7992: sub scantron_do_warning {
1.608     www      7993:     my ($r,$symb)=@_;
1.203     albertel 7994:     if (!$symb) {return '';}
1.324     albertel 7995:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7996:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7997:     if ( $env{'form.selectpage'} eq '' ||
                   7998: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7999: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  8000: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 8001: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 8002: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 8003: 	} 
1.257     albertel 8004: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  8005: 	    $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  8006: 	}
1.257     albertel 8007: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  8008: 	    $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  8009: 	}
1.237     albertel 8010:     } else {
1.650     raeburn  8011: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  8012:         my ($checksec,@possibles) = &gradable_sections();
                   8013:         my $gradesections;
                   8014:         if ($checksec) {
                   8015:             my $file=$env{'form.scantron_selectfile'};
                   8016:             if (&valid_file($file)) {
                   8017:                 my %bysec = &scantron_get_sections();
                   8018:                 my $table;
                   8019:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   8020:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   8021:                     $table = &Apache::loncommon::start_data_table()."\n".
                   8022:                              &Apache::loncommon::start_data_table_header_row().
                   8023:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   8024:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   8025:                     if ($bysec{'none'}) {
                   8026:                         $table .= &Apache::loncommon::start_data_table_row().
                   8027:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   8028:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8029:                     }
                   8030:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   8031:                         next if ($sec eq 'none');
                   8032:                         $table .= &Apache::loncommon::start_data_table_row().
                   8033:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   8034:                                   &Apache::loncommon::end_data_table_row()."\n";
                   8035:                     }
                   8036:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   8037:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   8038:                                       '<p>'.$table.'</p>';
                   8039:                     if (@possibles) {
                   8040:                         $gradesections .= '<p>'.
                   8041:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   8042:                                               scalar(@possibles)).'<br />'.
                   8043:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   8044:                                               '<i>'.$checksec.'</i>').' ';
                   8045:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   8046:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   8047:                         }
                   8048:                         $gradesections .= '</p>';
                   8049:                     }
                   8050:                 }
                   8051:             } else {
                   8052:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   8053:             }
                   8054:         }
1.663     raeburn  8055:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 8056: 	$r->print('
1.770     raeburn  8057: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 8058: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 8059: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 8060: ');
1.237     albertel 8061:     }
1.614     www      8062:     $r->print("</form><br />");
1.203     albertel 8063:     return '';
                   8064: }
                   8065: 
1.423     albertel 8066: =pod
                   8067: 
                   8068: =item scantron_form_start
                   8069: 
1.424     albertel 8070:     html hidden input for remembering all selected grading options
                   8071: 
1.423     albertel 8072: =cut
                   8073: 
1.203     albertel 8074: sub scantron_form_start {
                   8075:     my ($max_bubble)=@_;
                   8076:     my $result= <<SCANTRONFORM;
                   8077: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 8078:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   8079:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   8080:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 8081:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 8082:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   8083:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   8084:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   8085:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 8086:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 8087: SCANTRONFORM
1.447     foxr     8088: 
                   8089:   my $line = 0;
                   8090:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   8091:        my $chunk =
                   8092: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     8093:        $chunk .=
                   8094: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  8095:        $chunk .= 
                   8096:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  8097:        $chunk .=
                   8098:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  8099:        $chunk .=
                   8100:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     8101:        $result .= $chunk;
                   8102:        $line++;
1.691     raeburn  8103:     }
1.203     albertel 8104:     return $result;
                   8105: }
                   8106: 
1.423     albertel 8107: =pod
                   8108: 
                   8109: =item scantron_validate_file
                   8110: 
1.659     raeburn  8111:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 8112: 
                   8113:     Also processes any necessary information resets that need to
                   8114:     occur before validation begins (ignore previous corrections,
                   8115:     restarting the skipped records processing)
                   8116: 
1.423     albertel 8117: =cut
                   8118: 
1.157     albertel 8119: sub scantron_validate_file {
1.608     www      8120:     my ($r,$symb) = @_;
1.157     albertel 8121:     if (!$symb) {return '';}
1.324     albertel 8122:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 8123:     
1.703     bisitz   8124:     # do the detection of only doing skipped records first before we delete
1.424     albertel 8125:     # them when doing the corrections reset
1.257     albertel 8126:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 8127: 	&reset_skipping_status();
                   8128:     }
1.257     albertel 8129:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 8130: 	&remember_current_skipped();
1.257     albertel 8131: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 8132:     }
                   8133: 
1.257     albertel 8134:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 8135: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   8136: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   8137: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 8138: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 8139:     }
1.200     albertel 8140: 
1.257     albertel 8141:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 8142: 	&scantron_process_corrections($r);
                   8143:     }
1.770     raeburn  8144: 
                   8145:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   8146:     my ($checksec,@gradable);
                   8147:     if ($env{'request.course.sec'}) {
                   8148:         ($checksec,my @possibles) = &gradable_sections();
                   8149:         if ($checksec) {
                   8150:             if (@possibles) {
                   8151:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   8152:                 if (@chosensecs) {
                   8153:                     foreach my $sec (@chosensecs) {
                   8154:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   8155:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   8156:                                 push(@gradable,$sec);
                   8157:                             }
                   8158:                         }
                   8159:                     }
                   8160:                 }
                   8161:             }
                   8162:             $r->print('<p><table>');
                   8163:             if (@gradable) {
                   8164:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   8165:                 $r->print(
                   8166:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   8167:             } else {
                   8168:                 $r->print(
                   8169:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   8170:             }
                   8171:             $r->print('</table></p>');
                   8172:         }
                   8173:     }
                   8174:     $r->rflush();
                   8175: 
1.157     albertel 8176:     #get the student pick code ready
                   8177:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  8178:     my $nav_error;
1.754     raeburn  8179:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8180:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8181:     if ($nav_error) {
                   8182:         $r->print(&navmap_errormsg());
                   8183:         return '';
                   8184:     }
1.203     albertel 8185:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  8186:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8187:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   8188:     }
1.157     albertel 8189:     $r->print($result);
                   8190:     
1.334     albertel 8191:     my @validate_phases=( 'sequence',
                   8192: 			  'ID',
1.157     albertel 8193: 			  'CODE',
                   8194: 			  'doublebubble',
                   8195: 			  'missingbubbles');
1.257     albertel 8196:     if (!$env{'form.validatepass'}) {
                   8197: 	$env{'form.validatepass'} = 0;
1.157     albertel 8198:     }
1.257     albertel 8199:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  8200:     my %skipbysec=();
1.448     foxr     8201: 
1.157     albertel 8202:     my $stop=0;
                   8203:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  8204: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 8205: 	$r->rflush();
1.691     raeburn  8206:      
1.157     albertel 8207: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   8208: 	{
                   8209: 	    no strict 'refs';
1.770     raeburn  8210:             my @extras=();
                   8211:             if ($validate_phases[$currentphase] eq 'ID') {
                   8212:                 @extras = (\%skipbysec,$checksec,@gradable);
                   8213:             }
                   8214: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 8215: 	}
                   8216:     }
                   8217:     if (!$stop) {
1.650     raeburn  8218: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  8219:         my $secinfo;
                   8220:         if (keys(%skipbysec) > 0) {
                   8221:             my $seclist = '<ul>';
                   8222:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   8223:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   8224:             }
                   8225:             $seclist .= '</ul>';
                   8226:             $secinfo = '<p class="LC_info">'.
                   8227:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   8228:                            $seclist).
                   8229:                        '</p>';
                   8230:         }
1.542     raeburn  8231: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  8232:                   $secinfo.$warning.
1.542     raeburn  8233:                   &mt('Perform verification for each student after storage of submissions?').
                   8234:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   8235:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   8236:                   ('&nbsp;'x3).'<label>'.
                   8237:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   8238:                   '</label></span><br />'.
                   8239:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  8240:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  8241:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   8242:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 8243:     } else {
                   8244: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   8245: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   8246:     }
                   8247:     if ($stop) {
1.334     albertel 8248: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  8249: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 8250: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 8251: 
1.650     raeburn  8252: 	    $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 8253: 	} else {
1.503     raeburn  8254:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  8255: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  8256:             } else {
1.539     riegler  8257:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  8258:             }
1.492     albertel 8259: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   8260: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   8261: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 8262: 	}
1.157     albertel 8263:     }
1.614     www      8264:     $r->print(" </form><br />");
1.157     albertel 8265:     return '';
                   8266: }
                   8267: 
1.423     albertel 8268: 
                   8269: =pod
                   8270: 
                   8271: =item scantron_remove_file
                   8272: 
1.659     raeburn  8273:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 8274:    scantron_original_<filename> is never removed
                   8275: 
                   8276: 
1.423     albertel 8277: =cut
                   8278: 
1.200     albertel 8279: sub scantron_remove_file {
1.192     albertel 8280:     my ($which)=@_;
1.257     albertel 8281:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8282:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8283:     my $file='scantron_';
1.200     albertel 8284:     if ($which eq 'corrected' || $which eq 'skipped') {
                   8285: 	$file.=$which.'_';
1.192     albertel 8286:     } else {
                   8287: 	return 'refused';
                   8288:     }
1.257     albertel 8289:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 8290:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   8291: }
                   8292: 
1.423     albertel 8293: 
                   8294: =pod
                   8295: 
                   8296: =item scantron_remove_scan_data
                   8297: 
1.659     raeburn  8298:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 8299:    data file.  (In the case that both the are doing skipped records we need
                   8300:    to remember the old skipped lines for the time being so that element
                   8301:    persists for a while.)
                   8302: 
1.423     albertel 8303: =cut
                   8304: 
1.200     albertel 8305: sub scantron_remove_scan_data {
1.257     albertel 8306:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8307:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 8308:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   8309:     my @todelete;
1.257     albertel 8310:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 8311:     foreach my $key (@keys) {
                   8312: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 8313: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 8314: 		$key=~/remember_skipping/) {
                   8315: 		next;
                   8316: 	    }
1.192     albertel 8317: 	    push(@todelete,$key);
                   8318: 	}
                   8319:     }
1.200     albertel 8320:     my $result;
1.192     albertel 8321:     if (@todelete) {
1.491     albertel 8322: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   8323: 				       \@todelete,$cdom,$cname);
                   8324:     } else {
                   8325: 	$result = 'ok';
1.192     albertel 8326:     }
                   8327:     return $result;
                   8328: }
                   8329: 
1.423     albertel 8330: 
                   8331: =pod
                   8332: 
                   8333: =item scantron_getfile
                   8334: 
1.659     raeburn  8335:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 8336:     the scan_data hash
                   8337:   
                   8338:   Arguments:
                   8339:     None
                   8340: 
                   8341:   Returns:
                   8342:     2 hash references
                   8343: 
                   8344:      - first one has 
                   8345:          orig      -
                   8346:          corrected -
                   8347:          skipped   -  each of which points to an array ref of the specified
                   8348:                       file broken up into individual lines
                   8349:          count     - number of scanlines
                   8350:  
                   8351:      - second is the scan_data hash possible keys are
1.425     albertel 8352:        ($number refers to scanline numbered $number and thus the key affects
                   8353:         only that scanline
                   8354:         $bubline refers to the specific bubble line element and the aspects
                   8355:         refers to that specific bubble line element)
                   8356: 
                   8357:        $number.user - username:domain to use
                   8358:        $number.CODE_ignore_dup 
                   8359:                     - ignore the duplicate CODE error 
                   8360:        $number.useCODE
                   8361:                     - use the CODE in the scanline as is
                   8362:        $number.no_bubble.$bubline
                   8363:                     - it is valid that there is no bubbled in bubble
                   8364:                       at $number $bubline
                   8365:        remember_skipping
                   8366:                     - a frozen hash containing keys of $number and values
                   8367:                       of either 
                   8368:                         1 - we are on a 'do skipped records pass' and plan
                   8369:                             on processing this line
                   8370:                         2 - we are on a 'do skipped records pass' and this
                   8371:                             scanline has been marked to skip yet again
1.424     albertel 8372: 
1.423     albertel 8373: =cut
                   8374: 
1.157     albertel 8375: sub scantron_getfile {
1.200     albertel 8376:     #FIXME really would prefer a scantron directory
1.257     albertel 8377:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8378:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 8379:     my $lines;
                   8380:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8381: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 8382:     my %scanlines;
                   8383:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   8384:     my $temp=$scanlines{'orig'};
                   8385:     $scanlines{'count'}=$#$temp;
                   8386: 
                   8387:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8388: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 8389:     if ($lines eq '-1') {
                   8390: 	$scanlines{'corrected'}=[];
                   8391:     } else {
                   8392: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   8393:     }
                   8394:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 8395: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 8396:     if ($lines eq '-1') {
                   8397: 	$scanlines{'skipped'}=[];
                   8398:     } else {
                   8399: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   8400:     }
1.175     albertel 8401:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 8402:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   8403:     my %scan_data = @tmp;
                   8404:     return (\%scanlines,\%scan_data);
                   8405: }
                   8406: 
1.423     albertel 8407: =pod
                   8408: 
                   8409: =item lonnet_putfile
                   8410: 
1.424     albertel 8411:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   8412: 
                   8413:  Arguments:
                   8414:    $contents - data to store
                   8415:    $filename - filename to store $contents into
                   8416: 
                   8417:  Returns:
                   8418:    result value from &Apache::lonnet::finishuserfileupload
                   8419: 
1.423     albertel 8420: =cut
                   8421: 
1.157     albertel 8422: sub lonnet_putfile {
                   8423:     my ($contents,$filename)=@_;
1.257     albertel 8424:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8425:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8426:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 8427:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 8428: 
                   8429: }
                   8430: 
1.423     albertel 8431: =pod
                   8432: 
                   8433: =item scantron_putfile
                   8434: 
1.659     raeburn  8435:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 8436:     scan_data hash. (Does not modify the original version only the
                   8437:     corrected and skipped versions.
                   8438: 
                   8439:  Arguments:
                   8440:     $scanlines - hash ref that looks like the first return value from
                   8441:                  &scantron_getfile()
                   8442:     $scan_data - hash ref that looks like the second return value from
                   8443:                  &scantron_getfile()
                   8444: 
1.423     albertel 8445: =cut
                   8446: 
1.157     albertel 8447: sub scantron_putfile {
                   8448:     my ($scanlines,$scan_data) = @_;
1.200     albertel 8449:     #FIXME really would prefer a scantron directory
1.257     albertel 8450:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8451:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 8452:     if ($scanlines) {
                   8453: 	my $prefix='scantron_';
1.157     albertel 8454: # no need to update orig, shouldn't change
                   8455: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 8456: #		    $env{'form.scantron_selectfile'});
1.200     albertel 8457: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   8458: 			$prefix.'corrected_'.
1.257     albertel 8459: 			$env{'form.scantron_selectfile'});
1.200     albertel 8460: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   8461: 			$prefix.'skipped_'.
1.257     albertel 8462: 			$env{'form.scantron_selectfile'});
1.200     albertel 8463:     }
1.175     albertel 8464:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 8465: }
                   8466: 
1.423     albertel 8467: =pod
                   8468: 
                   8469: =item scantron_get_line
                   8470: 
1.424     albertel 8471:    Returns the correct version of the scanline
                   8472: 
                   8473:  Arguments:
                   8474:     $scanlines - hash ref that looks like the first return value from
                   8475:                  &scantron_getfile()
                   8476:     $scan_data - hash ref that looks like the second return value from
                   8477:                  &scantron_getfile()
                   8478:     $i         - number of the requested line (starts at 0)
                   8479: 
                   8480:  Returns:
                   8481:    A scanline, (either the original or the corrected one if it
                   8482:    exists), or undef if the requested scanline should be
                   8483:    skipped. (Either because it's an skipped scanline, or it's an
                   8484:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   8485:    pass.
                   8486: 
1.423     albertel 8487: =cut
                   8488: 
1.157     albertel 8489: sub scantron_get_line {
1.200     albertel 8490:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 8491:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   8492:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 8493:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   8494:     return $scanlines->{'orig'}[$i]; 
                   8495: }
                   8496: 
1.423     albertel 8497: =pod
                   8498: 
                   8499: =item scantron_todo_count
                   8500: 
1.424     albertel 8501:     Counts the number of scanlines that need processing.
                   8502: 
                   8503:  Arguments:
                   8504:     $scanlines - hash ref that looks like the first return value from
                   8505:                  &scantron_getfile()
                   8506:     $scan_data - hash ref that looks like the second return value from
                   8507:                  &scantron_getfile()
                   8508: 
                   8509:  Returns:
                   8510:     $count - number of scanlines to process
                   8511: 
1.423     albertel 8512: =cut
                   8513: 
1.200     albertel 8514: sub get_todo_count {
                   8515:     my ($scanlines,$scan_data)=@_;
                   8516:     my $count=0;
                   8517:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8518: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   8519: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8520: 	$count++;
                   8521:     }
                   8522:     return $count;
                   8523: }
                   8524: 
1.423     albertel 8525: =pod
                   8526: 
                   8527: =item scantron_put_line
                   8528: 
1.659     raeburn  8529:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 8530:     data file.
                   8531: 
                   8532:  Arguments:
                   8533:     $scanlines - hash ref that looks like the first return value from
                   8534:                  &scantron_getfile()
                   8535:     $scan_data - hash ref that looks like the second return value from
                   8536:                  &scantron_getfile()
                   8537:     $i         - line number to update
                   8538:     $newline   - contents of the updated scanline
                   8539:     $skip      - if true make the line for skipping and update the
                   8540:                  'skipped' file
                   8541: 
1.423     albertel 8542: =cut
                   8543: 
1.157     albertel 8544: sub scantron_put_line {
1.200     albertel 8545:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 8546:     if ($skip) {
                   8547: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 8548: 	&start_skipping($scan_data,$i);
1.157     albertel 8549: 	return;
                   8550:     }
                   8551:     $scanlines->{'corrected'}[$i]=$newline;
                   8552: }
                   8553: 
1.423     albertel 8554: =pod
                   8555: 
                   8556: =item scantron_clear_skip
                   8557: 
1.424     albertel 8558:    Remove a line from the 'skipped' file
                   8559: 
                   8560:  Arguments:
                   8561:     $scanlines - hash ref that looks like the first return value from
                   8562:                  &scantron_getfile()
                   8563:     $scan_data - hash ref that looks like the second return value from
                   8564:                  &scantron_getfile()
                   8565:     $i         - line number to update
                   8566: 
1.423     albertel 8567: =cut
                   8568: 
1.376     albertel 8569: sub scantron_clear_skip {
                   8570:     my ($scanlines,$scan_data,$i)=@_;
                   8571:     if (exists($scanlines->{'skipped'}[$i])) {
                   8572: 	undef($scanlines->{'skipped'}[$i]);
                   8573: 	return 1;
                   8574:     }
                   8575:     return 0;
                   8576: }
                   8577: 
1.423     albertel 8578: =pod
                   8579: 
                   8580: =item scantron_filter_not_exam
                   8581: 
1.424     albertel 8582:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   8583:    filter out resources that are not marked as 'exam' mode
                   8584: 
1.423     albertel 8585: =cut
                   8586: 
1.334     albertel 8587: sub scantron_filter_not_exam {
                   8588:     my ($curres)=@_;
                   8589:     
                   8590:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   8591: 	# if the user has asked to not have either hidden
                   8592: 	# or 'randomout' controlled resources to be graded
                   8593: 	# don't include them
                   8594: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   8595: 	    && $curres->randomout) {
                   8596: 	    return 0;
                   8597: 	}
                   8598: 	return 1;
                   8599:     }
                   8600:     return 0;
                   8601: }
                   8602: 
1.423     albertel 8603: =pod
                   8604: 
                   8605: =item scantron_validate_sequence
                   8606: 
1.424     albertel 8607:     Validates the selected sequence, checking for resource that are
                   8608:     not set to exam mode.
                   8609: 
1.423     albertel 8610: =cut
                   8611: 
1.334     albertel 8612: sub scantron_validate_sequence {
                   8613:     my ($r,$currentphase) = @_;
                   8614: 
                   8615:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8616:     unless (ref($navmap)) {
                   8617:         $r->print(&navmap_errormsg());
                   8618:         return (1,$currentphase);
                   8619:     }
1.334     albertel 8620:     my (undef,undef,$sequence)=
                   8621: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8622: 
                   8623:     my $map=$navmap->getResourceByUrl($sequence);
                   8624: 
                   8625:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   8626:                                     value="ignore" />');
                   8627:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   8628: 	my @resources=
                   8629: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   8630: 	if (@resources) {
1.675     bisitz   8631: 	    $r->print(
                   8632:                 '<p class="LC_warning">'
                   8633:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   8634:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   8635:                    .' work correctly.')
                   8636:                .'</p>'
                   8637:             );
1.334     albertel 8638: 	    return (1,$currentphase);
                   8639: 	}
                   8640:     }
                   8641: 
                   8642:     return (0,$currentphase+1);
                   8643: }
                   8644: 
1.423     albertel 8645: 
                   8646: 
1.157     albertel 8647: sub scantron_validate_ID {
1.770     raeburn  8648:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 8649:     
                   8650:     #get student info
                   8651:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8652:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  8653:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 8654: 
                   8655:     #get scantron line setup
1.754     raeburn  8656:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8657:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  8658: 
                   8659:     my $nav_error;
1.649     raeburn  8660:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  8661:     if ($nav_error) {
                   8662:         $r->print(&navmap_errormsg());
                   8663:         return(1,$currentphase);
                   8664:     }
1.157     albertel 8665: 
                   8666:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  8667:     my $unsavedskips = 0;
1.157     albertel 8668:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8669: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8670: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8671: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8672: 						 $scan_data);
                   8673: 	my $id=$$scan_record{'scantron.ID'};
                   8674: 	my $found;
                   8675: 	foreach my $checkid (keys(%idmap)) {
                   8676: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   8677: 	}
                   8678: 	if ($found) {
                   8679: 	    my $username=$idmap{$found};
1.770     raeburn  8680:             if ($checksec) {
                   8681:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   8682:                     my $stusec = $classlist->{$username}->[$secidx];
                   8683:                     if ($stusec ne $checksec) {
                   8684:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   8685:                             my $skip=1;
                   8686:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   8687:                             if (ref($skipbysec) eq 'HASH') {
                   8688:                                 if ($stusec eq '') {
                   8689:                                     $skipbysec->{'none'} ++;
                   8690:                                 } else {
                   8691:                                     $skipbysec->{$stusec} ++;
                   8692:                                 }
                   8693:                             }
                   8694:                             $unsavedskips ++;
                   8695:                             next;
                   8696:                         }
                   8697:                     }
                   8698:                 }
                   8699:             }
1.157     albertel 8700: 	    if ($found{'ids'}{$found}) {
                   8701: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   8702: 					 $line,'duplicateID',$found);
1.770     raeburn  8703:                 if ($unsavedskips) {
                   8704:                     &scantron_putfile($scanlines,$scan_data);
                   8705:                     $unsavedskips = 0;
                   8706:                 }
1.194     albertel 8707: 		return(1,$currentphase);
1.157     albertel 8708: 	    } elsif ($found{'usernames'}{$username}) {
                   8709: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   8710: 					 $line,'duplicateID',$username);
1.770     raeburn  8711:                 if ($unsavedskips) {
                   8712:                     &scantron_putfile($scanlines,$scan_data);
                   8713:                     $unsavedskips = 0;
                   8714:                 }
1.194     albertel 8715: 		return(1,$currentphase);
1.157     albertel 8716: 	    }
1.186     albertel 8717: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 8718: 	    $found{'ids'}{$found}++;
                   8719: 	    $found{'usernames'}{$username}++;
                   8720: 	} else {
                   8721: 	    if ($id =~ /^\s*$/) {
1.158     albertel 8722: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  8723:                 if (($checksec && $username ne '')) {
                   8724:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   8725:                         my $stusec = $classlist->{$username}->[$secidx];
                   8726:                         if ($stusec ne $checksec) {
                   8727:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   8728:                                 my $skip=1;
                   8729:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   8730:                                 if (ref($skipbysec) eq 'HASH') {
                   8731:                                     if ($stusec eq '') {
                   8732:                                         $skipbysec->{'none'} ++;
                   8733:                                     } else {
                   8734:                                         $skipbysec->{$stusec} ++;
                   8735:                                     }
                   8736:                                 }
                   8737:                                 $unsavedskips ++;
                   8738:                                 next;
                   8739:                             }
                   8740:                         }
                   8741:                     }
                   8742: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 8743: 		    &scantron_get_correction($r,$i,$scan_record,
                   8744: 					     \%scantron_config,
                   8745: 					     $line,'duplicateID',$username);
1.770     raeburn  8746:                     if ($unsavedskips) {
                   8747:                         &scantron_putfile($scanlines,$scan_data);
                   8748:                         $unsavedskips = 0;
                   8749:                     }
1.194     albertel 8750: 		    return(1,$currentphase);
1.157     albertel 8751: 		} elsif (!defined($username)) {
                   8752: 		    &scantron_get_correction($r,$i,$scan_record,
                   8753: 					     \%scantron_config,
                   8754: 					     $line,'incorrectID');
1.770     raeburn  8755:                     if ($unsavedskips) {
                   8756:                         &scantron_putfile($scanlines,$scan_data);
                   8757:                         $unsavedskips = 0;
                   8758:                     }
1.194     albertel 8759: 		    return(1,$currentphase);
1.157     albertel 8760: 		}
                   8761: 		$found{'usernames'}{$username}++;
                   8762: 	    } else {
                   8763: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   8764: 					 $line,'incorrectID');
1.770     raeburn  8765:                 if ($unsavedskips) {
                   8766:                     &scantron_putfile($scanlines,$scan_data);
                   8767:                     $unsavedskips = 0;
                   8768:                 }
1.194     albertel 8769: 		return(1,$currentphase);
1.157     albertel 8770: 	    }
                   8771: 	}
                   8772:     }
1.770     raeburn  8773:     if ($unsavedskips) {
                   8774:         &scantron_putfile($scanlines,$scan_data);
                   8775:         $unsavedskips = 0;
                   8776:     }
1.157     albertel 8777:     return (0,$currentphase+1);
                   8778: }
                   8779: 
1.770     raeburn  8780: sub scantron_get_sections {
                   8781:     my %bysec;
                   8782:     if ($env{'form.scantron_format'} ne '') {
                   8783:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   8784:         my ($scanlines,$scan_data)=&scantron_getfile();
                   8785:         my $classlist=&Apache::loncoursedata::get_classlist();
                   8786:         my %idmap=&username_to_idmap($classlist);
                   8787:         foreach my $key (keys(%idmap)) {
                   8788:             my $lckey = lc($key);
                   8789:             $idmap{$lckey} = $idmap{$key};
                   8790:         }
                   8791:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   8792:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8793:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   8794:             if ($line=~/^[\s\cz]*$/) { next; }
                   8795:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8796:                                                      $scan_data);
                   8797:             my $id=lc($$scan_record{'scantron.ID'});
                   8798:             if (exists($idmap{$id})) {
                   8799:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   8800:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   8801:                     if ($stusec eq '') {
                   8802:                         $bysec{'none'} ++;
                   8803:                     } else {
                   8804:                         $bysec{$stusec} ++;
                   8805:                     }
                   8806:                 }
                   8807:             }
                   8808:         }
                   8809:     }
                   8810:     return %bysec;
                   8811: }
1.423     albertel 8812: 
1.157     albertel 8813: sub scantron_get_correction {
1.691     raeburn  8814:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   8815:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 8816: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 8817: #to show both the current line and the previous one and allow skipping
                   8818: #the previous one or the current one
                   8819: 
1.333     albertel 8820:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   8821:         $r->print(
                   8822:             '<p class="LC_warning">'
                   8823:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   8824:                 "<b>$error</b>",
                   8825:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   8826:            ."</p> \n");
1.157     albertel 8827:     } else {
1.658     bisitz   8828:         $r->print(
                   8829:             '<p class="LC_warning">'
                   8830:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8831:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8832:            ."</p> \n");
                   8833:     }
                   8834:     my $message =
                   8835:         '<p>'
                   8836:        .&mt('The ID on the form is [_1]',
                   8837:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8838:        .'<br />'
1.665     raeburn  8839:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   8840:             $$scan_record{'scantron.LastName'},
                   8841:             $$scan_record{'scantron.FirstName'})
                   8842:        .'</p>';
1.242     albertel 8843: 
1.157     albertel 8844:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8845:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8846:                            # Array populated for doublebubble or
                   8847:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8848:                            # to validate radio button checking   
                   8849: 
1.157     albertel 8850:     if ($error =~ /ID$/) {
1.186     albertel 8851: 	if ($error eq 'incorrectID') {
1.658     bisitz   8852:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8853: 		      "</p>\n");
1.157     albertel 8854: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   8855:             $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 8856: 	}
1.242     albertel 8857: 	$r->print($message);
1.492     albertel 8858: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8859: 	$r->print("\n<ul><li> ");
                   8860: 	#FIXME it would be nice if this sent back the user ID and
                   8861: 	#could do partial userID matches
                   8862: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8863: 				       'scantron_username','scantron_domain'));
                   8864: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   8865: 	$r->print("\n:\n".
1.257     albertel 8866: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8867: 
                   8868: 	$r->print('</li>');
1.186     albertel 8869:     } elsif ($error =~ /CODE$/) {
                   8870: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   8871: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8872: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   8873: 	    $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 8874: 	}
1.658     bisitz   8875: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   8876: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8877:                  ."</p>\n");
1.242     albertel 8878: 	$r->print($message);
1.658     bisitz   8879: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8880: 	$r->print("\n<br /> ");
1.194     albertel 8881: 	my $i=0;
1.273     albertel 8882: 	if ($error eq 'incorrectCODE' 
                   8883: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8884: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8885: 	    if ($closest > 0) {
                   8886: 		foreach my $testcode (@{$closest}) {
                   8887: 		    my $checked='';
1.569     bisitz   8888: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8889: 		    $r->print("
                   8890:    <label>
1.569     bisitz   8891:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8892:        ".&mt("Use the similar CODE [_1] instead.",
                   8893: 	    "<b><tt>".$testcode."</tt></b>")."
                   8894:     </label>
                   8895:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8896: 		    $r->print("\n<br />");
                   8897: 		    $i++;
                   8898: 		}
1.194     albertel 8899: 	    }
                   8900: 	}
1.273     albertel 8901: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8902: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8903: 	    $r->print("
                   8904:     <label>
1.569     bisitz   8905:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  8906:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8907: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8908:     </label>");
1.273     albertel 8909: 	    $r->print("\n<br />");
                   8910: 	}
1.194     albertel 8911: 
1.597     wenzelju 8912: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8913: function change_radio(field) {
1.190     albertel 8914:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8915:     var i;
                   8916:     for (i=0;i<slct.length;i++) {
                   8917:         if (slct[i].value==field) { slct[i].checked=true; }
                   8918:     }
                   8919: }
                   8920: ENDSCRIPT
1.187     albertel 8921: 	my $href="/adm/pickcode?".
1.359     www      8922: 	   "form=".&escape("scantronupload").
                   8923: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8924: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8925: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8926: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8927: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8928: 	    $r->print("
                   8929:     <label>
                   8930:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8931:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8932: 	     "<a target='_blank' href='$href'>","</a>")."
                   8933:     </label> 
1.558     bisitz   8934:     ".&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 8935: 	    $r->print("\n<br />");
                   8936: 	}
1.492     albertel 8937: 	$r->print("
                   8938:     <label>
                   8939:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8940:        ".&mt("Use [_1] as the CODE.",
                   8941: 	     "</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 8942: 	$r->print("\n<br /><br />");
1.157     albertel 8943:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   8944: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8945: 
                   8946: 	# The form field scantron_questions is acutally a list of line numbers.
                   8947: 	# represented by this form so:
                   8948: 
1.691     raeburn  8949: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8950:                                                 $respnumlookup,$startline);
1.497     foxr     8951: 
1.157     albertel 8952: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8953: 		  $line_list.'" />');
1.242     albertel 8954: 	$r->print($message);
1.492     albertel 8955: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8956: 	foreach my $question (@{$arg}) {
1.503     raeburn  8957: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8958:                                                    $scan_record, $error,
                   8959:                                                    $randomorder,$randompick,
                   8960:                                                    $respnumlookup,$startline);
1.524     raeburn  8961:             push(@lines_to_correct,@linenums);
1.157     albertel 8962: 	}
1.503     raeburn  8963:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8964:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   8965: 	$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 8966: 	$r->print($message);
1.492     albertel 8967: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8968: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8969: 
1.503     raeburn  8970: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8971: 	# a list of question numbers. Therefore:
                   8972: 	#
1.691     raeburn  8973: 
                   8974: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8975:                                                 $respnumlookup,$startline);
1.497     foxr     8976: 
1.157     albertel 8977: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8978: 		  $line_list.'" />');
1.157     albertel 8979: 	foreach my $question (@{$arg}) {
1.503     raeburn  8980: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8981:                                                    $scan_record, $error,
                   8982:                                                    $randomorder,$randompick,
                   8983:                                                    $respnumlookup,$startline);
1.524     raeburn  8984:             push(@lines_to_correct,@linenums);
1.157     albertel 8985: 	}
1.503     raeburn  8986:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8987:     } else {
                   8988: 	$r->print("\n<ul>");
                   8989:     }
                   8990:     $r->print("\n</li></ul>");
1.497     foxr     8991: }
                   8992: 
1.503     raeburn  8993: sub verify_bubbles_checked {
                   8994:     my (@ansnums) = @_;
                   8995:     my $ansnumstr = join('","',@ansnums);
                   8996:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  8997:     &js_escape(\$warning);
1.767     raeburn  8998:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8999: function verify_bubble_radio(form) {
                   9000:     var ansnumArray = new Array ("$ansnumstr");
                   9001:     var need_bubble_count = 0;
                   9002:     for (var i=0; i<ansnumArray.length; i++) {
                   9003:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   9004:             var bubble_picked = 0; 
                   9005:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   9006:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   9007:                     bubble_picked = 1;
                   9008:                 }
                   9009:             }
                   9010:             if (bubble_picked == 0) {
                   9011:                 need_bubble_count ++;
                   9012:             }
                   9013:         }
                   9014:     }
                   9015:     if (need_bubble_count) {
                   9016:         alert("$warning");
                   9017:         return;
                   9018:     }
                   9019:     form.submit(); 
                   9020: }
                   9021: ENDSCRIPT
                   9022:     return $output;
                   9023: }
                   9024: 
1.497     foxr     9025: =pod
                   9026: 
                   9027: =item  questions_to_line_list
1.157     albertel 9028: 
1.497     foxr     9029: Converts a list of questions into a string of comma separated
                   9030: line numbers in the answer sheet used by the questions.  This is
                   9031: used to fill in the scantron_questions form field.
                   9032: 
                   9033:   Arguments:
                   9034:      questions    - Reference to an array of questions.
1.691     raeburn  9035:      randomorder  - True if randomorder in use.
                   9036:      randompick   - True if randompick in use.
                   9037:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9038:                      for current line to question number used for same question
                   9039:                      in "Master Seqence" (as seen by Course Coordinator).
                   9040:      startline    - Reference to hash where key is question number (0 is first)
                   9041:                     and key is number of first bubble line for current student
                   9042:                     or code-based randompick and/or randomorder.
1.693     raeburn  9043: 
1.497     foxr     9044: =cut
                   9045: 
                   9046: 
                   9047: sub questions_to_line_list {
1.691     raeburn  9048:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     9049:     my @lines;
                   9050: 
1.503     raeburn  9051:     foreach my $item (@{$questions}) {
                   9052:         my $question = $item;
                   9053:         my ($first,$count,$last);
                   9054:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   9055:             $question = $1;
                   9056:             my $subquestion = $2;
1.691     raeburn  9057:             my $responsenum = $question-1;
                   9058:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9059:                 $responsenum = $respnumlookup->{$question-1};
                   9060:                 if (ref($startline) eq 'HASH') {
                   9061:                     $first = $startline->{$question-1} + 1;
                   9062:                 }
                   9063:             } else {
                   9064:                 $first = $first_bubble_line{$responsenum} + 1;
                   9065:             }
                   9066:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9067:             my $subcount = 1;
                   9068:             while ($subcount<$subquestion) {
                   9069:                 $first += $subans[$subcount-1];
                   9070:                 $subcount ++;
                   9071:             }
                   9072:             $count = $subans[$subquestion-1];
                   9073:         } else {
1.691     raeburn  9074:             my $responsenum = $question-1;
                   9075:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9076:                 $responsenum = $respnumlookup->{$question-1};
                   9077:                 if (ref($startline) eq 'HASH') {
                   9078:                     $first = $startline->{$question-1} + 1;
                   9079:                 }
                   9080:             } else {
                   9081:                 $first = $first_bubble_line{$responsenum} + 1;
                   9082:             }
                   9083: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9084:         }
1.506     raeburn  9085:         $last = $first+$count-1;
1.503     raeburn  9086:         push(@lines, ($first..$last));
1.497     foxr     9087:     }
                   9088:     return join(',', @lines);
                   9089: }
                   9090: 
                   9091: =pod 
                   9092: 
                   9093: =item prompt_for_corrections
                   9094: 
                   9095: Prompts for a potentially multiline correction to the
                   9096: user's bubbling (factors out common code from scantron_get_correction
                   9097: for multi and missing bubble cases).
                   9098: 
                   9099:  Arguments:
                   9100:    $r           - Apache request object.
                   9101:    $question    - The question number to prompt for.
                   9102:    $scan_config - The scantron file configuration hash.
                   9103:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  9104:    $error       - Type of error
1.691     raeburn  9105:    $randomorder - True if randomorder in use.
                   9106:    $randompick  - True if randompick in use.
                   9107:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   9108:                     for current line to question number used for same question
                   9109:                     in "Master Seqence" (as seen by Course Coordinator).
                   9110:    $startline   - Reference to hash where key is question number (0 is first)
                   9111:                   and value is number of first bubble line for current student
                   9112:                   or code-based randompick and/or randomorder.
                   9113: 
1.497     foxr     9114: 
                   9115:  Implicit inputs:
                   9116:    %bubble_lines_per_response   - Starting line numbers for each question.
                   9117:                                   Numbered from 0 (but question numbers are from
                   9118:                                   1.
                   9119:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  9120:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   9121:                                   type problems render as separate sub-questions, 
1.503     raeburn  9122:                                   in exam mode. This hash contains a 
                   9123:                                   comma-separated list of the lines per 
                   9124:                                   sub-question.
1.510     raeburn  9125:    %responsetype_per_response   - essayresponse, formularesponse,
                   9126:                                   stringresponse, imageresponse, reactionresponse,
                   9127:                                   and organicresponse type problem parts can have
1.503     raeburn  9128:                                   multiple lines per response if the weight
                   9129:                                   assigned exceeds 10.  In this case, only
                   9130:                                   one bubble per line is permitted, but more 
                   9131:                                   than one line might contain bubbles, e.g.
                   9132:                                   bubbling of: line 1 - J, line 2 - J, 
                   9133:                                   line 3 - B would assign 22 points.  
1.497     foxr     9134: 
                   9135: =cut
                   9136: 
                   9137: sub prompt_for_corrections {
1.691     raeburn  9138:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   9139:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  9140:     my ($current_line,$lines);
                   9141:     my @linenums;
                   9142:     my $questionnum = $question;
1.691     raeburn  9143:     my ($first,$responsenum);
1.503     raeburn  9144:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   9145:         $question = $1;
                   9146:         my $subquestion = $2;
1.691     raeburn  9147:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9148:             $responsenum = $respnumlookup->{$question-1};
                   9149:             if (ref($startline) eq 'HASH') {
                   9150:                 $first = $startline->{$question-1};
                   9151:             }
                   9152:         } else {
                   9153:             $responsenum = $question-1;
1.714     raeburn  9154:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  9155:         }
                   9156:         $current_line = $first + 1 ;
                   9157:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  9158:         my $subcount = 1;
                   9159:         while ($subcount<$subquestion) {
                   9160:             $current_line += $subans[$subcount-1];
                   9161:             $subcount ++;
                   9162:         }
                   9163:         $lines = $subans[$subquestion-1];
                   9164:     } else {
1.691     raeburn  9165:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   9166:             $responsenum = $respnumlookup->{$question-1};
                   9167:             if (ref($startline) eq 'HASH') { 
                   9168:                 $first = $startline->{$question-1};
                   9169:             }
                   9170:         } else {
                   9171:             $responsenum = $question-1;
                   9172:             $first = $first_bubble_line{$responsenum};
                   9173:         }
                   9174:         $current_line = $first + 1;
                   9175:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  9176:     }
1.497     foxr     9177:     if ($lines > 1) {
1.503     raeburn  9178:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  9179:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   9180:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   9181:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   9182:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   9183:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   9184:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   9185:             $r->print(
                   9186:                 &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)
                   9187:                .'<br /><br />'
                   9188:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   9189:                .'<br />'
                   9190:                .&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.')
                   9191:                .'<br />'
                   9192:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   9193:                .'<br /><br />'
                   9194:             );
1.503     raeburn  9195:         } else {
                   9196:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   9197:         }
1.497     foxr     9198:     }
                   9199:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  9200:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  9201: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  9202: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  9203:         push(@linenums,$current_line);
1.497     foxr     9204: 	$current_line++;
                   9205:     }
                   9206:     if ($lines > 1) {
                   9207: 	$r->print("<hr /><br />");
                   9208:     }
1.503     raeburn  9209:     return @linenums;
1.157     albertel 9210: }
1.423     albertel 9211: 
                   9212: =pod
                   9213: 
                   9214: =item scantron_bubble_selector
                   9215:   
                   9216:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 9217:    possibly showing the existing the selected bubbles if known
1.423     albertel 9218: 
                   9219:  Arguments:
                   9220:     $r           - Apache request object
1.754     raeburn  9221:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     9222:     $line        - Number of the line being displayed.
1.503     raeburn  9223:     $questionnum - Question number (may include subquestion)
                   9224:     $error       - Type of error.
1.497     foxr     9225:     @selected    - Array of bubbles picked on this line.
1.423     albertel 9226: 
                   9227: =cut
                   9228: 
1.157     albertel 9229: sub scantron_bubble_selector {
1.503     raeburn  9230:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 9231:     my $max=$$scan_config{'Qlength'};
1.274     albertel 9232: 
                   9233:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  9234:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   9235:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   9236:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   9237:             $max=$$scan_config{'BubblesPerRow'};
                   9238:             if (($scmode eq 'number') && ($max > 10)) {
                   9239:                 $max = 10;
                   9240:             } elsif (($scmode eq 'letter') && $max > 26) {
                   9241:                 $max = 26;
                   9242:             }
                   9243:         } else {
                   9244:             $max = 10;
                   9245:         }
                   9246:     }
1.274     albertel 9247: 
1.157     albertel 9248:     my @alphabet=('A'..'Z');
1.503     raeburn  9249:     $r->print(&Apache::loncommon::start_data_table().
                   9250:               &Apache::loncommon::start_data_table_row());
                   9251:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     9252:     for (my $i=0;$i<$max+1;$i++) {
                   9253: 	$r->print("\n".'<td align="center">');
                   9254: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   9255: 	else { $r->print('&nbsp;'); }
                   9256: 	$r->print('</td>');
                   9257:     }
1.503     raeburn  9258:     $r->print(&Apache::loncommon::end_data_table_row().
                   9259:               &Apache::loncommon::start_data_table_row());
1.497     foxr     9260:     for (my $i=0;$i<$max;$i++) {
                   9261: 	$r->print("\n".
                   9262: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   9263: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   9264:     }
1.503     raeburn  9265:     my $nobub_checked = ' ';
                   9266:     if ($error eq 'missingbubble') {
                   9267:         $nobub_checked = ' checked = "checked" ';
                   9268:     }
                   9269:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   9270: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   9271:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   9272:               $line.'" value="'.$questionnum.'" /></td>');
                   9273:     $r->print(&Apache::loncommon::end_data_table_row().
                   9274:               &Apache::loncommon::end_data_table());
1.157     albertel 9275: }
                   9276: 
1.423     albertel 9277: =pod
                   9278: 
                   9279: =item num_matches
                   9280: 
1.424     albertel 9281:    Counts the number of characters that are the same between the two arguments.
                   9282: 
                   9283:  Arguments:
                   9284:    $orig - CODE from the scanline
                   9285:    $code - CODE to match against
                   9286: 
                   9287:  Returns:
                   9288:    $count - integer count of the number of same characters between the
                   9289:             two arguments
                   9290: 
1.423     albertel 9291: =cut
                   9292: 
1.194     albertel 9293: sub num_matches {
                   9294:     my ($orig,$code) = @_;
                   9295:     my @code=split(//,$code);
                   9296:     my @orig=split(//,$orig);
                   9297:     my $same=0;
                   9298:     for (my $i=0;$i<scalar(@code);$i++) {
                   9299: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   9300:     }
                   9301:     return $same;
                   9302: }
                   9303: 
1.423     albertel 9304: =pod
                   9305: 
                   9306: =item scantron_get_closely_matching_CODEs
                   9307: 
1.424     albertel 9308:    Cycles through all CODEs and finds the set that has the greatest
                   9309:    number of same characters as the provided CODE
                   9310: 
                   9311:  Arguments:
                   9312:    $allcodes - hash ref returned by &get_codes()
                   9313:    $CODE     - CODE from the current scanline
                   9314: 
                   9315:  Returns:
                   9316:    2 element list
                   9317:     - first elements is number of how closely matching the best fit is 
                   9318:       (5 means best set has 5 matching characters)
                   9319:     - second element is an arrary ref containing the set of valid CODEs
                   9320:       that best fit the passed in CODE
                   9321: 
1.423     albertel 9322: =cut
                   9323: 
1.194     albertel 9324: sub scantron_get_closely_matching_CODEs {
                   9325:     my ($allcodes,$CODE)=@_;
                   9326:     my @CODEs;
                   9327:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   9328: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   9329:     }
                   9330: 
                   9331:     return ($#CODEs,$CODEs[-1]);
                   9332: }
                   9333: 
1.423     albertel 9334: =pod
                   9335: 
                   9336: =item get_codes
                   9337: 
1.424     albertel 9338:    Builds a hash which has keys of all of the valid CODEs from the selected
                   9339:    set of remembered CODEs.
                   9340: 
                   9341:  Arguments:
                   9342:   $old_name - name of the set of remembered CODEs
                   9343:   $cdom     - domain of the course
                   9344:   $cnum     - internal course name
                   9345: 
                   9346:  Returns:
                   9347:   %allcodes - keys are the valid CODEs, values are all 1
                   9348: 
1.423     albertel 9349: =cut
                   9350: 
1.194     albertel 9351: sub get_codes {
1.280     foxr     9352:     my ($old_name, $cdom, $cnum) = @_;
                   9353:     if (!$old_name) {
                   9354: 	$old_name=$env{'form.scantron_CODElist'};
                   9355:     }
                   9356:     if (!$cdom) {
                   9357: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9358:     }
                   9359:     if (!$cnum) {
                   9360: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   9361:     }
1.278     albertel 9362:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   9363: 				    $cdom,$cnum);
                   9364:     my %allcodes;
                   9365:     if ($result{"type\0$old_name"} eq 'number') {
                   9366: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   9367:     } else {
                   9368: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   9369:     }
1.194     albertel 9370:     return %allcodes;
                   9371: }
                   9372: 
1.423     albertel 9373: =pod
                   9374: 
                   9375: =item scantron_validate_CODE
                   9376: 
1.424     albertel 9377:    Validates all scanlines in the selected file to not have any
                   9378:    invalid or underspecified CODEs and that none of the codes are
                   9379:    duplicated if this was requested.
                   9380: 
1.423     albertel 9381: =cut
                   9382: 
1.157     albertel 9383: sub scantron_validate_CODE {
                   9384:     my ($r,$currentphase) = @_;
1.754     raeburn  9385:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 9386:     if ($scantron_config{'CODElocation'} &&
                   9387: 	$scantron_config{'CODEstart'} &&
                   9388: 	$scantron_config{'CODElength'}) {
1.257     albertel 9389: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 9390: 	    &FIXME_blow_up()
                   9391: 	}
                   9392:     } else {
                   9393: 	return (0,$currentphase+1);
                   9394:     }
                   9395:     
                   9396:     my %usedCODEs;
                   9397: 
1.194     albertel 9398:     my %allcodes=&get_codes();
1.186     albertel 9399: 
1.582     raeburn  9400:     my $nav_error;
1.649     raeburn  9401:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  9402:     if ($nav_error) {
                   9403:         $r->print(&navmap_errormsg());
                   9404:         return(1,$currentphase);
                   9405:     }
1.447     foxr     9406: 
1.186     albertel 9407:     my ($scanlines,$scan_data)=&scantron_getfile();
                   9408:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9409: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 9410: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9411: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   9412: 						 $scan_data);
                   9413: 	my $CODE=$$scan_record{'scantron.CODE'};
                   9414: 	my $error=0;
1.224     albertel 9415: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   9416: 	    &scantron_get_correction($r,$i,$scan_record,
                   9417: 				     \%scantron_config,
                   9418: 				     $line,'incorrectCODE',\%allcodes);
                   9419: 	    return(1,$currentphase);
                   9420: 	}
1.221     albertel 9421: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   9422: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 9423: 	    &scantron_get_correction($r,$i,$scan_record,
                   9424: 				     \%scantron_config,
1.194     albertel 9425: 				     $line,'incorrectCODE',\%allcodes);
                   9426: 	    return(1,$currentphase);
1.186     albertel 9427: 	}
1.214     albertel 9428: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 9429: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 9430: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 9431: 	    &scantron_get_correction($r,$i,$scan_record,
                   9432: 				     \%scantron_config,
1.194     albertel 9433: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   9434: 	    return(1,$currentphase);
1.186     albertel 9435: 	}
1.524     raeburn  9436: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 9437:     }
1.157     albertel 9438:     return (0,$currentphase+1);
                   9439: }
                   9440: 
1.423     albertel 9441: =pod
                   9442: 
                   9443: =item scantron_validate_doublebubble
                   9444: 
1.424     albertel 9445:    Validates all scanlines in the selected file to not have any
                   9446:    bubble lines with multiple bubbles marked.
                   9447: 
1.423     albertel 9448: =cut
                   9449: 
1.157     albertel 9450: sub scantron_validate_doublebubble {
                   9451:     my ($r,$currentphase) = @_;
                   9452:     #get student info
                   9453:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9454:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  9455:     my (undef,undef,$sequence)=
                   9456:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 9457: 
                   9458:     #get scantron line setup
1.754     raeburn  9459:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9460:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  9461: 
                   9462:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9463:     unless (ref($navmap)) {
                   9464:         $r->print(&navmap_errormsg());
                   9465:         return(1,$currentphase);
                   9466:     }
                   9467:     my $map=$navmap->getResourceByUrl($sequence);
                   9468:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9469:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9470:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   9471:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9472: 
1.583     raeburn  9473:     my $nav_error;
1.691     raeburn  9474:     if (ref($map)) {
                   9475:         $randomorder = $map->randomorder();
                   9476:         $randompick = $map->randompick();
1.788     raeburn  9477:         unless ($randomorder || $randompick) {
                   9478:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9479:                 if ($res->randomorder()) {
                   9480:                     $randomorder = 1;
                   9481:                 }
                   9482:                 if ($res->randompick()) {
                   9483:                     $randompick = 1;
                   9484:                 }
                   9485:                 last if ($randomorder || $randompick);
                   9486:             }
                   9487:         }
1.691     raeburn  9488:         if ($randomorder || $randompick) {
                   9489:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9490:             if ($nav_error) {
                   9491:                 $r->print(&navmap_errormsg());
                   9492:                 return(1,$currentphase);
                   9493:             }
                   9494:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9495:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   9496:         }
                   9497:     } else {
                   9498:         $r->print(&navmap_errormsg());
                   9499:         return(1,$currentphase);
                   9500:     }
                   9501: 
1.649     raeburn  9502:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  9503:     if ($nav_error) {
                   9504:         $r->print(&navmap_errormsg());
                   9505:         return(1,$currentphase);
                   9506:     }
1.447     foxr     9507: 
1.157     albertel 9508:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9509: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9510: 	if ($line=~/^[\s\cz]*$/) { next; }
                   9511: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9512: 						 $scan_data,undef,\%idmap,$randomorder,
                   9513:                                                  $randompick,$sequence,\@master_seq,
                   9514:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9515:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 9516: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   9517: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   9518: 				 'doublebubble',
1.691     raeburn  9519: 				 $$scan_record{'scantron.doubleerror'},
                   9520:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 9521:     	return (1,$currentphase);
                   9522:     }
                   9523:     return (0,$currentphase+1);
                   9524: }
                   9525: 
1.423     albertel 9526: 
1.503     raeburn  9527: sub scantron_get_maxbubble {
1.649     raeburn  9528:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 9529:     if (defined($env{'form.scantron_maxbubble'}) &&
                   9530: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     9531: 	&restore_bubble_lines();
1.257     albertel 9532: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 9533:     }
1.330     albertel 9534: 
1.447     foxr     9535:     my (undef, undef, $sequence) =
1.257     albertel 9536: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 9537: 
1.447     foxr     9538:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9539:     unless (ref($navmap)) {
                   9540:         if (ref($nav_error)) {
                   9541:             $$nav_error = 1;
                   9542:         }
1.591     raeburn  9543:         return;
1.582     raeburn  9544:     }
1.191     albertel 9545:     my $map=$navmap->getResourceByUrl($sequence);
                   9546:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  9547:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 9548: 
                   9549:     &Apache::lonxml::clear_problem_counter();
                   9550: 
1.557     raeburn  9551:     my $uname       = $env{'user.name'};
                   9552:     my $udom        = $env{'user.domain'};
1.435     foxr     9553:     my $cid         = $env{'request.course.id'};
                   9554:     my $total_lines = 0;
                   9555:     %bubble_lines_per_response = ();
1.447     foxr     9556:     %first_bubble_line         = ();
1.503     raeburn  9557:     %subdivided_bubble_lines   = ();
                   9558:     %responsetype_per_response = ();
1.691     raeburn  9559:     %masterseq_id_responsenum  = ();
1.554     raeburn  9560: 
1.447     foxr     9561:     my $response_number = 0;
                   9562:     my $bubble_line     = 0;
1.191     albertel 9563:     foreach my $resource (@resources) {
1.691     raeburn  9564:         my $resid = $resource->id(); 
1.672     raeburn  9565:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   9566:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  9567:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   9568: 	    foreach my $part_id (@{$parts}) {
                   9569:                 my $lines;
                   9570: 
                   9571: 	        # TODO - make this a persistent hash not an array.
                   9572: 
                   9573:                 # optionresponse, matchresponse and rankresponse type items 
                   9574:                 # render as separate sub-questions in exam mode.
                   9575:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   9576:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   9577:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   9578:                     my ($numbub,$numshown);
                   9579:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   9580:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   9581:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   9582:                         }
                   9583:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   9584:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   9585:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   9586:                         }
                   9587:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   9588:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   9589:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   9590:                         }
                   9591:                     }
                   9592:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   9593:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   9594:                     }
1.649     raeburn  9595:                     my $bubbles_per_row =
                   9596:                         &bubblesheet_bubbles_per_row($scantron_config);
                   9597:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   9598:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  9599:                         $inner_bubble_lines++;
                   9600:                     }
                   9601:                     for (my $i=0; $i<$numshown; $i++) {
                   9602:                         $subdivided_bubble_lines{$response_number} .= 
                   9603:                             $inner_bubble_lines.',';
                   9604:                     }
                   9605:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   9606:                     $lines = $numshown * $inner_bubble_lines;
                   9607:                 } else {
                   9608:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  9609:                 }
1.542     raeburn  9610: 
                   9611:                 $first_bubble_line{$response_number} = $bubble_line;
                   9612: 	        $bubble_lines_per_response{$response_number} = $lines;
                   9613:                 $responsetype_per_response{$response_number} = 
                   9614:                     $analysis->{$part_id.'.type'};
1.691     raeburn  9615:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  9616: 	        $response_number++;
                   9617: 
                   9618: 	        $bubble_line +=  $lines;
                   9619: 	        $total_lines +=  $lines;
                   9620: 	    }
                   9621:         }
                   9622:     }
1.552     raeburn  9623:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  9624: 
                   9625:     &save_bubble_lines();
                   9626:     $env{'form.scantron_maxbubble'} =
                   9627: 	$total_lines;
                   9628:     return $env{'form.scantron_maxbubble'};
                   9629: }
1.523     raeburn  9630: 
1.649     raeburn  9631: sub bubblesheet_bubbles_per_row {
                   9632:     my ($scantron_config) = @_;
                   9633:     my $bubbles_per_row;
                   9634:     if (ref($scantron_config) eq 'HASH') {
                   9635:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   9636:     }
                   9637:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   9638:         $bubbles_per_row = 10;
                   9639:     }
                   9640:     return $bubbles_per_row;
                   9641: }
                   9642: 
1.157     albertel 9643: sub scantron_validate_missingbubbles {
                   9644:     my ($r,$currentphase) = @_;
                   9645:     #get student info
                   9646:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9647:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  9648:     my (undef,undef,$sequence)=
                   9649:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 9650: 
                   9651:     #get scantron line setup
1.754     raeburn  9652:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 9653:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  9654: 
                   9655:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9656:     unless (ref($navmap)) {
                   9657:         $r->print(&navmap_errormsg());
                   9658:         return(1,$currentphase);
                   9659:     }
                   9660: 
                   9661:     my $map=$navmap->getResourceByUrl($sequence);
                   9662:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9663:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9664:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   9665:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9666: 
1.582     raeburn  9667:     my $nav_error;
1.691     raeburn  9668:     if (ref($map)) {
                   9669:         $randomorder = $map->randomorder();
                   9670:         $randompick = $map->randompick();
1.788     raeburn  9671:         unless ($randomorder || $randompick) {
                   9672:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9673:                 if ($res->randomorder()) {
                   9674:                     $randomorder = 1;
                   9675:                 }
                   9676:                 if ($res->randompick()) {
                   9677:                     $randompick = 1;
                   9678:                 }
                   9679:                 last if ($randomorder || $randompick);
                   9680:             }
                   9681:         }
1.691     raeburn  9682:         if ($randomorder || $randompick) {
                   9683:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9684:             if ($nav_error) {
                   9685:                 $r->print(&navmap_errormsg());
                   9686:                 return(1,$currentphase);
                   9687:             }
                   9688:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9689:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   9690:         }
                   9691:     } else {
                   9692:         $r->print(&navmap_errormsg());
                   9693:         return(1,$currentphase);
                   9694:     }
                   9695: 
                   9696: 
1.649     raeburn  9697:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  9698:     if ($nav_error) {
1.691     raeburn  9699:         $r->print(&navmap_errormsg());
1.693     raeburn  9700:         return(1,$currentphase);
1.582     raeburn  9701:     }
1.691     raeburn  9702: 
1.157     albertel 9703:     if (!$max_bubble) { $max_bubble=2**31; }
                   9704:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9705: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9706: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  9707: 	my $scan_record =
                   9708:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   9709: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   9710:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   9711:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 9712: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   9713: 	my @to_correct;
1.470     foxr     9714: 	
                   9715: 	# Probably here's where the error is...
                   9716: 
1.157     albertel 9717: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  9718:             my $lastbubble;
                   9719:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   9720:                my $question = $1;
                   9721:                my $subquestion = $2;
1.691     raeburn  9722:                my ($first,$responsenum);
                   9723:                if ($randomorder || $randompick) {
                   9724:                    $responsenum = $respnumlookup{$question-1};
                   9725:                    $first = $startline{$question-1};
                   9726:                } else {
                   9727:                    $responsenum = $question-1; 
                   9728:                    $first = $first_bubble_line{$responsenum};
                   9729:                }
                   9730:                if (!defined($first)) { next; }
                   9731:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  9732:                my $subcount = 1;
                   9733:                while ($subcount<$subquestion) {
                   9734:                    $first += $subans[$subcount-1];
                   9735:                    $subcount ++;
                   9736:                }
                   9737:                my $count = $subans[$subquestion-1];
                   9738:                $lastbubble = $first + $count;
                   9739:             } else {
1.691     raeburn  9740:                my ($first,$responsenum);
                   9741:                if ($randomorder || $randompick) {
                   9742:                    $responsenum = $respnumlookup{$missing-1};
                   9743:                    $first = $startline{$missing-1};
                   9744:                } else {
                   9745:                    $responsenum = $missing-1;
                   9746:                    $first = $first_bubble_line{$responsenum};
                   9747:                }
                   9748:                if (!defined($first)) { next; }
                   9749:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  9750:             }
                   9751:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 9752: 	    push(@to_correct,$missing);
                   9753: 	}
                   9754: 	if (@to_correct) {
                   9755: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  9756: 				     $line,'missingbubble',\@to_correct,
                   9757:                                      $randomorder,$randompick,\%respnumlookup,
                   9758:                                      \%startline);
1.157     albertel 9759: 	    return (1,$currentphase);
                   9760: 	}
                   9761: 
                   9762:     }
                   9763:     return (0,$currentphase+1);
                   9764: }
                   9765: 
1.663     raeburn  9766: sub hand_bubble_option {
                   9767:     my (undef, undef, $sequence) =
                   9768:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9769:     return if ($sequence eq '');
                   9770:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9771:     unless (ref($navmap)) {
                   9772:         return;
                   9773:     }
                   9774:     my $needs_hand_bubbles;
                   9775:     my $map=$navmap->getResourceByUrl($sequence);
                   9776:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9777:     foreach my $res (@resources) {
                   9778:         if (ref($res)) {
                   9779:             if ($res->is_problem()) {
                   9780:                 my $partlist = $res->parts();
                   9781:                 foreach my $part (@{ $partlist }) {
                   9782:                     my @types = $res->responseType($part);
                   9783:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   9784:                         $needs_hand_bubbles = 1;
                   9785:                         last;
                   9786:                     }
                   9787:                 }
                   9788:             }
                   9789:         }
                   9790:     }
                   9791:     if ($needs_hand_bubbles) {
1.754     raeburn  9792:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  9793:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9794:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   9795:                &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 />').
                   9796:                '<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  9797:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  9798:     }
                   9799:     return;
                   9800: }
1.423     albertel 9801: 
1.82      albertel 9802: sub scantron_process_students {
1.608     www      9803:     my ($r,$symb) = @_;
1.513     foxr     9804: 
1.257     albertel 9805:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     9806:     if (!$symb) {
                   9807: 	return '';
                   9808:     }
1.324     albertel 9809:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 9810: 
1.754     raeburn  9811:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  9812:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 9813:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 9814:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9815:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 9816:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9817:     unless (ref($navmap)) {
                   9818:         $r->print(&navmap_errormsg());
                   9819:         return '';
1.691     raeburn  9820:     }
1.83      albertel 9821:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9822:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.788     raeburn  9823:         %grader_randomlists_by_symb,%symb_for_examcode);
1.677     raeburn  9824:     if (ref($map)) {
                   9825:         $randomorder = $map->randomorder();
1.689     raeburn  9826:         $randompick = $map->randompick();
1.788     raeburn  9827:         unless ($randomorder || $randompick) {
                   9828:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9829:                 if ($res->randomorder()) {
                   9830:                     $randomorder = 1;
                   9831:                 }
                   9832:                 if ($res->randompick()) {
                   9833:                     $randompick = 1;
                   9834:                 }
                   9835:                 last if ($randomorder || $randompick);
                   9836:             }
                   9837:         }
1.691     raeburn  9838:     } else {
                   9839:         $r->print(&navmap_errormsg());
                   9840:         return '';
1.677     raeburn  9841:     }
1.691     raeburn  9842:     my $nav_error;
1.83      albertel 9843:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9844:     if ($randomorder || $randompick) {
1.788     raeburn  9845:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
1.691     raeburn  9846:         if ($nav_error) {
                   9847:             $r->print(&navmap_errormsg());
                   9848:             return '';
                   9849:         }
                   9850:     }
1.557     raeburn  9851:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  9852:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  9853: 
1.554     raeburn  9854:     my ($uname,$udom);
1.82      albertel 9855:     my $result= <<SCANTRONFORM;
1.81      albertel 9856: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   9857:   <input type="hidden" name="command" value="scantron_configphase" />
                   9858:   $default_form_data
                   9859: SCANTRONFORM
1.82      albertel 9860:     $r->print($result);
                   9861: 
1.770     raeburn  9862:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 9863:     my @delayqueue;
1.542     raeburn  9864:     my (%completedstudents,%scandata);
1.770     raeburn  9865: 
1.520     www      9866:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9867:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9868:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   9869:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9870:     $r->print('<br />');
1.140     albertel 9871:     my $start=&Time::HiRes::time();
1.158     albertel 9872:     my $i=-1;
1.542     raeburn  9873:     my $started;
1.447     foxr     9874: 
1.649     raeburn  9875:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9876:     if ($nav_error) {
                   9877:         $r->print(&navmap_errormsg());
                   9878:         return '';
                   9879:     }
                   9880: 
1.513     foxr     9881:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9882:     # the user and return.
                   9883: 
                   9884:     if ($ssi_error) {
                   9885: 	$r->print("</form>");
                   9886: 	&ssi_print_error($r);
1.520     www      9887:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9888: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9889:     }
1.447     foxr     9890: 
1.755     raeburn  9891:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9892:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  9893:     my %orderedforcode;
1.542     raeburn  9894: 
1.157     albertel 9895:     while ($i<$scanlines->{'count'}) {
                   9896:  	($uname,$udom)=('','');
                   9897:  	$i++;
1.200     albertel 9898:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9899:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9900: 	if ($started) {
1.667     www      9901: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9902: 	}
                   9903: 	$started=1;
1.691     raeburn  9904:         my %respnumlookup = ();
                   9905:         my %startline = ();
                   9906:         my $total;
1.157     albertel 9907:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9908:                                                  $scan_data,undef,\%idmap,$randomorder,
                   9909:                                                  $randompick,$sequence,\@master_seq,
                   9910:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9911:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9912:                                                  \$total);
1.157     albertel 9913:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9914:  					      \%idmap,$i)) {
                   9915:   	    &scantron_add_delay(\@delayqueue,$line,
                   9916:  				'Unable to find a student that matches',1);
                   9917:  	    next;
                   9918:   	}
                   9919:  	if (exists $completedstudents{$uname}) {
                   9920:  	    &scantron_add_delay(\@delayqueue,$line,
                   9921:  				'Student '.$uname.' has multiple sheets',2);
                   9922:  	    next;
                   9923:  	}
1.677     raeburn  9924:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  9925:         if (($checksec ne '') && ($checksec ne $usec)) {
                   9926:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   9927:                 &scantron_add_delay(\@delayqueue,$line,
                   9928:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   9929:                 next;
                   9930:             }
                   9931:         }
1.677     raeburn  9932:         my $user = $uname.':'.$usec;
1.157     albertel 9933:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9934: 
1.677     raeburn  9935:         my $scancode;
                   9936:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9937:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9938:             $scancode = $scan_record->{'scantron.CODE'};
                   9939:         } else {
                   9940:             $scancode = '';
                   9941:         }
                   9942: 
                   9943:         my @mapresources = @resources;
1.689     raeburn  9944:         if ($randomorder || $randompick) {
1.678     raeburn  9945:             @mapresources = 
1.691     raeburn  9946:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9947:                              \%orderedforcode);
1.677     raeburn  9948:         }
1.586     raeburn  9949:         my (%partids_by_symb,$res_error);
1.677     raeburn  9950:         foreach my $resource (@mapresources) {
1.586     raeburn  9951:             my $ressymb;
                   9952:             if (ref($resource)) {
                   9953:                 $ressymb = $resource->symb();
                   9954:             } else {
                   9955:                 $res_error = 1;
                   9956:                 last;
                   9957:             }
1.557     raeburn  9958:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9959:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9960:                 my $currcode;
                   9961:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9962:                     $currcode = $scancode;
                   9963:                 }
1.557     raeburn  9964:                 my ($analysis,$parts) =
1.672     raeburn  9965:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  9966:                                               $uname,$udom,undef,$bubbles_per_row,
                   9967:                                               $currcode);
1.557     raeburn  9968:                 $partids_by_symb{$ressymb} = $parts;
                   9969:             } else {
                   9970:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9971:             }
1.554     raeburn  9972:         }
                   9973: 
1.586     raeburn  9974:         if ($res_error) {
                   9975:             &scantron_add_delay(\@delayqueue,$line,
                   9976:                                 'An error occurred while grading student '.$uname,2);
                   9977:             next;
                   9978:         }
                   9979: 
1.330     albertel 9980: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9981:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9982: 
                   9983: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9984: 	    &scantron_putfile($scanlines,$scan_data);
                   9985: 	}
1.161     albertel 9986: 	
1.542     raeburn  9987:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9988:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  9989:                                    $bubbles_per_row,$randomorder,$randompick,
                   9990:                                    \%respnumlookup,\%startline) 
                   9991:             eq 'ssi_error') {
1.542     raeburn  9992:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9993:             $r->print("</form>");
                   9994:             &ssi_print_error($r);
                   9995:             &Apache::lonnet::remove_lock($lock);
                   9996:             return '';      # Why return ''?  Beats me.
                   9997:         }
1.513     foxr     9998: 
1.692     raeburn  9999:         if (($scancode) && ($randomorder || $randompick)) {
1.788     raeburn  10000:             foreach my $key (keys(%symb_for_examcode)) {
                   10001:                 my $symb_in_map = $symb_for_examcode{$key};
                   10002:                 if ($symb_in_map ne '') {
                   10003:                     my $parmresult =
                   10004:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   10005:                                                                '0_examcode',2,$scancode,
                   10006:                                                                'string_examcode',$uname,
                   10007:                                                                $udom);
                   10008:                 }
                   10009:             }
1.692     raeburn  10010:         }
1.140     albertel 10011: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  10012:         if ($env{'form.verifyrecord'}) {
                   10013:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  10014:             if ($randompick) {
                   10015:                 if ($total) {
                   10016:                     $lastpos = $total*$scantron_config{'Qlength'};
                   10017:                 }
                   10018:             }
                   10019: 
1.542     raeburn  10020:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10021:             chomp($studentdata);
                   10022:             $studentdata =~ s/\r$//;
                   10023:             my $studentrecord = '';
                   10024:             my $counter = -1;
1.677     raeburn  10025:             foreach my $resource (@mapresources) {
1.554     raeburn  10026:                 my $ressymb = $resource->symb();
1.542     raeburn  10027:                 ($counter,my $recording) =
                   10028:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10029:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10030:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   10031:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  10032:                 $studentrecord .= $recording;
                   10033:             }
                   10034:             if ($studentrecord ne $studentdata) {
1.554     raeburn  10035:                 &Apache::lonxml::clear_problem_counter();
                   10036:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  10037:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  10038:                                            $bubbles_per_row,$randomorder,$randompick,
                   10039:                                            \%respnumlookup,\%startline) 
                   10040:                     eq 'ssi_error') {
1.554     raeburn  10041:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   10042:                     $r->print("</form>");
                   10043:                     &ssi_print_error($r);
                   10044:                     &Apache::lonnet::remove_lock($lock);
                   10045:                     delete($completedstudents{$uname});
                   10046:                     return '';
                   10047:                 }
1.542     raeburn  10048:                 $counter = -1;
                   10049:                 $studentrecord = '';
1.677     raeburn  10050:                 foreach my $resource (@mapresources) {
1.554     raeburn  10051:                     my $ressymb = $resource->symb();
1.542     raeburn  10052:                     ($counter,my $recording) =
                   10053:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  10054:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  10055:                                                  \%scantron_config,\%lettdig,$numletts,
                   10056:                                                  $randomorder,$randompick,\%respnumlookup,
                   10057:                                                  \%startline);
1.542     raeburn  10058:                     $studentrecord .= $recording;
                   10059:                 }
                   10060:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   10061:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  10062:                     if ($scancode eq '') {
1.658     bisitz   10063:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  10064:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   10065:                     } else {
1.658     bisitz   10066:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  10067:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   10068:                     }
                   10069:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   10070:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   10071:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   10072:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   10073:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10074:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   10075:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  10076:                               &Apache::loncommon::end_data_table_row().
                   10077:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   10078:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   10079:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  10080:                               &Apache::loncommon::end_data_table_row().
                   10081:                               &Apache::loncommon::end_data_table().'</p>');
                   10082:                 } else {
                   10083:                     $r->print('<br /><span class="LC_warning">'.
                   10084:                              &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 />'.
                   10085:                              &mt("As a consequence, this user's submission history records two tries.").
                   10086:                                  '</span><br />');
                   10087:                 }
                   10088:             }
                   10089:         }
1.543     raeburn  10090:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 10091:     } continue {
1.330     albertel 10092: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  10093: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 10094:     }
1.140     albertel 10095:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      10096:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 10097: #    my $lasttime = &Time::HiRes::time()-$start;
                   10098: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 10099: 
1.200     albertel 10100:     $r->print("</form>");
1.157     albertel 10101:     return '';
1.75      albertel 10102: }
1.157     albertel 10103: 
1.557     raeburn  10104: sub graders_resources_pass {
1.649     raeburn  10105:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   10106:         $bubbles_per_row) = @_;
1.557     raeburn  10107:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   10108:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   10109:         foreach my $resource (@{$resources}) {
                   10110:             my $ressymb = $resource->symb();
                   10111:             my ($analysis,$parts) =
                   10112:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  10113:                                           $env{'user.name'},$env{'user.domain'},
                   10114:                                           1,$bubbles_per_row);
1.557     raeburn  10115:             $grader_partids_by_symb->{$ressymb} = $parts;
                   10116:             if (ref($analysis) eq 'HASH') {
                   10117:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   10118:                     $grader_randomlists_by_symb->{$ressymb} =
                   10119:                         $analysis->{'parts_withrandomlist'};
                   10120:                 }
                   10121:             }
                   10122:         }
                   10123:     }
                   10124:     return;
                   10125: }
                   10126: 
1.678     raeburn  10127: =pod
                   10128: 
                   10129: =item users_order
                   10130: 
                   10131:   Returns array of resources in current map, ordered based on either CODE,
                   10132:   if this is a CODEd exam, or based on student's identity if this is a 
                   10133:   "NAMEd" exam.
                   10134: 
1.691     raeburn  10135:   Should be used when randomorder and/or randompick applied when the 
                   10136:   corresponding exam was printed, prior to students completing bubblesheets 
                   10137:   for the version of the exam the student received.
1.678     raeburn  10138: 
                   10139: =cut
                   10140: 
                   10141: sub users_order  {
1.691     raeburn  10142:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  10143:     my @mapresources;
1.691     raeburn  10144:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  10145:         return @mapresources;
1.691     raeburn  10146:     }
                   10147:     if ($scancode) {
                   10148:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   10149:             @mapresources = @{$orderedforcode->{$scancode}};
                   10150:         } else {
                   10151:             $env{'form.CODE'} = $scancode;
                   10152:             my $actual_seq =
                   10153:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10154:                                                                $master_seq,
                   10155:                                                                $user,$scancode,1);
                   10156:             if (ref($actual_seq) eq 'ARRAY') {
                   10157:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10158:                 if (ref($orderedforcode) eq 'HASH') {
                   10159:                     if (@mapresources > 0) { 
                   10160:                         $orderedforcode->{$scancode} = \@mapresources;
                   10161:                     }
                   10162:                 }
                   10163:             }
                   10164:             delete($env{'form.CODE'});
1.678     raeburn  10165:         }
                   10166:     } else {
                   10167:         my $actual_seq =
                   10168:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   10169:                                                            $master_seq,
1.688     raeburn  10170:                                                            $user,undef,1);
1.678     raeburn  10171:         if (ref($actual_seq) eq 'ARRAY') {
                   10172:             @mapresources = 
                   10173:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   10174:         }
1.691     raeburn  10175:     }
                   10176:     return @mapresources;
1.678     raeburn  10177: }
                   10178: 
1.542     raeburn  10179: sub grade_student_bubbles {
1.691     raeburn  10180:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   10181:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   10182:     my $uselookup = 0;
                   10183:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   10184:         (ref($startline) eq 'HASH')) {
                   10185:         $uselookup = 1;
                   10186:     }
                   10187: 
1.554     raeburn  10188:     if (ref($resources) eq 'ARRAY') {
                   10189:         my $count = 0;
                   10190:         foreach my $resource (@{$resources}) {
                   10191:             my $ressymb = $resource->symb();
                   10192:             my %form = ('submitted'      => 'scantron',
                   10193:                         'grade_target'   => 'grade',
                   10194:                         'grade_username' => $uname,
                   10195:                         'grade_domain'   => $udom,
                   10196:                         'grade_courseid' => $env{'request.course.id'},
                   10197:                         'grade_symb'     => $ressymb,
                   10198:                         'CODE'           => $scancode
                   10199:                        );
1.649     raeburn  10200:             if ($bubbles_per_row ne '') {
                   10201:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   10202:             }
1.663     raeburn  10203:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   10204:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   10205:             }
1.554     raeburn  10206:             if (ref($parts) eq 'HASH') {
                   10207:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   10208:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  10209:                         if ($uselookup) {
                   10210:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   10211:                         } else {
                   10212:                             $form{'scantron_questnum_start.'.$part} =
                   10213:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   10214:                         }
1.554     raeburn  10215:                         $count++;
                   10216:                     }
                   10217:                 }
                   10218:             }
                   10219:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   10220:             return 'ssi_error' if ($ssi_error);
                   10221:             last if (&Apache::loncommon::connection_aborted($r));
                   10222:         }
1.542     raeburn  10223:     }
                   10224:     return;
                   10225: }
                   10226: 
1.157     albertel 10227: sub scantron_upload_scantron_data {
1.767     raeburn  10228:     my ($r,$symb) = @_;
1.565     raeburn  10229:     my $dom = $env{'request.role.domain'};
1.754     raeburn  10230:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  10231:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   10232:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 10233:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 10234: 							  'domainid',
1.565     raeburn  10235: 							  'coursename',$dom);
                   10236:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   10237:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      10238:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  10239:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  10240:     &js_escape(\$nofile_alert);
1.579     raeburn  10241:     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  10242:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 10243:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 10244:     function checkUpload(formname) {
                   10245: 	if (formname.upfile.value == "") {
1.579     raeburn  10246: 	    alert("'.$nofile_alert.'");
1.157     albertel 10247: 	    return false;
                   10248: 	}
1.565     raeburn  10249:         if (formname.courseid.value == "") {
1.579     raeburn  10250:             alert("'.$nocourseid_alert.'");
1.565     raeburn  10251:             return false;
                   10252:         }
1.157     albertel 10253: 	formname.submit();
                   10254:     }
1.565     raeburn  10255: 
                   10256:     function ToSyllabus() {
                   10257:         var cdom = '."'$dom'".';
                   10258:         var cnum = document.rules.courseid.value;
                   10259:         if (cdom == "" || cdom == null) {
                   10260:             return;
                   10261:         }
                   10262:         if (cnum == "" || cnum == null) {
                   10263:            return;
                   10264:         }
                   10265:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   10266:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   10267:         return;
                   10268:     }
                   10269: 
1.754     raeburn  10270:     '.$formatjs.'
1.597     wenzelju 10271: '));
                   10272:     $r->print('
1.648     bisitz   10273: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  10274: 
1.492     albertel 10275: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  10276: '.$default_form_data.
                   10277:   &Apache::lonhtmlcommon::start_pick_box().
                   10278:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   10279:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   10280:   &Apache::lonhtmlcommon::row_closure().
                   10281:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   10282:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   10283:   &Apache::lonhtmlcommon::row_closure().
                   10284:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   10285:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  10286:   &Apache::lonhtmlcommon::row_closure());
                   10287:     if ($formatoptions) {
                   10288:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   10289:                   &Apache::lonhtmlcommon::row_closure());
                   10290:     }
                   10291:     $r->print(
1.565     raeburn  10292:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   10293:   '<input type="file" name="upfile" size="50" />'.
                   10294:   &Apache::lonhtmlcommon::row_closure(1).
                   10295:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   10296: 
1.492     albertel 10297: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   10298: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 10299: </form>
1.492     albertel 10300: ');
1.157     albertel 10301:     return '';
                   10302: }
                   10303: 
1.754     raeburn  10304: sub scantron_upload_dataformat {
                   10305:     my ($dom) = @_;
                   10306:     my ($formatoptions,$formattitle,$formatjs);
                   10307:     $formatjs = <<'END';
                   10308: function toggleScantab(form) {
                   10309:    return;
                   10310: }
                   10311: END
                   10312:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   10313:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10314:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10315:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   10316:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   10317:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  10318:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   10319:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   10320:                             my ($onclick,$formatextra,$singleline);
                   10321:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   10322:                             my $count = 0;
                   10323:                             foreach my $line (@lines) {
1.790     raeburn  10324:                                 next if (($line =~ /^\#/) || ($line eq ''));
1.756     raeburn  10325:                                 $singleline = $line;
                   10326:                                 $count ++;
                   10327:                             }
                   10328:                             if ($count > 1) {
                   10329:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  10330:                                                '<span class="LC_nobreak">'.
1.776     raeburn  10331:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  10332:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  10333:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   10334:                                 $formatjs = <<"END";
1.754     raeburn  10335: function toggleScantab(form) {
                   10336:     var divid = 'bubbletype';
                   10337:     if (document.getElementById(divid)) {
                   10338:         var radioname = 'fileformat';
                   10339:         var num = form.elements[radioname].length;
                   10340:         if (num) {
                   10341:             for (var i=0; i<num; i++) {
                   10342:                 if (form.elements[radioname][i].checked) {
                   10343:                     var chosen = form.elements[radioname][i].value;
                   10344:                     if (chosen == 'dat') {
                   10345:                         document.getElementById(divid).style.display = 'none';
                   10346:                     } else if (chosen == 'csv') {
1.757     raeburn  10347:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  10348:                     }
                   10349:                 }
                   10350:             }
                   10351:         }
                   10352:     }
                   10353:     return;
                   10354: }
                   10355: 
                   10356: END
1.756     raeburn  10357:                             } elsif ($count == 1) {
                   10358:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   10359:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   10360:                             }
                   10361:                             $formattitle = &mt('File format');
                   10362:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   10363:                                              &mt('Plain Text (no delimiters)').
                   10364:                                              '</label>'.('&nbsp;'x2).
                   10365:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   10366:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  10367:                         }
                   10368:                     }
                   10369:                 }
                   10370:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  10371:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10372:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  10373:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  10374:                         $formatoptions = &scantron_scantab();
                   10375:                     }
1.754     raeburn  10376:                 }
                   10377:             }
                   10378:         }
                   10379:     }
                   10380:     return ($formatoptions,$formattitle,$formatjs);
                   10381: }
1.423     albertel 10382: 
1.157     albertel 10383: sub scantron_upload_scantron_data_save {
1.767     raeburn  10384:     my ($r,$symb) = @_;
1.182     albertel 10385:     my $doanotherupload=
                   10386: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   10387: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 10388: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 10389: 	'</form>'."\n";
1.257     albertel 10390:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 10391: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  10392: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   10393:         !&Apache::lonnet::allowed('usc',
                   10394:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      10395: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      10396: 	unless ($symb) {
1.182     albertel 10397: 	    $r->print($doanotherupload);
                   10398: 	}
1.162     albertel 10399: 	return '';
                   10400:     }
1.257     albertel 10401:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  10402:     my $uploadedfile;
1.710     bisitz   10403:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 10404:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10405:         $r->print(
                   10406:             &Apache::lonhtmlcommon::confirm_success(
                   10407:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10408:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 10409:     } else {
1.754     raeburn  10410:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   10411:         my $parser;
                   10412:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   10413:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   10414:                 my $is_csv;
                   10415:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   10416:                 if (@possibles > 1) {
                   10417:                     if ($env{'form.fileformat'} eq 'csv') {
                   10418:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10419:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10420:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10421:                                     $is_csv = 1;
                   10422:                                 }
1.754     raeburn  10423:                             }
                   10424:                         }
                   10425:                     }
                   10426:                 } elsif (@possibles == 1) {
                   10427:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  10428:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   10429:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   10430:                                 $is_csv = 1;
                   10431:                             }
1.754     raeburn  10432:                         }
                   10433:                     }
                   10434:                 }
                   10435:                 if ($is_csv) {
                   10436:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   10437:                 }
                   10438:             }
                   10439:         }
                   10440:         my $result =
                   10441:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  10442:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   10443:         if ($result =~ m{^/uploaded/}) {
                   10444:             $r->print(
                   10445:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   10446:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   10447:                         (length($env{'form.upfile'})-1),
                   10448:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  10449:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  10450:             if ($uploadedfile =~ /^scantron_orig_/) {
                   10451:                 my $logname = $uploadedfile;
                   10452:                 $logname =~ s/^scantron_orig_//;
                   10453:                 if ($logname ne '') {
                   10454:                     my $now = time;
                   10455:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   10456:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   10457:                 }
                   10458:             }
1.567     raeburn  10459:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  10460:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   10461:         } else {
                   10462:             $r->print(
                   10463:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   10464:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   10465:                           $result,
1.568     raeburn  10466: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 10467: 	}
                   10468:     }
1.174     albertel 10469:     if ($symb) {
1.612     www      10470: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 10471:     } else {
1.182     albertel 10472: 	$r->print($doanotherupload);
1.174     albertel 10473:     }
1.157     albertel 10474:     return '';
                   10475: }
                   10476: 
1.567     raeburn  10477: sub validate_uploaded_scantron_file {
1.770     raeburn  10478:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   10479: 
1.567     raeburn  10480:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   10481:     my @lines;
                   10482:     if ($scanlines ne '-1') {
                   10483:         @lines=split("\n",$scanlines,-1);
                   10484:     }
1.770     raeburn  10485:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   10486:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   10487:     if ($context eq 'download') {
                   10488:         $priv = 'mgr';
                   10489:     } else {
                   10490:         $priv = 'usc';
                   10491:     }
                   10492:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   10493:             (($env{'request.course.id'}) &&
                   10494:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   10495:         if ($env{'request.course.sec'} ne '') {
                   10496:             unless (&Apache::lonnet::allowed($priv,
                   10497:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   10498:                 unless ($context eq 'download') {
                   10499:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   10500:                 }
                   10501:                 return $output;
                   10502:             }
                   10503:             ($checksec,@possibles)=&gradable_sections();
                   10504:         }
                   10505:     }
1.567     raeburn  10506:     if (@lines) {
                   10507:         my (%counts,$max_match_format);
1.710     bisitz   10508:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  10509:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   10510:         my %idmap = &username_to_idmap($classlist);
                   10511:         foreach my $key (keys(%idmap)) {
                   10512:             my $lckey = lc($key);
                   10513:             $idmap{$lckey} = $idmap{$key};
                   10514:         }
                   10515:         my %unique_formats;
1.754     raeburn  10516:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  10517:         foreach my $line (@formatlines) {
1.790     raeburn  10518:             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  10519:             my @config = split(/:/,$line);
                   10520:             my $idstart = $config[5];
                   10521:             my $idlength = $config[6];
                   10522:             if (($idstart ne '') && ($idlength > 0)) {
                   10523:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   10524:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   10525:                 } else {
                   10526:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   10527:                 }
                   10528:             }
                   10529:         }
                   10530:         foreach my $key (keys(%unique_formats)) {
                   10531:             my ($idstart,$idlength) = split(':',$key);
                   10532:             %{$counts{$key}} = (
                   10533:                                'found'   => 0,
                   10534:                                'total'   => 0,
1.770     raeburn  10535:                                'totalanysec' => 0,
                   10536:                                'othersec' => 0,
1.567     raeburn  10537:                               );
                   10538:             foreach my $line (@lines) {
                   10539:                 next if ($line =~ /^#/);
                   10540:                 next if ($line =~ /^[\s\cz]*$/);
                   10541:                 my $id = substr($line,$idstart-1,$idlength);
                   10542:                 $id = lc($id);
                   10543:                 if (exists($idmap{$id})) {
1.770     raeburn  10544:                     if ($checksec ne '') {
                   10545:                         $counts{$key}{'totalanysec'} ++;
                   10546:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   10547:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   10548:                             if ($stusec ne $checksec) {
                   10549:                                 if (@possibles) {
                   10550:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   10551:                                         $counts{$key}{'othersec'} ++;
                   10552:                                         next;
                   10553:                                     }
                   10554:                                 } else {
                   10555:                                     $counts{$key}{'othersec'} ++;
                   10556:                                     next;
                   10557:                                 }
                   10558:                             }
                   10559:                         }
                   10560:                     }
1.567     raeburn  10561:                     $counts{$key}{'found'} ++;
                   10562:                 }
                   10563:                 $counts{$key}{'total'} ++;
                   10564:             }
                   10565:             if ($counts{$key}{'total'}) {
                   10566:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   10567:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   10568:                     $max_match_pct = $percent_match;
                   10569:                     $max_match_format = $key;
1.710     bisitz   10570:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  10571:                     $max_match_count = $counts{$key}{'total'};
                   10572:                 }
                   10573:             }
                   10574:         }
1.770     raeburn  10575:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  10576:             my $format_descs;
                   10577:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   10578:             for (my $i=0; $i<$numwithformat; $i++) {
                   10579:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   10580:                 if ($i<$numwithformat-2) {
                   10581:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   10582:                 } elsif ($i==$numwithformat-2) {
                   10583:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   10584:                 } elsif ($i==$numwithformat-1) {
                   10585:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   10586:                 }
                   10587:             }
                   10588:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   10589:             $output .= '<br />';
                   10590:             if ($found_match_count == $max_match_count) {
                   10591:                 # 100% matching entries
                   10592:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   10593:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   10594:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   10595:                 &mt('Comparison of student IDs in the uploaded file with'.
                   10596:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   10597:                     ' in the file (for the format defined for [_3]).',
                   10598:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   10599:             } else {
                   10600:                 # Not all entries matching? -> Show warning and additional info
                   10601:                 $output .=
                   10602:                     &Apache::lonhtmlcommon::confirm_success(
                   10603:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   10604:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   10605:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   10606:                     &mt('Comparison of student IDs in the uploaded file with'.
                   10607:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   10608:                         ' in the file (for the format defined for [_3]).',
                   10609:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   10610:                     '<p class="LC_info">'.
                   10611:                     &mt('A low percentage of matches results from one of the following:').
                   10612:                     '</p><ul>'.
                   10613:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   10614:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   10615:                                '<i>'.$cdom.'</i>').'</li>'.
                   10616:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   10617:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   10618:                     '</ul>';
                   10619:             }
1.770     raeburn  10620:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   10621:                 if ($counts{$max_match_format}{'othersec'}) {
                   10622:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   10623:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   10624:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   10625:                     &js_escape(\$confirmdel);
                   10626:                     $output .= '<p class="LC_warning">'.
                   10627:                                &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',
                   10628:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   10629:                                '<br />'.
                   10630:                                &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>').
                   10631:                                '</p><p>'.
                   10632:                                &mt('If you prefer to delete the file now, use: [_1]').
                   10633:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   10634:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   10635:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   10636:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   10637:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   10638:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   10639:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   10640:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   10641:                                '</form></p>';
                   10642:                 }
                   10643:             }
1.567     raeburn  10644:         }
1.770     raeburn  10645:         if (($context eq 'download') && ($checksec ne '')) {
                   10646:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   10647:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   10648:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   10649:             }
                   10650:         } 
                   10651:     } elsif ($context ne 'download') {
1.710     bisitz   10652:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  10653:     }
                   10654:     return $output;
                   10655: }
                   10656: 
1.770     raeburn  10657: sub gradable_sections {
                   10658:     my $checksec = $env{'request.course.sec'};
                   10659:     my @oksecs;
                   10660:     if ($checksec) {
                   10661:         my %availablesecs = &sections_grade_privs();
                   10662:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   10663:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   10664:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   10665:                     push(@oksecs,$sec);
                   10666:                 }
                   10667:             }
                   10668:             if (grep(/^all$/,@oksecs)) {
                   10669:                 undef($checksec);
                   10670:             }
                   10671:         }
                   10672:     }
                   10673:     return($checksec,@oksecs);
                   10674: }
                   10675: 
                   10676: sub sections_grade_privs {
                   10677:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10678:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10679:     my %availablesecs = (
                   10680:                           mgr => [],
                   10681:                           vgr => [],
                   10682:                           usc => [],
                   10683:                         );
                   10684:     my $ccrole = 'cc';
                   10685:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   10686:         $ccrole = 'co';
                   10687:     }
                   10688:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   10689:                                                      'userroles',['active'],
                   10690:                                                      [$ccrole,'in','cr'],$cdom,1);
                   10691:     my $crsid = $cnum.':'.$cdom;
                   10692:     foreach my $item (keys(%crsroleshash)) {
                   10693:         next unless ($item =~ /^$crsid\:/);
                   10694:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   10695:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   10696:         if ($sec ne '') {
                   10697:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   10698:         }
                   10699:         if (($role eq $ccrole) || ($role eq 'in')) {
                   10700:             foreach my $priv ('mgr','vgr','usc') { 
                   10701:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   10702:                     if ($sec eq '') {
                   10703:                         $availablesecs{$priv} = ['all'];
                   10704:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   10705:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   10706:                             push(@{$availablesecs{$priv}},$sec);
                   10707:                         }
                   10708:                     }
                   10709:                 }
                   10710:             }
                   10711:         } elsif ($role =~ m{^cr/}) {
                   10712:             foreach my $priv ('mgr','vgr','usc') {
                   10713:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   10714:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   10715:                         if ($sec eq '') {
                   10716:                             $availablesecs{$priv} = ['all'];
                   10717:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   10718:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   10719:                                 push(@{$availablesecs{$priv}},$sec);
                   10720:                             }
                   10721:                         }
                   10722:                     }
                   10723:                 }
                   10724:             }
                   10725:         }
                   10726:     }
                   10727:     return %availablesecs;
                   10728: }
                   10729: 
                   10730: sub scantron_upload_delete {
                   10731:     my ($r,$symb) = @_;
                   10732:     my $filename = $env{'form.uploadedfile'};
                   10733:     if ($filename =~ /^scantron_orig_/) {
                   10734:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   10735:             &Apache::lonnet::allowed('usc',
                   10736:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   10737:             &Apache::lonnet::allowed('usc',
                   10738:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   10739:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   10740:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   10741:             if ($retrieval eq '-1') {
                   10742:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10743:                           &mt('File requested for deletion not found.'));
                   10744:             } else {
                   10745:                 $filename =~ s/^scantron_orig_//;
                   10746:                 if ($filename ne '') {
                   10747:                     my ($is_valid,$numleft);
                   10748:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   10749:                     if (keys(%info)) {
                   10750:                         if (ref($info{$filename}) eq 'HASH') {
                   10751:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   10752:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   10753:                                     $is_valid = 1;
                   10754:                                     delete($info{$filename}{$timestamp}); 
                   10755:                                 }
                   10756:                             }
                   10757:                             $numleft = scalar(keys(%{$info{$filename}}));
                   10758:                         }
                   10759:                     }
                   10760:                     if ($is_valid) {
                   10761:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   10762:                         if ($result eq 'ok') {
                   10763:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   10764:                             if ($numleft) {
                   10765:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   10766:                             } else {
                   10767:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   10768:                             }
                   10769:                         } else {
                   10770:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10771:                                       &mt('Result was [_1]',$result));
                   10772:                         }
                   10773:                     } else {
                   10774:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10775:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   10776:                     }
                   10777:                 } else {
                   10778:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10779:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   10780:                 }
                   10781:             }
                   10782:         } else {
                   10783:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   10784:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   10785:         }
                   10786:     } else {
                   10787:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10788:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   10789:     }
                   10790:     return;
                   10791: }
                   10792: 
1.202     albertel 10793: sub valid_file {
                   10794:     my ($requested_file)=@_;
                   10795:     foreach my $filename (sort(&scantron_filenames())) {
                   10796: 	if ($requested_file eq $filename) { return 1; }
                   10797:     }
                   10798:     return 0;
                   10799: }
                   10800: 
                   10801: sub scantron_download_scantron_data {
1.767     raeburn  10802:     my ($r,$symb) = @_;
1.608     www      10803:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 10804:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10805:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10806:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 10807:     if (! &valid_file($file)) {
1.492     albertel 10808: 	$r->print('
1.202     albertel 10809: 	<p>
1.686     bisitz   10810: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 10811:         </p>
1.492     albertel 10812: ');
1.202     albertel 10813: 	return;
                   10814:     }
1.770     raeburn  10815:     my (%uploader,$is_owner,%counts,$percent);
                   10816:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   10817:     if (ref($uploader{$file}) eq 'HASH') {
                   10818:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   10819:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   10820:                 $is_owner = 1;
                   10821:                 last;
                   10822:             }
                   10823:         }
                   10824:     }
                   10825:     unless ($is_owner) {
                   10826:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   10827:         if ($counts{'totalanysec'}) {
                   10828:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   10829:             if ($percent_othersec >= 10) {
                   10830:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   10831:                 $r->print('<p class="LC_warning">'.
                   10832:                           &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).
                   10833:                           '</p>');
                   10834:                 return;
                   10835:             }
                   10836:         }
                   10837:     }
1.202     albertel 10838:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   10839:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   10840:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   10841:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   10842:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   10843:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 10844:     $r->print('
1.202     albertel 10845:     <p>
1.723     raeburn  10846: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 10847: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 10848:     </p>
                   10849:     <p>
1.492     albertel 10850: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   10851: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 10852:     </p>
                   10853:     <p>
1.492     albertel 10854: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   10855: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 10856:     </p>
1.492     albertel 10857: ');
1.202     albertel 10858:     return '';
                   10859: }
1.157     albertel 10860: 
1.523     raeburn  10861: sub checkscantron_results {
1.608     www      10862:     my ($r,$symb) = @_;
1.523     raeburn  10863:     if (!$symb) {return '';}
                   10864:     my $cid = $env{'request.course.id'};
1.755     raeburn  10865:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  10866:     my $numletts = scalar(keys(%lettdig));
                   10867:     my $cnum = $env{'course.'.$cid.'.num'};
                   10868:     my $cdom = $env{'course.'.$cid.'.domain'};
                   10869:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10870:     my %record;
                   10871:     my %scantron_config =
1.754     raeburn  10872:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  10873:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  10874:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  10875:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10876:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   10877:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10878:     unless (ref($navmap)) {
                   10879:         $r->print(&navmap_errormsg());
                   10880:         return '';
                   10881:     }
1.523     raeburn  10882:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10883:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10884:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  10885:     if (ref($map)) { 
                   10886:         $randomorder=$map->randomorder();
1.689     raeburn  10887:         $randompick=$map->randompick();
1.788     raeburn  10888:         unless ($randomorder || $randompick) {
                   10889:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10890:                 if ($res->randomorder()) {
                   10891:                     $randomorder = 1;
                   10892:                 }
                   10893:                 if ($res->randompick()) {
                   10894:                     $randompick = 1;
                   10895:                 }
                   10896:                 last if ($randomorder || $randompick);
                   10897:             }
                   10898:         }
1.677     raeburn  10899:     }
1.557     raeburn  10900:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10901:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10902:     if ($nav_error) {
                   10903:         $r->print(&navmap_errormsg());
                   10904:         return '';
1.678     raeburn  10905:     }
1.673     raeburn  10906:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10907:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  10908:     my ($uname,$udom);
1.523     raeburn  10909:     my (%scandata,%lastname,%bylast);
                   10910:     $r->print('
                   10911: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   10912: 
                   10913:     my @delayqueue;
                   10914:     my %completedstudents;
                   10915: 
1.691     raeburn  10916:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10917:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  10918:     my ($username,$domain,$started);
1.649     raeburn  10919:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10920:     if ($nav_error) {
                   10921:         $r->print(&navmap_errormsg());
                   10922:         return '';
                   10923:     }
1.523     raeburn  10924: 
1.667     www      10925:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  10926:     my $start=&Time::HiRes::time();
                   10927:     my $i=-1;
                   10928: 
                   10929:     while ($i<$scanlines->{'count'}) {
                   10930:         ($username,$domain,$uname)=('','','');
                   10931:         $i++;
                   10932:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   10933:         if ($line=~/^[\s\cz]*$/) { next; }
                   10934:         if ($started) {
1.667     www      10935:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  10936:         }
                   10937:         $started=1;
                   10938:         my $scan_record=
                   10939:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   10940:                                                      $scan_data);
1.693     raeburn  10941:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10942:                                               \%idmap,$i)) {
1.523     raeburn  10943:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10944:                                 'Unable to find a student that matches',1);
                   10945:             next;
                   10946:         }
                   10947:         if (exists $completedstudents{$uname}) {
                   10948:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10949:                                 'Student '.$uname.' has multiple sheets',2);
                   10950:             next;
                   10951:         }
                   10952:         my $pid = $scan_record->{'scantron.ID'};
                   10953:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   10954:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  10955:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   10956:         my $user = $uname.':'.$usec;
1.523     raeburn  10957:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  10958: 
1.678     raeburn  10959:         my $scancode;
1.677     raeburn  10960:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10961:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10962:             $scancode = $scan_record->{'scantron.CODE'};
                   10963:         } else {
                   10964:             $scancode = '';
                   10965:         }
                   10966: 
                   10967:         my @mapresources = @resources;
1.691     raeburn  10968:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   10969:         my %respnumlookup=();
                   10970:         my %startline=();
1.689     raeburn  10971:         if ($randomorder || $randompick) {
1.678     raeburn  10972:             @mapresources =
1.691     raeburn  10973:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10974:                              \%orderedforcode);
                   10975:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   10976:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   10977:                                              \%grader_partids_by_symb,\%orderedforcode,
                   10978:                                              \%respnumlookup,\%startline);
                   10979:             if ($randompick && $total) {
                   10980:                 $lastpos = $total*$scantron_config{'Qlength'};
                   10981:             }
1.677     raeburn  10982:         }
1.691     raeburn  10983:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10984:         chomp($scandata{$pid});
                   10985:         $scandata{$pid} =~ s/\r$//;
                   10986: 
1.523     raeburn  10987:         my $counter = -1;
1.677     raeburn  10988:         foreach my $resource (@mapresources) {
1.557     raeburn  10989:             my $parts;
1.554     raeburn  10990:             my $ressymb = $resource->symb();
1.557     raeburn  10991:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10992:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10993:                 my $currcode;
                   10994:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10995:                     $currcode = $scancode;
                   10996:                 }
1.557     raeburn  10997:                 (my $analysis,$parts) =
1.672     raeburn  10998:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   10999:                                               $username,$domain,undef,
1.741     raeburn  11000:                                               $bubbles_per_row,$currcode);
1.557     raeburn  11001:             } else {
                   11002:                 $parts = $grader_partids_by_symb{$ressymb};
                   11003:             }
1.542     raeburn  11004:             ($counter,my $recording) =
                   11005:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  11006:                                          $scandata{$pid},$parts,
1.691     raeburn  11007:                                          \%scantron_config,\%lettdig,$numletts,
                   11008:                                          $randomorder,$randompick,
                   11009:                                          \%respnumlookup,\%startline);
1.542     raeburn  11010:             $record{$pid} .= $recording;
1.523     raeburn  11011:         }
                   11012:     }
                   11013:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   11014:     $r->print('<br />');
                   11015:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   11016:     $passed = 0;
                   11017:     $failed = 0;
                   11018:     $numstudents = 0;
                   11019:     foreach my $last (sort(keys(%bylast))) {
                   11020:         if (ref($bylast{$last}) eq 'ARRAY') {
                   11021:             foreach my $pid (sort(@{$bylast{$last}})) {
                   11022:                 my $showscandata = $scandata{$pid};
                   11023:                 my $showrecord = $record{$pid};
                   11024:                 $showscandata =~ s/\s/&nbsp;/g;
                   11025:                 $showrecord =~ s/\s/&nbsp;/g;
                   11026:                 if ($scandata{$pid} eq $record{$pid}) {
                   11027:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   11028:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      11029: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  11030: '</tr>'."\n".
                   11031: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11032: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  11033:                     $passed ++;
                   11034:                 } else {
                   11035:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      11036:                     $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  11037: '</tr>'."\n".
                   11038: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   11039: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  11040: '</tr>'."\n";
                   11041:                     $failed ++;
                   11042:                 }
                   11043:                 $numstudents ++;
                   11044:             }
                   11045:         }
                   11046:     }
1.648     bisitz   11047:     $r->print(
                   11048:         '<p>'
                   11049:        .&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).',
                   11050:             '<b>',
                   11051:             $numstudents,
                   11052:             '</b>',
                   11053:             $env{'form.scantron_maxbubble'})
                   11054:        .'</p>'
                   11055:     );
1.682     raeburn  11056:     $r->print('<p>'
1.683     raeburn  11057:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  11058:              .'<br />'
                   11059:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   11060:              .'</p>'
                   11061:     );
1.523     raeburn  11062:     if ($passed) {
1.572     www      11063:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11064:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11065:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11066:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11067:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11068:                  $okstudents."\n".
                   11069:                  &Apache::loncommon::end_data_table().'<br />');
                   11070:     }
                   11071:     if ($failed) {
1.572     www      11072:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  11073:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   11074:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   11075:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   11076:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   11077:                  $badstudents."\n".
                   11078:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      11079:                  &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  11080:     }
1.614     www      11081:     $r->print('</form><br />');
1.523     raeburn  11082:     return;
                   11083: }
                   11084: 
1.542     raeburn  11085: sub verify_scantron_grading {
1.554     raeburn  11086:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  11087:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   11088:         $respnumlookup,$startline) = @_;
1.542     raeburn  11089:     my ($record,%expected,%startpos);
                   11090:     return ($counter,$record) if (!ref($resource));
                   11091:     return ($counter,$record) if (!$resource->is_problem());
                   11092:     my $symb = $resource->symb();
1.554     raeburn  11093:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   11094:     foreach my $part_id (@{$partids}) {
1.542     raeburn  11095:         $counter ++;
                   11096:         $expected{$part_id} = 0;
1.691     raeburn  11097:         my $respnum = $counter;
                   11098:         if ($randomorder || $randompick) {
                   11099:             $respnum = $respnumlookup->{$counter};
                   11100:             $startpos{$part_id} = $startline->{$counter} + 1;
                   11101:         } else {
                   11102:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   11103:         }
                   11104:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   11105:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  11106:             foreach my $item (@sub_lines) {
                   11107:                 $expected{$part_id} += $item;
                   11108:             }
                   11109:         } else {
1.691     raeburn  11110:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  11111:         }
                   11112:     }
                   11113:     if ($symb) {
                   11114:         my %recorded;
                   11115:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   11116:         if ($returnhash{'version'}) {
                   11117:             my %lasthash=();
                   11118:             my $version;
                   11119:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   11120:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   11121:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   11122:                 }
                   11123:             }
                   11124:             foreach my $key (keys(%lasthash)) {
                   11125:                 if ($key =~ /\.scantron$/) {
                   11126:                     my $value = &unescape($lasthash{$key});
                   11127:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   11128:                     if ($value eq '') {
                   11129:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11130:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   11131:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11132:                             }
                   11133:                         }
                   11134:                     } else {
                   11135:                         my @tocheck;
                   11136:                         my @items = split(//,$value);
                   11137:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   11138:                             ($scantron_config->{'Qon'} eq 'number')) {
                   11139:                             if (@items < $expected{$part_id}) {
                   11140:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   11141:                                 my @singles = split(//,$fragment);
                   11142:                                 foreach my $pos (@singles) {
                   11143:                                     if ($pos eq ' ') {
                   11144:                                         push(@tocheck,$pos);
                   11145:                                     } else {
                   11146:                                         my $next = shift(@items);
                   11147:                                         push(@tocheck,$next);
                   11148:                                     }
                   11149:                                 }
                   11150:                             } else {
                   11151:                                 @tocheck = @items;
                   11152:                             }
                   11153:                             foreach my $letter (@tocheck) {
                   11154:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   11155:                                     if ($letter !~ /^[A-J]$/) {
                   11156:                                         $letter = $scantron_config->{'Qoff'};
                   11157:                                     }
                   11158:                                     $recorded{$part_id} .= $letter;
                   11159:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   11160:                                     my $digit;
                   11161:                                     if ($letter !~ /^[A-J]$/) {
                   11162:                                         $digit = $scantron_config->{'Qoff'};
                   11163:                                     } else {
                   11164:                                         $digit = $lettdig->{$letter};
                   11165:                                     }
                   11166:                                     $recorded{$part_id} .= $digit;
                   11167:                                 }
                   11168:                             }
                   11169:                         } else {
                   11170:                             @tocheck = @items;
                   11171:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11172:                                 my $curr_sub = shift(@tocheck);
                   11173:                                 my $digit;
                   11174:                                 if ($curr_sub =~ /^[A-J]$/) {
                   11175:                                     $digit = $lettdig->{$curr_sub}-1;
                   11176:                                 }
                   11177:                                 if ($curr_sub eq 'J') {
                   11178:                                     $digit += scalar($numletts);
                   11179:                                 }
                   11180:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11181:                                     if ($j == $digit) {
                   11182:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   11183:                                     } else {
                   11184:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11185:                                     }
                   11186:                                 }
                   11187:                             }
                   11188:                         }
                   11189:                     }
                   11190:                 }
                   11191:             }
                   11192:         }
1.554     raeburn  11193:         foreach my $part_id (@{$partids}) {
1.542     raeburn  11194:             if ($recorded{$part_id} eq '') {
                   11195:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   11196:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   11197:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   11198:                     }
                   11199:                 }
                   11200:             }
                   11201:             $record .= $recorded{$part_id};
                   11202:         }
                   11203:     }
                   11204:     return ($counter,$record);
                   11205: }
                   11206: 
1.75      albertel 11207: #-------- end of section for handling grading scantron forms -------
                   11208: #
                   11209: #-------------------------------------------------------------------
                   11210: 
1.72      ng       11211: #-------------------------- Menu interface -------------------------
                   11212: #
1.614     www      11213: #--- Href with symb and command ---
                   11214: 
                   11215: sub href_symb_cmd {
                   11216:     my ($symb,$cmd)=@_;
1.796     raeburn  11217:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.
                   11218:            &HTML::Entities::encode($cmd,'<>&"');
1.72      ng       11219: }
                   11220: 
1.443     banghart 11221: sub grading_menu {
1.608     www      11222:     my ($request,$symb) = @_;
1.443     banghart 11223:     if (!$symb) {return '';}
                   11224: 
                   11225:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      11226:                   'command'=>'individual');
1.538     schulted 11227:     
1.598     www      11228:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11229: 
                   11230:     $fields{'command'}='ungraded';
                   11231:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11232: 
                   11233:     $fields{'command'}='table';
                   11234:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11235: 
                   11236:     $fields{'command'}='all_for_one';
                   11237:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11238: 
1.621     www      11239:     $fields{'command'}='downloadfilesselect';
                   11240:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11241: 
1.443     banghart 11242:     $fields{'command'} = 'csvform';
1.538     schulted 11243:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11244:     
1.443     banghart 11245:     $fields{'command'} = 'processclicker';
1.538     schulted 11246:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11247:     
1.443     banghart 11248:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 11249:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      11250: 
                   11251:     $fields{'command'} = 'initialverifyreceipt';
                   11252:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  11253: 
                   11254:     my %permissions;
                   11255:     if ($perm{'mgr'}) {
                   11256:         $permissions{'either'} = 'F';
                   11257:         $permissions{'mgr'} = 'F';
                   11258:     }
                   11259:     if ($perm{'vgr'}) {
                   11260:         $permissions{'either'} = 'F';
                   11261:         $permissions{'vgr'} = 'F';
                   11262:     }
                   11263: 
1.598     www      11264:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 11265:             items =>[
1.598     www      11266:                         {	linktext => 'Select individual students to grade',
                   11267:                     		url => $url1a,
1.781     raeburn  11268:                     		permission => $permissions{'either'},
1.636     wenzelju 11269:                     		icon => 'grade_students.png',
1.598     www      11270:                     		linktitle => 'Grade current resource for a selection of students.'
                   11271:                         }, 
1.764     raeburn  11272:                         {       linktext => 'Grade ungraded submissions',
1.598     www      11273:                                 url => $url1b,
1.781     raeburn  11274:                                 permission => $permissions{'either'},
1.636     wenzelju 11275:                                 icon => 'ungrade_sub.png',
1.598     www      11276:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 11277:                         },
1.598     www      11278: 
                   11279:                         {       linktext => 'Grading table',
                   11280:                                 url => $url1c,
1.781     raeburn  11281:                                 permission => $permissions{'either'},
1.636     wenzelju 11282:                                 icon => 'grading_table.png',
1.598     www      11283:                                 linktitle => 'Grade current resource for all students.'
                   11284:                         },
1.615     www      11285:                         {       linktext => 'Grade page/folder for one student',
1.598     www      11286:                                 url => $url1d,
1.781     raeburn  11287:                                 permission => $permissions{'either'},
1.636     wenzelju 11288:                                 icon => 'grade_PageFolder.png',
1.598     www      11289:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      11290:                         },
                   11291:                         {       linktext => 'Download submissions',
                   11292:                                 url => $url1e,
1.781     raeburn  11293:                                 permission => $permissions{'either'},
1.636     wenzelju 11294:                                 icon => 'download_sub.png',
1.621     www      11295:                                 linktitle => 'Download all students submissions.'
1.598     www      11296:                         }]},
                   11297:                          { categorytitle=>'Automated Grading',
                   11298:                items =>[
                   11299: 
1.538     schulted 11300:                 	    {	linktext => 'Upload Scores',
                   11301:                     		url => $url2,
1.780     raeburn  11302:                     		permission => $permissions{'mgr'},
1.538     schulted 11303:                     		icon => 'uploadscores.png',
                   11304:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   11305:                 	    },
                   11306:                 	    {	linktext => 'Process Clicker',
                   11307:                     		url => $url3,
1.780     raeburn  11308:                     		permission => $permissions{'mgr'},
1.538     schulted 11309:                     		icon => 'addClickerInfoFile.png',
                   11310:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   11311:                 	    },
1.587     raeburn  11312:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 11313:                     		url => $url4,
1.780     raeburn  11314:                     		permission => $permissions{'mgr'},
1.636     wenzelju 11315:                     		icon => 'bubblesheet.png',
1.648     bisitz   11316:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      11317:                 	    },
1.616     www      11318:                             {   linktext => 'Verify Receipt Number',
1.602     www      11319:                                 url => $url5,
1.780     raeburn  11320:                                 permission => $permissions{'either'},
1.636     wenzelju 11321:                                 icon => 'receipt_number.png',
1.602     www      11322:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   11323:                             }
                   11324: 
1.538     schulted 11325:                     ]
                   11326:             });
1.796     raeburn  11327:     my $cdom = $env{"course.$env{'request.course.id'}.domain"};
                   11328:     my $cnum = $env{"course.$env{'request.course.id'}.num"};
                   11329:     my %passback = &Apache::lonnet::dump('nohist_linkprot_passback',$cdom,$cnum);
                   11330:     if (keys(%passback)) {
                   11331:         $fields{'command'} = 'initialpassback';
                   11332:         my $url6 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   11333:         push (@{$menu[1]{items}},
                   11334:                   { linktext => 'Passback of Scores',
                   11335:                     url => $url6,
                   11336:                     permission => $permissions{'either'},
                   11337:                     icon => 'passback.png',
                   11338:                     linktitle => 'Passback scores to launcher CMS for resources accessed via LTI-mediated deep-linking',
                   11339:                   });
                   11340:     }
1.443     banghart 11341:     # Create the menu
                   11342:     my $Str;
1.445     banghart 11343:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   11344:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      11345:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 11346: 
1.602     www      11347:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 11348:     return $Str;    
                   11349: }
                   11350: 
1.598     www      11351: sub ungraded {
                   11352:     my ($request)=@_;
                   11353:     &submit_options($request);
                   11354: }
                   11355: 
1.599     www      11356: sub submit_options_sequence {
1.608     www      11357:     my ($request,$symb) = @_;
1.599     www      11358:     if (!$symb) {return '';}
1.600     www      11359:     &commonJSfunctions($request);
                   11360:     my $result;
1.599     www      11361: 
1.600     www      11362:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11363:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      11364:     $result.=&selectfield(0).
1.601     www      11365:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      11366:             <div>
                   11367:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11368:             </div>
                   11369:         </div>
                   11370:   </form>';
                   11371:     return $result;
                   11372: }
                   11373: 
                   11374: sub submit_options_table {
1.608     www      11375:     my ($request,$symb) = @_;
1.600     www      11376:     if (!$symb) {return '';}
1.599     www      11377:     &commonJSfunctions($request);
1.746     raeburn  11378:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      11379:     my $result;
                   11380: 
                   11381:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11382:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      11383: 
1.745     raeburn  11384:     $result.=&selectfield(1,$is_tool).
1.601     www      11385:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      11386:             <div>
                   11387:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11388:             </div>
                   11389:         </div>
                   11390:   </form>';
                   11391:     return $result;
                   11392: }
1.443     banghart 11393: 
1.621     www      11394: sub submit_options_download {
                   11395:     my ($request,$symb) = @_;
                   11396:     if (!$symb) {return '';}
                   11397: 
1.773     raeburn  11398:     my $res_error;
                   11399:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   11400:         &response_type($symb,\$res_error);
                   11401:     if ($res_error) {
                   11402:         $request->print(&mt('An error occurred retrieving response types'));
                   11403:         return;
                   11404:     }
                   11405:     unless ($numessay) {
                   11406:         $request->print(&mt('No essayresponse items found'));
                   11407:         return;
                   11408:     }
                   11409:     my $table;
                   11410:     if (ref($partlist) eq 'ARRAY') {
                   11411:         if (scalar(@$partlist) > 1 ) {
                   11412:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   11413:         }
                   11414:     }
                   11415: 
1.746     raeburn  11416:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      11417:     &commonJSfunctions($request);
                   11418: 
                   11419:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  11420:                $table."\n".
                   11421:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      11422:     $result.='
                   11423: <h2>
1.750     raeburn  11424:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  11425: </h2>'.&selectfield(1,$is_tool).'
1.621     www      11426:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   11427:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11428:             </div>
                   11429:           </div>
1.600     www      11430: 
                   11431: 
1.621     www      11432:   </form>';
                   11433:     return $result;
                   11434: }
                   11435: 
1.443     banghart 11436: #--- Displays the submissions first page -------
                   11437: sub submit_options {
1.608     www      11438:     my ($request,$symb) = @_;
1.72      ng       11439:     if (!$symb) {return '';}
                   11440: 
1.746     raeburn  11441:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       11442:     &commonJSfunctions($request);
1.473     albertel 11443:     my $result;
1.533     bisitz   11444: 
1.72      ng       11445:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      11446: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  11447:     $result.=&selectfield(1,$is_tool).'
1.601     www      11448:                 <input type="hidden" name="command" value="submission" /> 
                   11449: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   11450:             </div>
                   11451:           </div>
                   11452:   </form>';
                   11453:     return $result;
                   11454: }
1.533     bisitz   11455: 
1.601     www      11456: sub selectfield {
1.745     raeburn  11457:    my ($full,$is_tool)=@_;
                   11458:    my %options;
                   11459:    if ($is_tool) {
                   11460:        %options =
                   11461:            (&transtatus_options,
                   11462:             'select_form_order' => ['yes','incorrect','all']);
                   11463:    } else {
                   11464:        %options = 
                   11465:            (&substatus_options,
                   11466:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   11467:    }
1.782     raeburn  11468: 
                   11469:   #
                   11470:   # PrepareClasslist() needs to be called to avoid getting a sections list
                   11471:   # for a different course from the @Sections global in lonstatistics.pm, 
                   11472:   # populated by an earlier request.
                   11473:   #
                   11474:    &Apache::lonstatistics::PrepareClasslist();
                   11475: 
1.601     www      11476:    my $result='<div class="LC_columnSection">
1.537     harmsja  11477:   
1.533     bisitz   11478:     <fieldset>
                   11479:       <legend>
                   11480:        '.&mt('Sections').'
                   11481:       </legend>
1.601     www      11482:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   11483:     </fieldset>
1.537     harmsja  11484:   
1.533     bisitz   11485:     <fieldset>
                   11486:       <legend>
                   11487:         '.&mt('Groups').'
                   11488:       </legend>
                   11489:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   11490:     </fieldset>
1.537     harmsja  11491:   
1.533     bisitz   11492:     <fieldset>
                   11493:       <legend>
                   11494:         '.&mt('Access Status').'
                   11495:       </legend>
1.601     www      11496:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   11497:     </fieldset>';
                   11498:     if ($full) {
1.745     raeburn  11499:         my $heading = &mt('Submission Status');
                   11500:         if ($is_tool) {
                   11501:             $heading = &mt('Transaction Status');
                   11502:         }
                   11503:         $result.='
1.533     bisitz   11504:     <fieldset>
                   11505:       <legend>
1.745     raeburn  11506:         '.$heading.'
1.601     www      11507:       </legend>'.
1.635     raeburn  11508:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      11509:    '</fieldset>';
                   11510:     }
                   11511:     $result.='</div><br />';
1.44      ng       11512:     return $result;
1.2       albertel 11513: }
                   11514: 
1.738     raeburn  11515: sub substatus_options {
                   11516:     return &Apache::lonlocal::texthash(
                   11517:                                       'yes'       => 'with submissions',
                   11518:                                       'queued'    => 'in grading queue',
                   11519:                                       'graded'    => 'with ungraded submissions',
                   11520:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  11521:                                       'all'       => 'with any status',
                   11522:                                       );
1.738     raeburn  11523: }
                   11524: 
1.745     raeburn  11525: sub transtatus_options {
                   11526:     return &Apache::lonlocal::texthash(
                   11527:                                        'yes'       => 'with score transactions',
                   11528:                                        'incorrect' => 'with less than full credit',
                   11529:                                        'all'       => 'with any status',
                   11530:                                       );
                   11531: }
                   11532: 
1.285     albertel 11533: sub reset_perm {
                   11534:     undef(%perm);
                   11535: }
                   11536: 
                   11537: sub init_perm {
                   11538:     &reset_perm();
1.770     raeburn  11539:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 11540: 
                   11541: 	my $scope = $env{'request.course.id'};
                   11542: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   11543: 
                   11544: 	    $scope .= '/'.$env{'request.course.sec'};
                   11545: 	    if ( $perm{$test_perm}=
                   11546: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   11547: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   11548: 	    } else {
                   11549: 		delete($perm{$test_perm});
                   11550: 	    }
1.285     albertel 11551: 	}
                   11552:     }
                   11553: }
                   11554: 
1.674     raeburn  11555: sub init_old_essays {
                   11556:     my ($symb,$apath,$adom,$aname) = @_;
                   11557:     if ($symb ne '') {
                   11558:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   11559:         if (keys(%essays) > 0) {
                   11560:             $old_essays{$symb} = \%essays;
                   11561:         }
                   11562:     }
                   11563:     return;
                   11564: }
                   11565: 
                   11566: sub reset_old_essays {
                   11567:     undef(%old_essays);
                   11568: }
                   11569: 
1.400     www      11570: sub gather_clicker_ids {
1.408     albertel 11571:     my %clicker_ids;
1.400     www      11572: 
                   11573:     my $classlist = &Apache::loncoursedata::get_classlist();
                   11574: 
                   11575:     # Set up a couple variables.
1.407     albertel 11576:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   11577:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      11578:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      11579: 
1.407     albertel 11580:     foreach my $student (keys(%$classlist)) {
1.438     www      11581:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 11582:         my $username = $classlist->{$student}->[$username_idx];
                   11583:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      11584:         my $clickers =
1.408     albertel 11585: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      11586:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      11587:             $id=~s/^[\#0]+//;
1.421     www      11588:             $id=~s/[\-\:]//g;
1.407     albertel 11589:             if (exists($clicker_ids{$id})) {
1.408     albertel 11590: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      11591:             } else {
1.408     albertel 11592: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      11593:             }
                   11594:         }
                   11595:     }
1.407     albertel 11596:     return %clicker_ids;
1.400     www      11597: }
                   11598: 
1.402     www      11599: sub gather_adv_clicker_ids {
1.408     albertel 11600:     my %clicker_ids;
1.402     www      11601:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   11602:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   11603:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 11604:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      11605:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   11606:             my ($puname,$pudom)=split(/\:/,$person);
                   11607:             my $clickers =
1.408     albertel 11608: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      11609:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      11610: 		$id=~s/^[\#0]+//;
1.421     www      11611:                 $id=~s/[\-\:]//g;
1.408     albertel 11612: 		if (exists($clicker_ids{$id})) {
                   11613: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   11614: 		} else {
                   11615: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   11616: 		}
1.405     www      11617:             }
1.402     www      11618:         }
                   11619:     }
1.407     albertel 11620:     return %clicker_ids;
1.402     www      11621: }
                   11622: 
1.413     www      11623: sub clicker_grading_parameters {
                   11624:     return ('gradingmechanism' => 'scalar',
                   11625:             'upfiletype' => 'scalar',
                   11626:             'specificid' => 'scalar',
                   11627:             'pcorrect' => 'scalar',
                   11628:             'pincorrect' => 'scalar');
                   11629: }
                   11630: 
1.400     www      11631: sub process_clicker {
1.608     www      11632:     my ($r,$symb)=@_;
1.400     www      11633:     if (!$symb) {return '';}
                   11634:     my $result=&checkforfile_js();
1.632     www      11635:     $result.=&Apache::loncommon::start_data_table().
                   11636:              &Apache::loncommon::start_data_table_header_row().
                   11637:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   11638:              &Apache::loncommon::end_data_table_header_row().
                   11639:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      11640: # Attempt to restore parameters from last session, set defaults if not present
                   11641:     my %Saveable_Parameters=&clicker_grading_parameters();
                   11642:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   11643:                                                  \%Saveable_Parameters);
                   11644:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   11645:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   11646:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   11647:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   11648: 
                   11649:     my %checked;
1.521     www      11650:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      11651:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   11652:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      11653:        }
                   11654:     }
                   11655: 
1.632     www      11656:     my $upload=&mt("Evaluate File");
1.400     www      11657:     my $type=&mt("Type");
1.402     www      11658:     my $attendance=&mt("Award points just for participation");
                   11659:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      11660:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      11661:     my $given=&mt("Correctness determined from given list of answers").' '.
                   11662:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      11663:     my $pcorrect=&mt("Percentage points for correct solution");
                   11664:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      11665:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  11666: 						   {'iclicker' => 'i>clicker',
1.666     www      11667:                                                     'interwrite' => 'interwrite PRS',
                   11668:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 11669:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 11670:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      11671: function sanitycheck() {
                   11672: // Accept only integer percentages
                   11673:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   11674:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   11675: // Find out grading choice
                   11676:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   11677:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   11678:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   11679:       }
                   11680:    }
                   11681: // By default, new choice equals user selection
                   11682:    newgradingchoice=gradingchoice;
                   11683: // Not good to give more points for false answers than correct ones
                   11684:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   11685:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   11686:    }
                   11687: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   11688:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   11689:       document.forms.gradesupload.pcorrect.value=100;
                   11690:       document.forms.gradesupload.pincorrect.value=100;
                   11691:    }
                   11692: // If the values are different, cannot be attendance only
                   11693:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   11694:        (gradingchoice=='attendance')) {
                   11695:        newgradingchoice='personnel';
                   11696:    }
                   11697: // Change grading choice to new one
                   11698:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   11699:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   11700:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   11701:       } else {
                   11702:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   11703:       }
                   11704:    }
                   11705: // Remember the old state
                   11706:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   11707: }
1.597     wenzelju 11708: ENDUPFORM
                   11709:     $result.= <<ENDUPFORM;
1.400     www      11710: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   11711: <input type="hidden" name="symb" value="$symb" />
                   11712: <input type="hidden" name="command" value="processclickerfile" />
                   11713: <input type="file" name="upfile" size="50" />
                   11714: <br /><label>$type: $selectform</label>
1.632     www      11715: ENDUPFORM
                   11716:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   11717:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   11718:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   11719: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   11720: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      11721: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   11722: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      11723: <br />&nbsp;&nbsp;&nbsp;
                   11724: <input type="text" name="givenanswer" size="50" />
1.413     www      11725: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      11726: ENDGRADINGFORM
1.766     raeburn  11727:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      11728:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   11729:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   11730: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   11731: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  11732: </form>
1.632     www      11733: ENDPERCFORM
                   11734:     $result.='</td>'.
                   11735:              &Apache::loncommon::end_data_table_row().
                   11736:              &Apache::loncommon::end_data_table();
1.400     www      11737:     return $result;
                   11738: }
                   11739: 
                   11740: sub process_clicker_file {
1.766     raeburn  11741:     my ($r,$symb) = @_;
1.400     www      11742:     if (!$symb) {return '';}
1.413     www      11743: 
                   11744:     my %Saveable_Parameters=&clicker_grading_parameters();
                   11745:     &Apache::loncommon::store_course_settings('grades_clicker',
                   11746:                                               \%Saveable_Parameters);
1.598     www      11747:     my $result='';
1.404     www      11748:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 11749: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      11750: 	return $result;
1.404     www      11751:     }
1.522     www      11752:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      11753:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      11754:         return $result;
1.521     www      11755:     }
1.522     www      11756:     my $foundgiven=0;
1.521     www      11757:     if ($env{'form.gradingmechanism'} eq 'given') {
                   11758:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   11759:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      11760:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      11761:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      11762:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   11763:         $foundgiven=$#answers+1;
1.521     www      11764:     }
1.407     albertel 11765:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 11766:     my %correct_ids;
1.404     www      11767:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 11768: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      11769:     }
                   11770:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      11771: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   11772: 	   $correct_id=~tr/a-z/A-Z/;
                   11773: 	   $correct_id=~s/\s//gs;
                   11774: 	   $correct_id=~s/^[\#0]+//;
1.421     www      11775:            $correct_id=~s/[\-\:]//g;
1.414     www      11776:            if ($correct_id) {
                   11777: 	      $correct_ids{$correct_id}='specified';
                   11778:            }
                   11779:         }
1.400     www      11780:     }
1.404     www      11781:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 11782: 	$result.=&mt('Score based on attendance only');
1.521     www      11783:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      11784:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      11785:     } else {
1.408     albertel 11786: 	my $number=0;
1.411     www      11787: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 11788: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      11789: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 11790: 	    if ($correct_ids{$id} eq 'specified') {
                   11791: 		$result.=&mt('specified');
                   11792: 	    } else {
                   11793: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   11794: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   11795: 	    }
                   11796: 	    $number++;
                   11797: 	}
1.411     www      11798:         $result.="</p>\n";
1.710     bisitz   11799:         if ($number==0) {
                   11800:             $result .=
                   11801:                  &Apache::lonhtmlcommon::confirm_success(
                   11802:                      &mt('No IDs found to determine correct answer'),1);
                   11803:             return $result;
                   11804:         }
1.404     www      11805:     }
1.405     www      11806:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   11807:         $result .=
                   11808:             &Apache::lonhtmlcommon::confirm_success(
                   11809:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   11810:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      11811:         return $result;
1.405     www      11812:     }
1.760     raeburn  11813:     my $mimetype;
                   11814:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   11815:         my $mm = new File::MMagic;
                   11816:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   11817:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   11818:             $result.= '<p>'.
                   11819:                 &Apache::lonhtmlcommon::confirm_success(
                   11820:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   11821:             return $result;
                   11822:         }
                   11823:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   11824:         $result .= '<p>'.
                   11825:             &Apache::lonhtmlcommon::confirm_success(
                   11826:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   11827:         return $result;
                   11828:     }
1.410     www      11829: 
                   11830: # Were able to get all the info needed, now analyze the file
                   11831: 
1.411     www      11832:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 11833:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      11834:     $result.=&Apache::loncommon::start_data_table().
                   11835:              &Apache::loncommon::start_data_table_header_row().
                   11836:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   11837:              &Apache::loncommon::end_data_table_header_row().
                   11838:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   11839: <td>
1.410     www      11840: <form method="post" action="/adm/grades" name="clickeranalysis">
                   11841: <input type="hidden" name="symb" value="$symb" />
                   11842: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      11843: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   11844: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   11845: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      11846: ENDHEADER
1.522     www      11847:     if ($env{'form.gradingmechanism'} eq 'given') {
                   11848:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   11849:     } 
1.408     albertel 11850:     my %responses;
                   11851:     my @questiontitles;
1.405     www      11852:     my $errormsg='';
                   11853:     my $number=0;
                   11854:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  11855:         if ($mimetype eq 'text/plain') {
                   11856:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   11857:         } elsif ($mimetype eq 'text/html') {
                   11858:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   11859:         }
                   11860:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      11861:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  11862:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      11863:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   11864:     }
1.411     www      11865:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   11866:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   11867:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   11868:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   11869:              '<br />';
1.522     www      11870:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   11871:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      11872:        return $result;
1.522     www      11873:     } 
1.414     www      11874: # Remember Question Titles
                   11875: # FIXME: Possibly need delimiter other than ":"
                   11876:     for (my $i=0;$i<$number;$i++) {
                   11877:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   11878:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   11879:     }
1.411     www      11880:     my $correct_count=0;
                   11881:     my $student_count=0;
                   11882:     my $unknown_count=0;
1.414     www      11883: # Match answers with usernames
                   11884: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 11885:     foreach my $id (keys(%responses)) {
1.410     www      11886:        if ($correct_ids{$id}) {
1.414     www      11887:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      11888:           $correct_count++;
1.410     www      11889:        } elsif ($clicker_ids{$id}) {
1.437     www      11890:           if ($clicker_ids{$id}=~/\,/) {
                   11891: # More than one user with the same clicker!
1.632     www      11892:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11893:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11894:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      11895:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11896:                            "<select name='multi".$id."'>";
                   11897:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   11898:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   11899:              }
                   11900:              $result.='</select>';
                   11901:              $unknown_count++;
                   11902:           } else {
                   11903: # Good: found one and only one user with the right clicker
                   11904:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   11905:              $student_count++;
                   11906:           }
1.410     www      11907:        } else {
1.632     www      11908:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11909:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11910:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      11911:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11912:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   11913:                    "\n".&mt("Domain").": ".
                   11914:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  11915:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      11916:           $unknown_count++;
1.410     www      11917:        }
1.405     www      11918:     }
1.412     www      11919:     $result.='<hr />'.
                   11920:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      11921:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      11922:        if ($correct_count==0) {
1.696     bisitz   11923:           $errormsg.="Found no correct answers for grading!";
1.412     www      11924:        } elsif ($correct_count>1) {
1.414     www      11925:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      11926:        }
                   11927:     }
1.428     www      11928:     if ($number<1) {
                   11929:        $errormsg.="Found no questions.";
                   11930:     }
1.412     www      11931:     if ($errormsg) {
                   11932:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   11933:     } else {
                   11934:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   11935:     }
1.632     www      11936:     $result.='</form></td>'.
                   11937:              &Apache::loncommon::end_data_table_row().
                   11938:              &Apache::loncommon::end_data_table();
1.614     www      11939:     return $result;
1.400     www      11940: }
                   11941: 
1.405     www      11942: sub iclicker_eval {
1.406     www      11943:     my ($questiontitles,$responses)=@_;
1.405     www      11944:     my $number=0;
                   11945:     my $errormsg='';
                   11946:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      11947:         my %components=&Apache::loncommon::record_sep($line);
                   11948:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 11949: 	if ($entries[0] eq 'Question') {
                   11950: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   11951: 		$$questiontitles[$number]=$entries[$i];
                   11952: 		$number++;
                   11953: 	    }
                   11954: 	}
                   11955: 	if ($entries[0]=~/^\#/) {
                   11956: 	    my $id=$entries[0];
                   11957: 	    my @idresponses;
                   11958: 	    $id=~s/^[\#0]+//;
                   11959: 	    for (my $i=0;$i<$number;$i++) {
                   11960: 		my $idx=3+$i*6;
1.644     www      11961:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 11962: 		push(@idresponses,$entries[$idx]);
                   11963: 	    }
                   11964: 	    $$responses{$id}=join(',',@idresponses);
                   11965: 	}
1.405     www      11966:     }
                   11967:     return ($errormsg,$number);
                   11968: }
                   11969: 
1.760     raeburn  11970: sub iclickerxml_eval {
                   11971:     my ($questiontitles,$responses)=@_;
                   11972:     my $number=0;
                   11973:     my $errormsg='';
                   11974:     my @state;
                   11975:     my %respbyid;
                   11976:     my $p = HTML::Parser->new
                   11977:     (
                   11978:         xml_mode => 1,
                   11979:         start_h =>
                   11980:             [sub {
                   11981:                  my ($tagname,$attr) = @_;
                   11982:                  push(@state,$tagname);
                   11983:                  if ("@state" eq "ssn p") {
                   11984:                      my $title = $attr->{qn};
                   11985:                      $title =~ s/(^\s+|\s+$)//g;
                   11986:                      $questiontitles->[$number]=$title;
                   11987:                  } elsif ("@state" eq "ssn p v") {
                   11988:                      my $id = $attr->{id};
                   11989:                      my $entry = $attr->{ans};
                   11990:                      $id=~s/^[\#0]+//;
                   11991:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   11992:                      $respbyid{$id}[$number] = $entry;
                   11993:                  }
                   11994:             }, "tagname, attr"],
                   11995:          end_h =>
                   11996:                [sub {
                   11997:                    my ($tagname) = @_;
                   11998:                    if ("@state" eq "ssn p") {
                   11999:                        $number++;
                   12000:                    }
                   12001:                    pop(@state);
                   12002:                 }, "tagname"],
                   12003:     );
                   12004: 
                   12005:     $p->parse($env{'form.upfile'});
                   12006:     $p->eof;
                   12007:     foreach my $id (keys(%respbyid)) {
                   12008:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   12009:     }
                   12010:     return ($errormsg,$number);
                   12011: }
                   12012: 
1.419     www      12013: sub interwrite_eval {
                   12014:     my ($questiontitles,$responses)=@_;
                   12015:     my $number=0;
                   12016:     my $errormsg='';
1.420     www      12017:     my $skipline=1;
                   12018:     my $questionnumber=0;
                   12019:     my %idresponses=();
1.419     www      12020:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12021:         my %components=&Apache::loncommon::record_sep($line);
                   12022:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      12023:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   12024:         if ($entries[1] eq 'Response') { $skipline=1; }
                   12025:         next if $skipline;
                   12026:         if ($entries[0]!=$questionnumber) {
                   12027:            $questionnumber=$entries[0];
                   12028:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   12029:            $number++;
1.419     www      12030:         }
1.420     www      12031:         my $id=$entries[4];
                   12032:         $id=~s/^[\#0]+//;
1.421     www      12033:         $id=~s/^v\d*\://i;
                   12034:         $id=~s/[\-\:]//g;
1.420     www      12035:         $idresponses{$id}[$number]=$entries[6];
                   12036:     }
1.524     raeburn  12037:     foreach my $id (keys(%idresponses)) {
1.420     www      12038:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   12039:        $$responses{$id}=~s/^\s*\,//;
1.419     www      12040:     }
                   12041:     return ($errormsg,$number);
                   12042: }
                   12043: 
1.666     www      12044: sub turning_eval {
                   12045:     my ($questiontitles,$responses)=@_;
                   12046:     my $number=0;
                   12047:     my $errormsg='';
                   12048:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   12049:         my %components=&Apache::loncommon::record_sep($line);
                   12050:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   12051:         if ($#entries>$number) { $number=$#entries; }
                   12052:         my $id=$entries[0];
                   12053:         my @idresponses;
                   12054:         $id=~s/^[\#0]+//;
                   12055:         unless ($id) { next; }
                   12056:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   12057:             $entries[$idx]=~s/\,/\;/g;
                   12058:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   12059:             push(@idresponses,$entries[$idx]);
                   12060:         }
                   12061:         $$responses{$id}=join(',',@idresponses);
                   12062:     }
                   12063:     for (my $i=1; $i<=$number; $i++) {
                   12064:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   12065:     }
                   12066:     return ($errormsg,$number);
                   12067: }
                   12068: 
                   12069: 
1.414     www      12070: sub assign_clicker_grades {
1.766     raeburn  12071:     my ($r,$symb) = @_;
1.414     www      12072:     if (!$symb) {return '';}
1.416     www      12073: # See which part we are saving to
1.582     raeburn  12074:     my $res_error;
                   12075:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   12076:     if ($res_error) {
                   12077:         return &navmap_errormsg();
                   12078:     }
1.416     www      12079: # FIXME: This should probably look for the first handgradeable part
                   12080:     my $part=$$partlist[0];
                   12081: # Start screen output
1.766     raeburn  12082:     my $result = &Apache::loncommon::start_data_table().
                   12083:                  &Apache::loncommon::start_data_table_header_row().
                   12084:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   12085:                  &Apache::loncommon::end_data_table_header_row().
                   12086:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      12087: # Get correct result
                   12088: # FIXME: Possibly need delimiter other than ":"
                   12089:     my @correct=();
1.415     www      12090:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   12091:     my $number=$env{'form.number'};
                   12092:     if ($gradingmechanism ne 'attendance') {
1.414     www      12093:        foreach my $key (keys(%env)) {
                   12094:           if ($key=~/^form\.correct\:/) {
                   12095:              my @input=split(/\,/,$env{$key});
                   12096:              for (my $i=0;$i<=$#input;$i++) {
                   12097:                  if (($correct[$i]) && ($input[$i]) &&
                   12098:                      ($correct[$i] ne $input[$i])) {
                   12099:                     $result.='<br /><span class="LC_warning">'.
                   12100:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   12101:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      12102:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      12103:                     $correct[$i]=$input[$i];
                   12104:                  }
                   12105:              }
                   12106:           }
                   12107:        }
1.415     www      12108:        for (my $i=0;$i<$number;$i++) {
1.644     www      12109:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      12110:              $result.='<br /><span class="LC_error">'.
                   12111:                       &mt('No correct result given for question "[_1]"!',
                   12112:                           $env{'form.question:'.$i}).'</span>';
                   12113:           }
                   12114:        }
1.644     www      12115:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      12116:     }
                   12117: # Start grading
1.415     www      12118:     my $pcorrect=$env{'form.pcorrect'};
                   12119:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      12120:     my $storecount=0;
1.632     www      12121:     my %users=();
1.415     www      12122:     foreach my $key (keys(%env)) {
1.420     www      12123:        my $user='';
1.415     www      12124:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      12125:           $user=$1;
                   12126:        }
                   12127:        if ($key=~/^form\.unknown\:(.*)$/) {
                   12128:           my $id=$1;
                   12129:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   12130:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      12131:           } elsif ($env{'form.multi'.$id}) {
                   12132:              $user=$env{'form.multi'.$id};
1.420     www      12133:           }
                   12134:        }
1.632     www      12135:        if ($user) {
                   12136:           if ($users{$user}) {
                   12137:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   12138:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      12139:                       '</span><br />';
                   12140:           }
                   12141:           $users{$user}=1; 
1.415     www      12142:           my @answer=split(/\,/,$env{$key});
                   12143:           my $sum=0;
1.522     www      12144:           my $realnumber=$number;
1.415     www      12145:           for (my $i=0;$i<$number;$i++) {
1.576     www      12146:              if  ($correct[$i] eq '-') {
                   12147:                 $realnumber--;
1.766     raeburn  12148:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      12149:                 if ($gradingmechanism eq 'attendance') {
                   12150:                    $sum+=$pcorrect;
1.576     www      12151:                 } elsif ($correct[$i] eq '*') {
1.522     www      12152:                    $sum+=$pcorrect;
1.415     www      12153:                 } else {
1.644     www      12154: # We actually grade if correct or not
                   12155:                    my $increment=$pincorrect;
                   12156: # Special case: numerical answer "0"
                   12157:                    if ($correct[$i] eq '0') {
                   12158:                       if ($answer[$i]=~/^[0\.]+$/) {
                   12159:                          $increment=$pcorrect;
                   12160:                       }
                   12161: # General numerical answer, both evaluate to something non-zero
                   12162:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   12163:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   12164:                          $increment=$pcorrect;
                   12165:                       }
                   12166: # Must be just alphanumeric
                   12167:                    } elsif ($answer[$i] eq $correct[$i]) {
                   12168:                       $increment=$pcorrect;
1.415     www      12169:                    }
1.644     www      12170:                    $sum+=$increment;
1.415     www      12171:                 }
                   12172:              }
                   12173:           }
1.522     www      12174:           my $ave=$sum/(100*$realnumber);
1.416     www      12175: # Store
                   12176:           my ($username,$domain)=split(/\:/,$user);
                   12177:           my %grades=();
                   12178:           $grades{"resource.$part.solved"}='correct_by_override';
                   12179:           $grades{"resource.$part.awarded"}=$ave;
                   12180:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   12181:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   12182:                                                  $env{'request.course.id'},
                   12183:                                                  $domain,$username);
                   12184:           if ($returncode ne 'ok') {
                   12185:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   12186:           } else {
                   12187:              $storecount++;
                   12188:           }
1.415     www      12189:        }
                   12190:     }
                   12191: # We are done
1.549     hauer    12192:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      12193:              '</td>'.
                   12194:              &Apache::loncommon::end_data_table_row().
                   12195:              &Apache::loncommon::end_data_table();
1.614     www      12196:     return $result;
1.414     www      12197: }
                   12198: 
1.582     raeburn  12199: sub navmap_errormsg {
                   12200:     return '<div class="LC_error">'.
                   12201:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  12202:            &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  12203:            '</div>';
                   12204: }
1.607     droeschl 12205: 
1.609     www      12206: sub startpage {
1.777     raeburn  12207:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  12208:     my %args;
                   12209:     if ($onload) {
                   12210:          my %loaditems = (
                   12211:                         'onload' => $onload,
                   12212:                       );
                   12213:          $args{'add_entries'} = \%loaditems;
                   12214:     }
1.671     raeburn  12215:     if ($nomenu) {
1.754     raeburn  12216:         $args{'only_body'} = 1; 
1.777     raeburn  12217:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  12218:     } else {
1.785     raeburn  12219:         if ($env{'request.course.id'}) { 
                   12220:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   12221:         }
1.754     raeburn  12222:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  12223:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  12224:         if ($env{'request.course.id'}) {
                   12225:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   12226:         }
1.671     raeburn  12227:     }
1.613     www      12228:     unless ($nodisplayflag) {
1.773     raeburn  12229:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      12230:     }
1.607     droeschl 12231: }
1.582     raeburn  12232: 
1.622     www      12233: sub select_problem {
                   12234:     my ($r)=@_;
1.632     www      12235:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  12236:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      12237:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   12238:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   12239: }
                   12240: 
1.793     raeburn  12241: #----- display problem, answer, and submissions for a single student (no grading)
                   12242: 
                   12243: sub view_as_user {
                   12244:     my ($symb,$vuname,$vudom,$hasperm) = @_;
                   12245:     my $plainname = &Apache::loncommon::plainname($vuname,$vudom,'lastname');
                   12246:     my $displayname = &nameUserString('',$plainname,$vuname,$vudom);
                   12247:     my $output = &Apache::loncommon::get_student_view($symb,$vuname,$vudom,
                   12248:                                                       $env{'request.course.id'},
                   12249:                                                       undef,{'disable_submit' => 1}).
                   12250:                  "\n\n".
                   12251:                  '<div class="LC_grade_show_user">'.
                   12252:                  '<h2>'.$displayname.'</h2>'.
                   12253:                  "\n".
                   12254:                  &Apache::loncommon::track_student_link('View recent activity',
                   12255:                                                         $vuname,$vudom,'check').' '.
                   12256:                  "\n";
                   12257:     if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) ||
                   12258:         (($env{'request.course.sec'} ne '') &&
                   12259:          &Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
                   12260:         $output .= &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   12261:                                                $vuname,$vudom,$symb,'check');
                   12262:     }
                   12263:     $output .= "\n";
                   12264:     my $companswer = &Apache::loncommon::get_student_answers($symb,$vuname,$vudom,
                   12265:                                                              $env{'request.course.id'});
                   12266:     $companswer=~s|<form(.*?)>||g;
                   12267:     $companswer=~s|</form>||g;
                   12268:     $companswer=~s|name="submit"|name="would_have_been_submit"|g;
                   12269:     $output .= '<div class="LC_Box">'.
                   12270:                '<h3 class="LC_hcell">'.&mt('Correct answer for[_1]',$displayname).'</h3>'.
                   12271:                $companswer.
                   12272:                '</div>'."\n";
                   12273:     my $is_tool = ($symb =~ /ext\.tool$/);
                   12274:     my ($essayurl,%coursedesc_by_cid);
                   12275:     (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   12276:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$vudom,$vuname);
                   12277:     my $res_error;
                   12278:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   12279:         &response_type($symb,\$res_error);
                   12280:     my $fullname;
                   12281:     my $collabinfo;
                   12282:     if ($numessay) {
                   12283:         unless ($hasperm) {
                   12284:             &init_perm();
                   12285:         }
                   12286:         ($collabinfo,$fullname)=
                   12287:             &check_collaborators($symb,$vuname,$vudom,\%record,$handgrade,0);
                   12288:         unless ($hasperm) {
                   12289:             &reset_perm();
                   12290:         }
                   12291:     }
                   12292:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   12293:                     '" src="'.$Apache::lonnet::perlvar{'lonIconsURL'}.
                   12294:                     '/check.gif" height="16" border="0" />';
                   12295:     my ($lastsubonly,$partinfo) =
                   12296:         &show_last_submission($vuname,$vudom,$symb,$essayurl,$responseType,'datesub',
                   12297:                               '',$fullname,\%record,\%coursedesc_by_cid);
                   12298:     $output .= '<div class="LC_Box">'.
                   12299:                '<h3 class="LC_hcell">'.&mt('Submissions').'</h3>'."\n".$collabinfo."\n";
                   12300:     if (($numresp > $numessay) & !$is_tool) {
                   12301:         $output .='<p class="LC_info">'.
                   12302:                   &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon).
                   12303:                   "</p>\n";
                   12304:     }
                   12305:     $output .= $partinfo;
                   12306:     $output .= $lastsubonly;
                   12307:     $output .= &displaySubByDates($symb,\%record,$partlist,$responseType,$checkIcon,$vuname,$vudom);
                   12308:     $output .= '</div></div>'."\n";
                   12309:     return $output;
                   12310: }
                   12311: 
1.1       albertel 12312: sub handler {
1.41      ng       12313:     my $request=$_[0];
1.434     albertel 12314:     &reset_caches();
1.646     raeburn  12315:     if ($request->header_only) {
                   12316:         &Apache::loncommon::content_type($request,'text/html');
                   12317:         $request->send_http_header;
                   12318:         return OK;
                   12319:     }
                   12320:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   12321: 
1.664     raeburn  12322: # see what command we need to execute
                   12323: 
                   12324:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   12325:     my $command=$commands[0];
                   12326: 
1.646     raeburn  12327:     &init_perm();
                   12328:     if (!$env{'request.course.id'}) {
1.664     raeburn  12329:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   12330:                 ($command =~ /^scantronupload/)) {
                   12331:             # Not in a course.
                   12332:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   12333:             return HTTP_NOT_ACCEPTABLE;
                   12334:         }
1.646     raeburn  12335:     } elsif (!%perm) {
                   12336:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  12337:         return OK;
1.41      ng       12338:     }
1.646     raeburn  12339:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       12340:     $request->send_http_header;
1.646     raeburn  12341: 
1.160     albertel 12342:     if ($#commands > 0) {
                   12343: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   12344:     }
1.608     www      12345: 
                   12346: # see what the symb is
                   12347: 
                   12348:     my $symb=$env{'form.symb'};
                   12349:     unless ($symb) {
                   12350:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   12351:        $symb=&Apache::lonnet::symbread($url);
                   12352:     }
1.646     raeburn  12353:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      12354: 
1.513     foxr     12355:     $ssi_error = 0;
1.637     www      12356:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      12357: #
1.637     www      12358: # Not called from a resource, but inside a course
1.601     www      12359: #    
1.622     www      12360:         &startpage($request,undef,[],1,1);
                   12361:         &select_problem($request);
1.41      ng       12362:     } else {
1.104     albertel 12363: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  12364:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  12365:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   12366:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12367:                     &choose_task_version_form($symb,$env{'form.student'},
                   12368:                                               $env{'form.userdom'});
                   12369:             }
1.773     raeburn  12370:             my $divforres;
                   12371:             if ($env{'form.student'} eq '') {
                   12372:                 $js .= &part_selector_js();
                   12373:                 $onload = "toggleParts('gradesub');";
                   12374:             } else {
                   12375:                 $divforres = 1;
                   12376:             }
1.778     raeburn  12377:             my $head_extra = $js;
                   12378:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12379:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12380:                 if ($csslinks) {
                   12381:                     $head_extra .= "\n$csslinks";
                   12382:                 }
                   12383:             }
1.777     raeburn  12384:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   12385:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  12386:             if ($versionform) {
1.775     raeburn  12387:                 if ($divforres) {
                   12388:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   12389:                 }
1.671     raeburn  12390:                 $request->print($versionform);
                   12391:             }
1.773     raeburn  12392: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  12393:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   12394:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   12395:                 &choose_task_version_form($symb,$env{'form.student'},
                   12396:                                           $env{'form.userdom'},
                   12397:                                           $env{'form.inhibitmenu'});
1.778     raeburn  12398:             my $head_extra = $js;
                   12399:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12400:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12401:                 if ($csslinks) {
                   12402:                     $head_extra .= "\n$csslinks";
                   12403:                 }
                   12404:             }
1.777     raeburn  12405:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   12406:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  12407:             if ($versionform) {
                   12408:                 $request->print($versionform);
                   12409:             }
                   12410:             $request->print('<br clear="all" />');
                   12411:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 12412: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      12413:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12414:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      12415: 	    &pickStudentPage($request,$symb);
1.103     albertel 12416: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  12417:             my $csslinks;
                   12418:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12419:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  12420:             }
1.615     www      12421:             &startpage($request,$symb,
                   12422:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12423:                                        {href=>'',text=>'Select student'},
1.777     raeburn  12424:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      12425: 	    &displayPage($request,$symb);
1.104     albertel 12426: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      12427:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   12428:                                        {href=>'',text=>'Select student'},
                   12429:                                        {href=>'',text=>'Grade student'},
                   12430:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      12431: 	    &updateGradeByPage($request,$symb);
1.104     albertel 12432: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  12433:             my $csslinks;
                   12434:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  12435:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  12436:             }
1.619     www      12437:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  12438:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      12439: 	    &processGroup($request,$symb);
1.104     albertel 12440: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      12441:             &startpage($request,$symb);
                   12442: 	    $request->print(&grading_menu($request,$symb));
1.598     www      12443: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      12444:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      12445: 	    $request->print(&submit_options($request,$symb));
1.598     www      12446:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  12447:             my $js = &part_selector_js();
                   12448:             my $onload = "toggleParts('gradesub');";
                   12449:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   12450:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      12451:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      12452:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      12453:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      12454:             $request->print(&submit_options_table($request,$symb));
1.598     www      12455:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      12456:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      12457:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 12458: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      12459:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      12460: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 12461: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      12462:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   12463:                                        {href=>'',text=>'Store grades'}]);
1.608     www      12464: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 12465: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      12466:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   12467:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   12468:                                                                              text=>"Modify grades"},
                   12469:                                        {href=>'', text=>"Store grades"}]);
1.608     www      12470: 	    $request->print(&editgrades($request,$symb));
1.602     www      12471:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      12472:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      12473:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 12474: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      12475:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   12476:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      12477: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      12478:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      12479:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      12480:             $request->print(&process_clicker($request,$symb));
1.400     www      12481:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      12482:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   12483:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      12484:             $request->print(&process_clicker_file($request,$symb));
1.414     www      12485:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      12486:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   12487:                                        {href=>'', text=>'Process clicker file'},
                   12488:                                        {href=>'', text=>'Store grades'}]);
1.608     www      12489:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 12490: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      12491:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12492: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 12493: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      12494:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12495: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 12496: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      12497:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12498: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 12499: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 12500: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      12501:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12502: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       12503: 	    } else {
1.257     albertel 12504: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   12505: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       12506: 		} else {
1.257     albertel 12507: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       12508: 		}
1.627     www      12509:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12510: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       12511: 	    }
1.246     albertel 12512: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      12513:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      12514: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 12515: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  12516:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   12517:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      12518: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 12519:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      12520:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      12521:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 12522: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      12523:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      12524: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 12525: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      12526:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      12527: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 12528:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  12529:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  12530:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   12531:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      12532:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 12533:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  12534:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      12535:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      12536:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  12537:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      12538:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      12539:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  12540:         } elsif ($command eq 'scantronupload_delete' &&
                   12541:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   12542:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   12543:             &scantron_upload_delete($request,$symb);
1.523     raeburn  12544:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      12545:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      12546:             $request->print(&checkscantron_results($request,$symb));
                   12547:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  12548:             my $js = &part_selector_js();
                   12549:             my $onload = "toggleParts('gradingMenu');";
                   12550:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   12551:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      12552:             $request->print(&submit_options_download($request,$symb));
                   12553:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   12554:             &startpage($request,$symb,
                   12555:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  12556:     {href=>'', text=>'Download submitted files'}],
                   12557:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  12558:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      12559:             &submit_download_link($request,$symb);
1.796     raeburn  12560:         } elsif ($command eq 'initialpassback') {
                   12561:             &startpage($request,$symb,[{href=>'', text=>'Choose Launcher'}],undef,1);
                   12562:             $request->print(&initialpassback($request,$symb));
                   12563:         } elsif ($command eq 'passback') {
                   12564:             &startpage($request,$symb,
                   12565:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   12566:                         {href=>'', text=>'Types of User'}],undef,1);
                   12567:             $request->print(&passback_filters($request,$symb));
                   12568:         } elsif ($command eq 'passbacknames') {
                   12569:             my $chosen;
                   12570:             if ($env{'form.passback'} ne '') {
                   12571:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   12572:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   12573:                 }
                   12574:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   12575:             }
                   12576:             &startpage($request,$symb,
                   12577:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   12578:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   12579:                         {href=>'', text=>'Select Users'}],undef,1);
                   12580:             $request->print(&names_for_passback($request,$symb));
                   12581:         } elsif ($command eq 'passbackscores') {
                   12582:             my ($chosen,$stu_status);
                   12583:             if ($env{'form.passback'} ne '') {
                   12584:                 if ($env{'form.passback'} eq &unescape($env{'form.passback'})) {
                   12585:                     $env{'form.passback'} = &escape($env{'form.passback'} );
                   12586:                 }
                   12587:                 $chosen = &HTML::Entities::encode($env{'form.passback'},'<>"&');
                   12588:             }
                   12589:             if ($env{'form.Status'}) {
                   12590:                 $stu_status = &HTML::Entities::encode($env{'form.Status'});
                   12591:             }
                   12592:             &startpage($request,$symb,
                   12593:                        [{href=>&href_symb_cmd($symb,'initialpassback'), text=>'Choose Launcher'},
                   12594:                         {href=>&href_symb_cmd($symb,'passback').'&amp;passback='.$chosen, text=>'Types of User'},
                   12595:                         {href=>&href_symb_cmd($symb,'passbacknames').'&amp;Status='.$stu_status.'&amp;passback='.$chosen, text=>'Select Users'},
                   12596:                         {href=>'', text=>'Execute Passback'}],undef,1);
                   12597:             $request->print(&do_passback($request,$symb));
1.106     albertel 12598: 	} elsif ($command) {
1.620     www      12599:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   12600: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 12601: 	}
1.2       albertel 12602:     }
1.513     foxr     12603:     if ($ssi_error) {
                   12604: 	&ssi_print_error($request);
                   12605:     }
1.671     raeburn  12606:     if ($env{'form.inhibitmenu'}) {
                   12607:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  12608:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  12609:         &Apache::lonquickgrades::endGradeScreen($request);
                   12610:     }
1.434     albertel 12611:     &reset_caches();
1.646     raeburn  12612:     return OK;
1.44      ng       12613: }
                   12614: 
1.1       albertel 12615: 1;
                   12616: 
1.13      albertel 12617: __END__;
1.531     jms      12618: 
                   12619: 
                   12620: =head1 NAME
                   12621: 
                   12622: Apache::grades
                   12623: 
                   12624: =head1 SYNOPSIS
                   12625: 
                   12626: Handles the viewing of grades.
                   12627: 
                   12628: This is part of the LearningOnline Network with CAPA project
                   12629: described at http://www.lon-capa.org.
                   12630: 
                   12631: =head1 OVERVIEW
                   12632: 
                   12633: Do an ssi with retries:
1.715     bisitz   12634: While I'd love to factor out this with the version in lonprintout,
1.531     jms      12635: 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
                   12636: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   12637: 
                   12638: At least the logic that drives this has been pulled out into loncommon.
                   12639: 
                   12640: 
                   12641: 
                   12642: ssi_with_retries - Does the server side include of a resource.
                   12643:                      if the ssi call returns an error we'll retry it up to
                   12644:                      the number of times requested by the caller.
1.715     bisitz   12645:                      If we still have a problem, no text is appended to the
1.531     jms      12646:                      output and we set some global variables.
                   12647:                      to indicate to the caller an SSI error occurred.  
                   12648:                      All of this is supposed to deal with the issues described
1.715     bisitz   12649:                      in LON-CAPA BZ 5631 see:
1.531     jms      12650:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   12651:                      by informing the user that this happened.
                   12652: 
                   12653: Parameters:
                   12654:   resource   - The resource to include.  This is passed directly, without
                   12655:                interpretation to lonnet::ssi.
                   12656:   form       - The form hash parameters that guide the interpretation of the resource
                   12657:                
                   12658:   retries    - Number of retries allowed before giving up completely.
                   12659: Returns:
                   12660:   On success, returns the rendered resource identified by the resource parameter.
                   12661: Side Effects:
                   12662:   The following global variables can be set:
                   12663:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   12664:                               It is up to the caller to initialize this to false
                   12665:                               if desired.
                   12666:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   12667:                               of the resource that could not be rendered by the ssi
                   12668:                               call.
                   12669:    ssi_error_message   - The error string fetched from the ssi response
                   12670:                               in the event of an error.
                   12671: 
                   12672: 
                   12673: =head1 HANDLER SUBROUTINE
                   12674: 
                   12675: ssi_with_retries()
                   12676: 
                   12677: =head1 SUBROUTINES
                   12678: 
                   12679: =over
                   12680: 
1.671     raeburn  12681: =head1 Routines to display previous version of a Task for a specific student
                   12682: 
                   12683: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   12684: can receive another opportunity. Access to tasks is slot-based. If a slot
                   12685: requires a proctor to check-in the student, a new version of the Task will
                   12686: be created when the student is checked in to the new opportunity.
                   12687: 
                   12688: If a particular student has tried two or more versions of a particular task,
                   12689: the submission screen provides a user with vgr privileges (e.g., a Course
                   12690: Coordinator) the ability to display a previous version worked on by the
                   12691: student.  By default, the current version is displayed. If a previous version
                   12692: has been selected for display, submission data are only shown that pertain
                   12693: to that particular version, and the interface to submit grades is not shown.
                   12694: 
                   12695: =over 4
                   12696: 
                   12697: =item show_previous_task_version()
                   12698: 
                   12699: Displays a specified version of a student's Task, as the student sees it.
                   12700: 
                   12701: Inputs: 2
                   12702:         request - request object
                   12703:         symb    - unique symb for current instance of resource
                   12704: 
                   12705: Output: None.
                   12706: 
                   12707: Side Effects: calls &show_problem() to print version of Task, with
                   12708:               version contained in form item: $env{'form.previousversion'}
                   12709: 
                   12710: =item choose_task_version_form()
                   12711: 
                   12712: Displays a web form used to select which version of a student's view of a
                   12713: Task should be displayed.  Either launches a pop-up window, or replaces
                   12714: content in existing pop-up, or replaces page in main window.
                   12715: 
                   12716: Inputs: 4
                   12717:         symb    - unique symb for current instance of resource
                   12718:         uname   - username of student
                   12719:         udom    - domain of student
                   12720:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   12721:                   breadcrumbs etc., are displayed
                   12722: 
                   12723: Output: 4
                   12724:         current   - student's current version
                   12725:         displayed - student's version being displayed
                   12726:         result    - scalar containing HTML for web form used to switch to
                   12727:                     a different version (or a link to close window, if pop-up).
                   12728:         js        - javascript for processing selection in versions web form
                   12729: 
                   12730: Side Effects: None.
                   12731: 
                   12732: =item previous_display_javascript()
                   12733: 
                   12734: Inputs: 2
                   12735:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   12736:                   breadcrumbs etc., are displayed.
                   12737:         current - student's current version number.
                   12738: 
                   12739: Output: 1
                   12740:         js      - javascript for processing selection in versions web form.
                   12741: 
                   12742: Side Effects: None.
                   12743: 
                   12744: =back
                   12745: 
                   12746: =head1 Routines to process bubblesheet data.
                   12747: 
                   12748: =over 4
                   12749: 
1.531     jms      12750: =item scantron_get_correction() : 
                   12751: 
                   12752:    Builds the interface screen to interact with the operator to fix a
                   12753:    specific error condition in a specific scanline
                   12754: 
                   12755:  Arguments:
                   12756:     $r           - Apache request object
                   12757:     $i           - number of the current scanline
                   12758:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  12759:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      12760:     $line        - full contents of the current scanline
                   12761:     $error       - error condition, valid values are
                   12762:                    'incorrectCODE', 'duplicateCODE',
                   12763:                    'doublebubble', 'missingbubble',
                   12764:                    'duplicateID', 'incorrectID'
                   12765:     $arg         - extra information needed
                   12766:        For errors:
                   12767:          - duplicateID   - paper number that this studentID was seen before on
                   12768:          - duplicateCODE - array ref of the paper numbers this CODE was
                   12769:                            seen on before
                   12770:          - incorrectCODE - current incorrect CODE 
                   12771:          - doublebubble  - array ref of the bubble lines that have double
                   12772:                            bubble errors
                   12773:          - missingbubble - array ref of the bubble lines that have missing
                   12774:                            bubble errors
                   12775: 
1.788     raeburn  12776:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   12777:    $randompick  - True if exam folder (or a sub-folder) has randompick set
1.691     raeburn  12778:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   12779:                      for current line to question number used for same question
                   12780:                      in "Master Seqence" (as seen by Course Coordinator).
                   12781:    $startline   - Reference to hash where key is question number (0 is first)
                   12782:                   and value is number of first bubble line for current student
                   12783:                   or code-based randompick and/or randomorder.
                   12784: 
                   12785: 
                   12786: 
1.531     jms      12787: =item  scantron_get_maxbubble() : 
                   12788: 
1.582     raeburn  12789:    Arguments:
                   12790:        $nav_error  - Reference to scalar which is a flag to indicate a
                   12791:                       failure to retrieve a navmap object.
                   12792:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   12793:        calling routine should trap the error condition and display the warning
                   12794:        found in &navmap_errormsg().
                   12795: 
1.649     raeburn  12796:        $scantron_config - Reference to bubblesheet format configuration hash.
                   12797: 
1.531     jms      12798:    Returns the maximum number of bubble lines that are expected to
                   12799:    occur. Does this by walking the selected sequence rendering the
                   12800:    resource and then checking &Apache::lonxml::get_problem_counter()
                   12801:    for what the current value of the problem counter is.
                   12802: 
                   12803:    Caches the results to $env{'form.scantron_maxbubble'},
                   12804:    $env{'form.scantron.bubble_lines.n'}, 
                   12805:    $env{'form.scantron.first_bubble_line.n'} and
                   12806:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  12807:    which are the total number of bubble lines, the number of bubble
1.531     jms      12808:    lines for response n and number of the first bubble line for response n,
                   12809:    and a comma separated list of numbers of bubble lines for sub-questions
                   12810:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   12811: 
                   12812: 
                   12813: =item  scantron_validate_missingbubbles() : 
                   12814: 
                   12815:    Validates all scanlines in the selected file to not have any
                   12816:     answers that don't have bubbles that have not been verified
                   12817:     to be bubble free.
                   12818: 
                   12819: =item  scantron_process_students() : 
                   12820: 
1.659     raeburn  12821:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      12822: 
                   12823:    The parsed scanline hash is added to %env 
                   12824: 
                   12825:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   12826:    foreach resource , with the form data of
                   12827: 
                   12828: 	'submitted'     =>'scantron' 
                   12829: 	'grade_target'  =>'grade',
                   12830: 	'grade_username'=> username of student
                   12831: 	'grade_domain'  => domain of student
                   12832: 	'grade_courseid'=> of course
                   12833: 	'grade_symb'    => symb of resource to grade
                   12834: 
                   12835:     This triggers a grading pass. The problem grading code takes care
                   12836:     of converting the bubbled letter information (now in %env) into a
                   12837:     valid submission.
                   12838: 
                   12839: =item  scantron_upload_scantron_data() :
                   12840: 
1.659     raeburn  12841:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      12842: 
                   12843: =item  scantron_upload_scantron_data_save() : 
                   12844: 
                   12845:    Adds a provided bubble information data file to the course if user
1.770     raeburn  12846:    has the correct privileges to do so.
                   12847: 
                   12848: = item scantron_upload_delete() :
                   12849: 
                   12850:    Deletes a previously uploaded bubble information data file, if user
                   12851:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      12852: 
                   12853: =item  valid_file() :
                   12854: 
                   12855:    Validates that the requested bubble data file exists in the course.
                   12856: 
                   12857: =item  scantron_download_scantron_data() : 
                   12858: 
                   12859:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  12860:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      12861:    course.
                   12862: 
                   12863: =item  scantron_validate_ID() : 
                   12864: 
                   12865:    Validates all scanlines in the selected file to not have any
1.556     weissno  12866:    invalid or underspecified student/employee IDs
1.531     jms      12867: 
1.582     raeburn  12868: =item navmap_errormsg() :
                   12869: 
                   12870:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  12871:    Should be called whenever the request to instantiate a navmap object fails.
                   12872: 
                   12873: =back
1.582     raeburn  12874: 
1.531     jms      12875: =back
                   12876: 
                   12877: =cut

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