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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.795   ! raeburn     4: # $Id: grades.pm,v 1.794 2024/07/01 20:22:34 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.170     albertel   50: use String::Similarity;
1.760     raeburn    51: use HTML::Parser();
                     52: use File::MMagic;
1.359     www        53: use LONCAPA;
                     54: 
1.315     bowersj2   55: use POSIX qw(floor);
1.87      www        56: 
1.435     foxr       57: 
1.513     foxr       58: 
1.435     foxr       59: my %perm=();
1.674     raeburn    60: my %old_essays=();
1.447     foxr       61: 
1.513     foxr       62: #  These variables are used to recover from ssi errors
                     63: 
                     64: my $ssi_retries = 5;
                     65: my $ssi_error;
                     66: my $ssi_error_resource;
                     67: my $ssi_error_message;
                     68: 
                     69: 
                     70: sub ssi_with_retries {
                     71:     my ($resource, $retries, %form) = @_;
                     72:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     73:     if ($response->is_error) {
                     74: 	$ssi_error          = 1;
                     75: 	$ssi_error_resource = $resource;
                     76: 	$ssi_error_message  = $response->code . " " . $response->message;
                     77:     }
                     78: 
                     79:     return $content;
                     80: 
                     81: }
                     82: #
                     83: #  Prodcuces an ssi retry failure error message to the user:
                     84: #
                     85: 
                     86: sub ssi_print_error {
                     87:     my ($r) = @_;
1.516     raeburn    88:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     89:     $r->print('
                     90: <br />
                     91: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     92: <p>
                     93: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     94: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     95: '.&mt('Error:').' '.$ssi_error_message.'
                     96: </p>
                     97: <p>'.
                     98: &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 />'.
                     99: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                    100: '</p>');
                    101:     return;
1.513     foxr      102: }
                    103: 
1.44      ng        104: #
1.146     albertel  105: # --- Retrieve the parts from the metadata file.---
1.598     www       106: # Returns an array of everything that the resources stores away
                    107: #
                    108: 
1.44      ng        109: sub getpartlist {
1.582     raeburn   110:     my ($symb,$errorref) = @_;
1.439     albertel  111: 
                    112:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   113:     unless (ref($navmap)) {
                    114:         if (ref($errorref)) { 
                    115:             $$errorref = 'navmap';
                    116:             return;
                    117:         }
                    118:     }
1.439     albertel  119:     my $res      = $navmap->getBySymb($symb);
                    120:     my $partlist = $res->parts();
                    121:     my $url      = $res->src();
1.745     raeburn   122:     my $toolsymb;
                    123:     if ($url =~ /ext\.tool$/) {
                    124:         $toolsymb = $symb;
                    125:     }
                    126:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
1.439     albertel  127: 
1.146     albertel  128:     my @stores;
1.439     albertel  129:     foreach my $part (@{ $partlist }) {
1.146     albertel  130: 	foreach my $key (@metakeys) {
                    131: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    132: 	}
                    133:     }
                    134:     return @stores;
1.2       albertel  135: }
                    136: 
1.129     ng        137: #--- Format fullname, username:domain if different for display
                    138: #--- Use anywhere where the student names are listed
                    139: sub nameUserString {
                    140:     my ($type,$fullname,$uname,$udom) = @_;
                    141:     if ($type eq 'header') {
1.485     albertel  142: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        143:     } else {
1.398     albertel  144: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    145: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        146:     }
                    147: }
                    148: 
1.44      ng        149: #--- Get the partlist and the response type for a given problem. ---
1.773     raeburn   150: #--- Count responseIDs, essayresponse items, and dropbox items ---
1.623     www       151: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        152: sub response_type {
1.582     raeburn   153:     my ($symb,$response_error) = @_;
1.377     albertel  154: 
                    155:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   156:     unless (ref($navmap)) {
                    157:         if (ref($response_error)) {
                    158:             $$response_error = 1;
                    159:         }
                    160:         return;
                    161:     }
1.377     albertel  162:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   163:     unless (ref($res)) {
                    164:         $$response_error = 1;
                    165:         return;
                    166:     }
1.377     albertel  167:     my $partlist = $res->parts();
1.773     raeburn   168:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
1.392     albertel  169:     my %vPart = 
                    170: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  171:     my (%response_types,%handgrade);
                    172:     foreach my $part (@{ $partlist }) {
1.392     albertel  173: 	next if (%vPart && !exists($vPart{$part}));
                    174: 
1.377     albertel  175: 	my @types = $res->responseType($part);
                    176: 	my @ids = $res->responseIds($part);
                    177: 	for (my $i=0; $i < scalar(@ids); $i++) {
1.773     raeburn   178:             $numresp ++;
1.377     albertel  179: 	    $response_types{$part}{$ids[$i]} = $types[$i];
1.773     raeburn   180:             if ($types[$i] eq 'essay') {
                    181:                 $numessay ++;
                    182:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
                    183:                     $numdropbox ++;
                    184:                 }
                    185:             }
1.377     albertel  186: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    187: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    188: 				     '.handgrade',$symb);
1.41      ng        189: 	}
                    190:     }
1.773     raeburn   191:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
1.39      ng        192: }
                    193: 
1.375     albertel  194: sub flatten_responseType {
                    195:     my ($responseType) = @_;
                    196:     my @part_response_id =
                    197: 	map { 
                    198: 	    my $part = $_;
                    199: 	    map {
                    200: 		[$part,$_]
                    201: 		} sort(keys(%{ $responseType->{$part} }));
                    202: 	} sort(keys(%$responseType));
                    203:     return @part_response_id;
                    204: }
                    205: 
1.207     albertel  206: sub get_display_part {
1.324     albertel  207:     my ($partID,$symb)=@_;
1.207     albertel  208:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    209:     if (defined($display) and $display ne '') {
1.577     bisitz    210:         $display.= ' (<span class="LC_internal_info">'
                    211:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  212:     } else {
                    213: 	$display=$partID;
                    214:     }
                    215:     return $display;
                    216: }
1.269     raeburn   217: 
1.773     raeburn   218: #--- Show parts and response type
                    219: sub showResourceInfo {
                    220:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
                    221:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
                    222:         return '<br clear="all">';
                    223:     }
                    224:     my $coltitle = &mt('Problem Part Shown');
                    225:     if ($checkboxes) {
                    226:         $coltitle = &mt('Problem Part');
                    227:     } else {
                    228:         my $checkedparts = 0;
                    229:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                    230:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
                    231:                 $checkedparts ++;
                    232:             }
                    233:         }
                    234:         if ($checkedparts == scalar(@{$partlist})) {
                    235:             return '<br clear="all">';
                    236:         }
                    237:         if ($uploads) {
                    238:             $coltitle = &mt('Problem Part Selected');
                    239:         }
                    240:     }
                    241:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
                    242:     if ($checkboxes) {
                    243:         my $legend = &mt('Parts to display');
                    244:         if ($uploads) {
                    245:             $legend = &mt('Part(s) with dropbox');
                    246:         }
                    247:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
                    248:                    '<span class="LC_nobreak">'.
                    249:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
                    250:                    &mt('All parts').'</label>'.('&nbsp;'x2).
                    251:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
                    252:                    &mt('Selected parts').'</label></span>'.
                    253:                    '<div id="LC_partselector" style="display:none">';
                    254:     }
                    255:     $result .= &Apache::loncommon::start_data_table()
                    256:               .&Apache::loncommon::start_data_table_header_row();
                    257:     if ($checkboxes) {
                    258:         $result .= '<th>'.&mt('Display?').'</th>';
                    259:     }
                    260:     $result .= '<th>'.$coltitle.'</th>'
                    261:               .'<th>'.&mt('Res. ID').'</th>'
                    262:               .'<th>'.&mt('Type').'</th>'
                    263:               .&Apache::loncommon::end_data_table_header_row();
                    264:     my %partsseen;
                    265:     foreach my $partID (sort(keys(%$responseType))) {
                    266:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    267:             my $responsetype = $responseType->{$partID}->{$resID};
                    268:             if ($uploads) {
                    269:                 next unless ($responsetype eq 'essay');
                    270:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
                    271:             }
                    272:             my $display_part=&get_display_part($partID,$symb);
                    273:             if (exists($partsseen{$partID})) {
                    274:                 $result.=&Apache::loncommon::continue_data_table_row();
                    275:             } else {
                    276:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
                    277:                 $result.=&Apache::loncommon::start_data_table_row().
                    278:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
                    279:                 if ($checkboxes) {
                    280:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
                    281:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
                    282:                 } else {
                    283:                     $result.=$display_part.'</td>';
                    284:                 }
                    285:             }
                    286:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
                    287:                     .'<td>'.&mt($responsetype).'</td>'
                    288:                     .&Apache::loncommon::end_data_table_row();
                    289:         }
                    290:     }
                    291:     $result.=&Apache::loncommon::end_data_table();
                    292:     if ($checkboxes) {
                    293:         $result .= '</div></fieldset>';
                    294:     }
                    295:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
1.775     raeburn   296:     if (!keys(%partsseen)) {
                    297:         $result = '';
                    298:         if ($uploads) {
                    299:             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
                    300:                    '<p class="LC_info">'.
                    301:                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
                    302:                    '</p>';
                    303:         } else {
                    304:             return '<br clear="all" />';
                    305:         }
                    306:     }
1.773     raeburn   307:     return $result;
                    308: }
                    309: 
                    310: sub part_selector_js {
                    311:     my $js = <<"END";
                    312: function toggleParts(formname) {
                    313:     if (document.getElementById('LC_partselector')) {
                    314:         var index = '';
                    315:         if (document.forms.length) {
                    316:             for (var i=0; i<document.forms.length; i++) {
                    317:                 if (document.forms[i].name == formname) {
                    318:                     index = i;
                    319:                     break;
                    320:                 }
                    321:             }
                    322:         }
                    323:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
                    324:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
                    325:                 if (document.forms[index].elements['chooseparts'][i].checked) {
                    326:                    var val = document.forms[index].elements['chooseparts'][i].value;
                    327:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
                    328:                         document.getElementById('LC_partselector').style.display = 'block';
                    329:                     } else {
                    330:                         document.getElementById('LC_partselector').style.display = 'none';
                    331:                     }
                    332:                 }
                    333:             }
                    334:         }
                    335:     }
                    336: }
                    337: END
                    338:     return &Apache::lonhtmlcommon::scripttag($js);
                    339: }
                    340: 
1.434     albertel  341: sub reset_caches {
                    342:     &reset_analyze_cache();
                    343:     &reset_perm();
1.674     raeburn   344:     &reset_old_essays();
1.434     albertel  345: }
                    346: 
                    347: {
                    348:     my %analyze_cache;
1.557     raeburn   349:     my %analyze_cache_formkeys;
1.148     albertel  350: 
1.434     albertel  351:     sub reset_analyze_cache {
                    352: 	undef(%analyze_cache);
1.557     raeburn   353:         undef(%analyze_cache_formkeys);
1.434     albertel  354:     }
                    355: 
                    356:     sub get_analyze {
1.649     raeburn   357: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  358: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   359:         if ($type eq 'randomizetry') {
                    360:             if ($trial ne '') {
                    361:                 $key .= "\0".$trial;
                    362:             }
                    363:         }
1.557     raeburn   364: 	if (exists($analyze_cache{$key})) {
                    365:             my $getupdate = 0;
                    366:             if (ref($add_to_hash) eq 'HASH') {
                    367:                 foreach my $item (keys(%{$add_to_hash})) {
                    368:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    369:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    370:                             $getupdate = 1;
                    371:                             last;
                    372:                         }
                    373:                     } else {
                    374:                         $getupdate = 1;
                    375:                     }
                    376:                 }
                    377:             }
                    378:             if (!$getupdate) {
                    379:                 return $analyze_cache{$key};
                    380:             }
                    381:         }
1.434     albertel  382: 
                    383: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    384: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   385:         my %form = ('grade_target'      => 'analyze',
                    386:                     'grade_domain'      => $udom,
                    387:                     'grade_symb'        => $symb,
                    388:                     'grade_courseid'    =>  $env{'request.course.id'},
                    389:                     'grade_username'    => $uname,
                    390:                     'grade_noincrement' => $no_increment);
1.649     raeburn   391:         if ($bubbles_per_row ne '') {
                    392:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    393:         }
1.640     raeburn   394:         if ($type eq 'randomizetry') {
                    395:             $form{'grade_questiontype'} = $type;
                    396:             if ($rndseed ne '') {
                    397:                 $form{'grade_rndseed'} = $rndseed;
                    398:             }
                    399:         }
1.557     raeburn   400:         if (ref($add_to_hash)) {
                    401:             %form = (%form,%{$add_to_hash});
1.640     raeburn   402:         }
1.557     raeburn   403: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  404: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    405: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   406:         if (ref($add_to_hash) eq 'HASH') {
                    407:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    408:         } else {
                    409:             $analyze_cache_formkeys{$key} = {};
                    410:         }
1.434     albertel  411: 	return $analyze_cache{$key} = \%analyze;
                    412:     }
                    413: 
                    414:     sub get_order {
1.640     raeburn   415: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    416: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  417: 	return $analyze->{"$partid.$respid.shown"};
                    418:     }
                    419: 
                    420:     sub get_radiobutton_correct_foil {
1.640     raeburn   421: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    422: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    423:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   424:         if (ref($foils) eq 'ARRAY') {
                    425: 	    foreach my $foil (@{$foils}) {
                    426: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    427: 		    return $foil;
                    428: 	        }
1.434     albertel  429: 	    }
                    430: 	}
                    431:     }
1.554     raeburn   432: 
                    433:     sub scantron_partids_tograde {
1.741     raeburn   434:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   435:         my (%analysis,@parts);
                    436:         if (ref($resource)) {
                    437:             my $symb = $resource->symb();
1.557     raeburn   438:             my $add_to_form;
                    439:             if ($check_for_randomlist) {
                    440:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    441:             }
1.741     raeburn   442:             if ($scancode) {
                    443:                 if (ref($add_to_form) eq 'HASH') {
                    444:                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    445:                 } else {
                    446:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    447:                 }
                    448:             }
1.767     raeburn   449:             my $analyze =
1.649     raeburn   450:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    451:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   452:             if (ref($analyze) eq 'HASH') {
                    453:                 %analysis = %{$analyze};
                    454:             }
                    455:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    456:                 foreach my $part (@{$analysis{'parts'}}) {
                    457:                     my ($id,$respid) = split(/\./,$part);
                    458:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    459:                         push(@parts,$part);
                    460:                     }
                    461:                 }
                    462:             }
                    463:         }
                    464:         return (\%analysis,\@parts);
                    465:     }
                    466: 
1.148     albertel  467: }
1.434     albertel  468: 
1.118     ng        469: #--- Clean response type for display
1.335     albertel  470: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    471: #        response types only.
1.118     ng        472: sub cleanRecord {
1.336     albertel  473:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   474: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  475:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  476:     if ($response =~ /^(option|rank)$/) {
                    477: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     478:         my @answer = %answer;
1.767     raeburn   479:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  480: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    481: 	my ($toprow,$bottomrow);
                    482: 	foreach my $foil (@$order) {
                    483: 	    if ($grading{$foil} == 1) {
                    484: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    485: 	    } else {
                    486: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    487: 	    }
1.398     albertel  488: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  489: 	}
                    490: 	return '<blockquote><table border="1">'.
1.466     albertel  491: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    492: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   493: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  494:     } elsif ($response eq 'match') {
                    495: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     496:         my @answer = %answer;
1.767     raeburn   497:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  498: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    499: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    500: 	my ($toprow,$middlerow,$bottomrow);
                    501: 	foreach my $foil (@$order) {
                    502: 	    my $item=shift(@items);
                    503: 	    if ($grading{$foil} == 1) {
                    504: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  505: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  506: 	    } else {
                    507: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  508: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  509: 	    }
1.398     albertel  510: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        511: 	}
1.126     ng        512: 	return '<blockquote><table border="1">'.
1.466     albertel  513: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    514: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  515: 	    $middlerow.'</tr>'.
1.466     albertel  516: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   517: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  518:     } elsif ($response eq 'radiobutton') {
                    519: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     520:         my @answer = %answer;
                    521:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  522: 	my ($toprow,$bottomrow);
1.434     albertel  523: 	my $correct = 
1.640     raeburn   524: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  525: 	foreach my $foil (@$order) {
1.148     albertel  526: 	    if (exists($answer{$foil})) {
1.434     albertel  527: 		if ($foil eq $correct) {
1.466     albertel  528: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  529: 		} else {
1.466     albertel  530: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  531: 		}
                    532: 	    } else {
1.466     albertel  533: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  534: 	    }
1.398     albertel  535: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  536: 	}
                    537: 	return '<blockquote><table border="1">'.
1.466     albertel  538: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    539: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   540: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  541:     } elsif ($response eq 'essay') {
1.257     albertel  542: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        543: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  544: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    545: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        546: 
1.257     albertel  547: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    548: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    549: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    550: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    551: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    552: 	    $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        553: 	}
1.751     raeburn   554:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
1.730     kruse     555: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  556:     } elsif ( $response eq 'organic') {
1.721     bisitz    557:         my $result=&mt('Smile representation: [_1]',
                    558:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  559: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    560: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    561: 	return $result;
1.335     albertel  562:     } elsif ( $response eq 'Task') {
                    563: 	if ( $answer eq 'SUBMITTED') {
                    564: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  565: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  566: 	    return $result;
                    567: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    568: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    569: 			       keys(%{$record}));
                    570: 	    return join('<br />',($version,@matches));
                    571: 			       
                    572: 			       
                    573: 	} else {
                    574: 	    my $result =
                    575: 		'<p>'
                    576: 		.&mt('Overall result: [_1]',
                    577: 		     $record->{$version."resource.$respid.$partid.status"})
                    578: 		.'</p>';
                    579: 	    
                    580: 	    $result .= '<ul>';
                    581: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    582: 			     keys(%{$record}));
                    583: 	    foreach my $grade (sort(@grade)) {
                    584: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    585: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    586: 				     $dim, $record->{$grade}).
                    587: 			  '</li>';
                    588: 	    }
                    589: 	    $result.='</ul>';
                    590: 	    return $result;
                    591: 	}
1.716     bisitz    592:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    593:         # Respect multiple input fields, see Bug #5409
1.440     albertel  594: 	$answer = 
                    595: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    596: 							      $answer);
1.720     kruse     597: 	return $answer;
1.122     ng        598:     }
1.720     kruse     599:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        600: }
                    601: 
                    602: #-- A couple of common js functions
                    603: sub commonJSfunctions {
                    604:     my $request = shift;
1.597     wenzelju  605:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        606:     function radioSelection(radioButton) {
                    607: 	var selection=null;
                    608: 	if (radioButton.length > 1) {
                    609: 	    for (var i=0; i<radioButton.length; i++) {
                    610: 		if (radioButton[i].checked) {
                    611: 		    return radioButton[i].value;
                    612: 		}
                    613: 	    }
                    614: 	} else {
                    615: 	    if (radioButton.checked) return radioButton.value;
                    616: 	}
                    617: 	return selection;
                    618:     }
                    619: 
                    620:     function pullDownSelection(selectOne) {
                    621: 	var selection="";
                    622: 	if (selectOne.length > 1) {
                    623: 	    for (var i=0; i<selectOne.length; i++) {
                    624: 		if (selectOne[i].selected) {
                    625: 		    return selectOne[i].value;
                    626: 		}
                    627: 	    }
                    628: 	} else {
1.138     albertel  629:             // only one value it must be the selected one
                    630: 	    return selectOne.value;
1.118     ng        631: 	}
                    632:     }
                    633: COMMONJSFUNCTIONS
                    634: }
                    635: 
1.44      ng        636: #--- Dumps the class list with usernames,list of sections,
                    637: #--- section, ids and fullnames for each user.
                    638: sub getclasslist {
1.750     raeburn   639:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  640:     my @getsec;
1.450     banghart  641:     my @getgroup;
1.442     banghart  642:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  643:     if (!ref($getsec)) {
                    644: 	if ($getsec ne '' && $getsec ne 'all') {
                    645: 	    @getsec=($getsec);
                    646: 	}
                    647:     } else {
                    648: 	@getsec=@{$getsec};
                    649:     }
                    650:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  651:     if (!ref($getgroup)) {
                    652: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    653: 	    @getgroup=($getgroup);
                    654: 	}
                    655:     } else {
                    656: 	@getgroup=@{$getgroup};
                    657:     }
                    658:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  659: 
1.449     banghart  660:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  661:     # Bail out if we were unable to get the classlist
1.56      matthew   662:     return if (! defined($classlist));
1.449     banghart  663:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   664:     #
                    665:     my %sections;
                    666:     my %fullnames;
1.750     raeburn   667:     my ($cdom,$cnum,$partlist);
                    668:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    669:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    670:         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    671:         my $res_error;
1.773     raeburn   672:         ($partlist) = &response_type($symb,\$res_error);
1.750     raeburn   673:     }
1.205     matthew   674:     foreach my $student (keys(%$classlist)) {
                    675:         my $end      = 
                    676:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    677:         my $start    = 
                    678:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    679:         my $id       = 
                    680:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    681:         my $section  = 
                    682:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    683:         my $fullname = 
                    684:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    685:         my $status   = 
                    686:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  687:         my $group   = 
                    688:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        689: 	# filter students according to status selected
1.750     raeburn   690: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  691: 	    if (!($stu_status =~ $status)) {
1.450     banghart  692: 		delete($classlist->{$student});
1.76      ng        693: 		next;
                    694: 	    }
                    695: 	}
1.450     banghart  696: 	# filter students according to groups selected
1.453     banghart  697: 	my @stu_groups = split(/,/,$group);
1.450     banghart  698: 	if (@getgroup) {
                    699: 	    my $exclude = 1;
1.454     banghart  700: 	    foreach my $grp (@getgroup) {
                    701: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  702: 	            if ($stu_group eq $grp) {
                    703: 	                $exclude = 0;
                    704:     	            } 
1.450     banghart  705: 	        }
1.453     banghart  706:     	        if (($grp eq 'none') && !$group) {
1.750     raeburn   707:         	    $exclude = 0;
1.453     banghart  708:         	}
1.450     banghart  709: 	    }
                    710: 	    if ($exclude) {
                    711: 	        delete($classlist->{$student});
1.750     raeburn   712: 		next;
1.450     banghart  713: 	    }
                    714: 	}
1.750     raeburn   715:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    716:             my $udom =
                    717:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    718:             my $uname =
                    719:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    720:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    721:                 if ($submitonly eq 'queued') {
                    722:                     my %queue_status =
                    723:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    724:                                                                 $udom,$uname);
                    725:                     if (!defined($queue_status{'gradingqueue'})) {
                    726:                         delete($classlist->{$student});
                    727:                         next;
                    728:                     }
                    729:                 } else {
                    730:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    731:                     my $submitted = 0;
                    732:                     my $graded = 0;
                    733:                     my $incorrect = 0;
                    734:                     foreach (keys(%status)) {
                    735:                         $submitted = 1 if ($status{$_} ne 'nothing');
                    736:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    737:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    738: 
                    739:                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    740:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    741:                             $submitted = 0;
                    742:                         }
                    743:                     }
                    744:                     if (!$submitted && ($submitonly eq 'yes' ||
                    745:                                         $submitonly eq 'incorrect' ||
                    746:                                         $submitonly eq 'graded')) {
                    747:                         delete($classlist->{$student});
                    748:                         next;
                    749:                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    750:                         delete($classlist->{$student});
                    751:                         next;
                    752:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    753:                         delete($classlist->{$student});
                    754:                         next;
                    755:                     }
                    756:                 }
                    757:             }
                    758:         }
1.205     matthew   759: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  760: 	if (&canview($section)) {
1.291     albertel  761: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  762: 		$sections{$section}++;
1.450     banghart  763: 		if ($classlist->{$student}) {
                    764: 		    $fullnames{$student}=$fullname;
                    765: 		}
1.103     albertel  766: 	    } else {
1.205     matthew   767: 		delete($classlist->{$student});
1.103     albertel  768: 	    }
                    769: 	} else {
1.205     matthew   770: 	    delete($classlist->{$student});
1.103     albertel  771: 	}
1.44      ng        772:     }
1.56      matthew   773:     my @sections = sort(keys(%sections));
                    774:     return ($classlist,\@sections,\%fullnames);
1.44      ng        775: }
                    776: 
1.103     albertel  777: sub canmodify {
                    778:     my ($sec)=@_;
                    779:     if ($perm{'mgr'}) {
                    780: 	if (!defined($perm{'mgr_section'})) {
                    781: 	    # can modify whole class
                    782: 	    return 1;
                    783: 	} else {
                    784: 	    if ($sec eq $perm{'mgr_section'}) {
                    785: 		#can modify the requested section
                    786: 		return 1;
                    787: 	    } else {
1.763     raeburn   788: 		# can't modify the requested section
1.103     albertel  789: 		return 0;
                    790: 	    }
                    791: 	}
                    792:     }
                    793:     #can't modify
                    794:     return 0;
                    795: }
                    796: 
                    797: sub canview {
                    798:     my ($sec)=@_;
                    799:     if ($perm{'vgr'}) {
                    800: 	if (!defined($perm{'vgr_section'})) {
1.763     raeburn   801: 	    # can view whole class
1.103     albertel  802: 	    return 1;
                    803: 	} else {
                    804: 	    if ($sec eq $perm{'vgr_section'}) {
1.763     raeburn   805: 		#can view the requested section
1.103     albertel  806: 		return 1;
                    807: 	    } else {
1.763     raeburn   808: 		# can't view the requested section
1.103     albertel  809: 		return 0;
                    810: 	    }
                    811: 	}
                    812:     }
1.763     raeburn   813:     #can't view
1.103     albertel  814:     return 0;
                    815: }
                    816: 
1.44      ng        817: #--- Retrieve the grade status of a student for all the parts
                    818: sub student_gradeStatus {
1.324     albertel  819:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  820:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        821:     my %partstatus = ();
                    822:     foreach (@$partlist) {
1.128     ng        823: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        824: 	$status              = 'nothing' if ($status eq '');
                    825: 	$partstatus{$_}      = $status;
                    826: 	my $subkey           = "resource.$_.submitted_by";
                    827: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    828:     }
                    829:     return %partstatus;
                    830: }
                    831: 
1.45      ng        832: # hidden form and javascript that calls the form
                    833: # Use by verifyscript and viewgrades
                    834: # Shows a student's view of problem and submission
                    835: sub jscriptNform {
1.324     albertel  836:     my ($symb) = @_;
1.442     banghart  837:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  838:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        839: 	'    function viewOneStudent(user,domain) {'."\n".
                    840: 	'	document.onestudent.student.value = user;'."\n".
                    841: 	'	document.onestudent.userdom.value = domain;'."\n".
                    842: 	'	document.onestudent.submit();'."\n".
                    843: 	'    }'."\n".
1.597     wenzelju  844: 	"\n");
1.45      ng        845:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  846: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  847: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        848: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    849: 	'<input type="hidden" name="student" value="" />'."\n".
                    850: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    851: 	'</form>'."\n";
                    852:     return $jscript;
                    853: }
1.39      ng        854: 
1.447     foxr      855: 
                    856: 
1.315     bowersj2  857: # Given the score (as a number [0-1] and the weight) what is the final
                    858: # point value? This function will round to the nearest tenth, third,
                    859: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  860: sub compute_points {
1.315     bowersj2  861:     my ($score, $weight) = @_;
                    862:     
                    863:     my $tolerance = .00001;
                    864:     my $points = $score * $weight;
                    865: 
                    866:     # Check for nearness to 1/x.
                    867:     my $check_for_nearness = sub {
                    868:         my ($factor) = @_;
                    869:         my $num = ($points * $factor) + $tolerance;
                    870:         my $floored_num = floor($num);
1.316     albertel  871:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  872:             return $floored_num / $factor;
                    873:         }
                    874:         return $points;
                    875:     };
                    876: 
                    877:     $points = $check_for_nearness->(10);
                    878:     $points = $check_for_nearness->(3);
                    879:     $points = $check_for_nearness->(4);
                    880:     
                    881:     return $points;
                    882: }
                    883: 
1.44      ng        884: #------------------ End of general use routines --------------------
1.87      www       885: 
                    886: #
                    887: # Find most similar essay
                    888: #
                    889: 
                    890: sub most_similar {
1.674     raeburn   891:     my ($uname,$udom,$symb,$uessay)=@_;
                    892: 
                    893:     unless ($symb) { return ''; }
                    894: 
                    895:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       896: 
                    897: # ignore spaces and punctuation
                    898: 
                    899:     $uessay=~s/\W+/ /gs;
                    900: 
1.282     www       901: # ignore empty submissions (occuring when only files are sent)
                    902: 
1.598     www       903:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       904: 
1.87      www       905: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       906:     my $limit=0.6;
1.87      www       907:     my $sname='';
                    908:     my $sdom='';
                    909:     my $scrsid='';
                    910:     my $sessay='';
                    911: # go through all essays ...
1.674     raeburn   912:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  913: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       914: # ... except the same student
1.426     albertel  915:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   916: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  917: 	$tessay=~s/\W+/ /gs;
1.87      www       918: # String similarity gives up if not even limit
1.426     albertel  919: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       920: # Found one
1.426     albertel  921: 	if ($tsimilar>$limit) {
                    922: 	    $limit=$tsimilar;
                    923: 	    $sname=$tname;
                    924: 	    $sdom=$tdom;
                    925: 	    $scrsid=$tcrsid;
1.674     raeburn   926: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  927: 	}
1.87      www       928:     }
1.88      www       929:     if ($limit>0.6) {
1.87      www       930:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    931:     } else {
                    932:        return ('','','','',0);
                    933:     }
                    934: }
                    935: 
1.44      ng        936: #-------------------------------------------------------------------
                    937: 
                    938: #------------------------------------ Receipt Verification Routines
1.45      ng        939: #
1.602     www       940: 
                    941: sub initialverifyreceipt {
1.608     www       942:    my ($request,$symb) = @_;
1.602     www       943:    &commonJSfunctions($request);
1.694     bisitz    944:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       945:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    946:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       947:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    948:         '<input type="hidden" name="command" value="verify" />'.
                    949:         "</form>\n";
1.602     www       950: }
                    951: 
1.44      ng        952: #--- Check whether a receipt number is valid.---
                    953: sub verifyreceipt {
1.766     raeburn   954:     my ($request,$symb) = @_;
1.44      ng        955: 
1.257     albertel  956:     my $courseid = $env{'request.course.id'};
1.184     www       957:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  958: 	$env{'form.receipt'};
1.44      ng        959:     $receipt     =~ s/[^\-\d]//g;
                    960: 
1.766     raeburn   961:     my $title =
1.487     albertel  962: 	'<h3><span class="LC_info">'.
1.605     www       963: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    964: 	'</span></h3>'."\n";
1.44      ng        965: 
                    966:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   967:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  968:     
                    969:     my $receiptparts=0;
1.390     albertel  970:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    971: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  972:     my $parts=['0'];
1.582     raeburn   973:     if ($receiptparts) {
                    974:         my $res_error; 
                    975:         ($parts)=&response_type($symb,\$res_error);
                    976:         if ($res_error) {
                    977:             return &navmap_errormsg();
                    978:         } 
                    979:     }
1.486     albertel  980:     
                    981:     my $header = 
                    982: 	&Apache::loncommon::start_data_table().
                    983: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  984: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    985: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    986: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  987:     if ($receiptparts) {
1.487     albertel  988: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  989:     }
                    990:     $header.=
                    991: 	&Apache::loncommon::end_data_table_header_row();
                    992: 
1.294     albertel  993:     foreach (sort 
                    994: 	     {
                    995: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    996: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    997: 		 }
                    998: 		 return $a cmp $b;
                    999: 	     } (keys(%$fullname))) {
1.44      ng       1000: 	my ($uname,$udom)=split(/\:/);
1.177     albertel 1001: 	foreach my $part (@$parts) {
                   1002: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel 1003: 		$contents.=
                   1004: 		    &Apache::loncommon::start_data_table_row().
                   1005: 		    '<td>&nbsp;'."\n".
1.177     albertel 1006: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 1007: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel 1008: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                   1009: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                   1010: 		if ($receiptparts) {
                   1011: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                   1012: 		}
1.486     albertel 1013: 		$contents.= 
                   1014: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel 1015: 		
                   1016: 		$matches++;
                   1017: 	    }
1.44      ng       1018: 	}
                   1019:     }
                   1020:     if ($matches == 0) {
1.584     bisitz   1021:         $string = $title
                   1022:                  .'<p class="LC_warning">'
                   1023:                  .&mt('No match found for the above receipt number.')
                   1024:                  .'</p>';
1.44      ng       1025:     } else {
1.324     albertel 1026: 	$string = &jscriptNform($symb).$title.
1.487     albertel 1027: 	    '<p>'.
1.584     bisitz   1028: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel 1029: 	    '</p>'.
1.486     albertel 1030: 	    $header.
                   1031: 	    $contents.
                   1032: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng       1033:     }
1.614     www      1034:     return $string;
1.44      ng       1035: }
                   1036: 
                   1037: #--- This is called by a number of programs.
                   1038: #--- Called from the Grading Menu - View/Grade an individual student
                   1039: #--- Also called directly when one clicks on the subm button 
                   1040: #    on the problem page.
1.30      ng       1041: sub listStudents {
1.773     raeburn  1042:     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1043: 
1.747     raeburn  1044:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1045:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1046:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1047:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1048:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www      1049:     unless ($submitonly) {
1.766     raeburn  1050:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www      1051:     }
1.49      albertel 1052: 
1.632     www      1053:     my $result='';
1.623     www      1054:     my $res_error;
1.773     raeburn  1055:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   1056: 
                   1057:     my $table;
                   1058:     if (ref($partlist) eq 'ARRAY') {
                   1059:         if (scalar(@$partlist) > 1 ) {
                   1060:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1061:         } elsif ($divforres) {
                   1062:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1063:         } else {
                   1064:             $table = '<br clear="all" />';
                   1065:         }
                   1066:     }
1.49      albertel 1067: 
1.736     damieng  1068:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn  1069: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   1070: 		'single'   => 'Please select the student before clicking on the Next button.',
                   1071: 	     );
1.736     damieng  1072:     &js_escape(\%js_lt);
1.597     wenzelju 1073:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1074:     function checkSelect(checkBox) {
                   1075: 	var ctr=0;
                   1076: 	var sense="";
                   1077: 	if (checkBox.length > 1) {
                   1078: 	    for (var i=0; i<checkBox.length; i++) {
                   1079: 		if (checkBox[i].checked) {
                   1080: 		    ctr++;
                   1081: 		}
                   1082: 	    }
1.736     damieng  1083: 	    sense = '$js_lt{'multiple'}';
1.110     ng       1084: 	} else {
                   1085: 	    if (checkBox.checked) {
                   1086: 		ctr = 1;
                   1087: 	    }
1.736     damieng  1088: 	    sense = '$js_lt{'single'}';
1.110     ng       1089: 	}
                   1090: 	if (ctr == 0) {
1.485     albertel 1091: 	    alert(sense);
1.110     ng       1092: 	    return false;
                   1093: 	}
                   1094: 	document.gradesub.submit();
                   1095:     }
                   1096: 
                   1097:     function reLoadList(formname) {
1.112     ng       1098: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1099: 	formname.command.value = 'submission';
                   1100: 	formname.submit();
                   1101:     }
1.45      ng       1102: LISTJAVASCRIPT
                   1103: 
1.118     ng       1104:     &commonJSfunctions($request);
1.41      ng       1105:     $request->print($result);
1.39      ng       1106: 
1.154     albertel 1107:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.773     raeburn  1108: 	"\n".$table;
                   1109: 
1.561     bisitz   1110:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn  1111:     unless ($is_tool) {
                   1112:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1113:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1114:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1115:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1116:                       .&Apache::lonhtmlcommon::row_closure();
                   1117:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1118:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1119:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1120:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1121:                       .&Apache::lonhtmlcommon::row_closure();
                   1122:     }
1.485     albertel 1123: 
1.442     banghart 1124:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1125:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1126:     $env{'form.Status'} = $saveStatus;
1.745     raeburn  1127:     my %optiontext;
                   1128:     if ($is_tool) {
                   1129:         %optiontext = &Apache::lonlocal::texthash (
                   1130:                           lastonly => 'last transaction',
                   1131:                           last     => 'last transaction with details',
                   1132:                           datesub  => 'all transactions',
                   1133:                           all      => 'all transactions with details',
                   1134:                       );
                   1135:     } else {
                   1136:         %optiontext = &Apache::lonlocal::texthash (
                   1137:                           lastonly => 'last submission',
                   1138:                           last     => 'last submission with details',
                   1139:                           datesub  => 'all submissions',
                   1140:                           all      => 'all submissions with details',
                   1141:                       );
                   1142:     }
1.773     raeburn  1143:     my $submission_options =
1.592     bisitz   1144:         '<span class="LC_nobreak">'.
1.624     www      1145:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  1146:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1147:         '<span class="LC_nobreak">'.
                   1148:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  1149:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1150:         '<span class="LC_nobreak">'.
1.628     www      1151:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  1152:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1153:         '<span class="LC_nobreak">'.
                   1154:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  1155:         $optiontext{'all'}.'</label></span>';
                   1156:     my $viewtitle;
                   1157:     if ($is_tool) {
                   1158:         $viewtitle = &mt('View Transactions');
                   1159:     } else {
                   1160:         $viewtitle = &mt('View Submissions');
                   1161:     }
1.773     raeburn  1162:     my ($compmsg,$nocompmsg);
                   1163:     $nocompmsg = ' checked="checked"';
                   1164:     if ($numessay) {
                   1165:         $compmsg = $nocompmsg;
                   1166:         $nocompmsg = '';
                   1167:     }
1.745     raeburn  1168:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.780     raeburn  1169:                   .$submission_options;
                   1170: # Check if any gradable
                   1171:     my $showmore;
                   1172:     if ($perm{'mgr'}) {
                   1173:         my @sections;
                   1174:         if ($env{'request.course.sec'} ne '') {
                   1175:             @sections = ($env{'request.course.sec'});
1.783     raeburn  1176:         } elsif ($env{'form.section'} eq '') {
                   1177:             @sections = ('all');
1.780     raeburn  1178:         } else {
                   1179:             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1180:         }
                   1181:         if (grep(/^all$/,@sections)) {
                   1182:             $showmore = 1;
                   1183:         } else {
                   1184:             foreach my $sec (@sections) {
                   1185:                 if (&canmodify($sec)) {
                   1186:                     $showmore = 1;
                   1187:                     last;
                   1188:                 }
                   1189:             }
                   1190:         }
                   1191:     }
                   1192: 
                   1193:     if ($showmore) {
                   1194:         $gradeTable .=
                   1195:                    &Apache::lonhtmlcommon::row_closure()
1.773     raeburn  1196:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   1197:                   .'<span class="LC_nobreak">'
                   1198:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   1199:                   .&mt('No').('&nbsp;'x2).'</label>'
                   1200:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   1201:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1202:                   .&Apache::lonhtmlcommon::row_closure();
                   1203: 
1.780     raeburn  1204:         $gradeTable .= 
                   1205:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   1206:                   .'<select name="increment">'
                   1207:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1208:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1209:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1210:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773     raeburn  1211:                   .'</select>';
1.780     raeburn  1212:     }
1.485     albertel 1213:     $gradeTable .= 
1.432     banghart 1214:         &build_section_inputs().
1.45      ng       1215: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1216: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1217: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      1218:     if (exists($env{'form.Status'})) {
1.784     raeburn  1219: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng       1220:     } else {
1.773     raeburn  1221:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1222:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1223:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773     raeburn  1224:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1225:     }
1.773     raeburn  1226:     if ($numessay) {
                   1227:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1228:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1229:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  1230:     }
1.773     raeburn  1231:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
                   1232:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  1233:     my $regrademsg;
                   1234:     if ($is_tool) {
                   1235:         $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.");
                   1236:     } else {
                   1237:         $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.");
                   1238:     }
1.561     bisitz   1239:     $gradeTable .= '<p>'
1.745     raeburn  1240:                   .$regrademsg."\n"
1.561     bisitz   1241:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1242:                   .'</p>';
1.249     albertel 1243: 
                   1244: # checkall buttons
                   1245:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1246:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1247:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1248:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1249:     $gradeTable.=&check_buttons();
1.450     banghart 1250:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1251:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1252: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1253:     my $loop = 0;
                   1254:     while ($loop < 2) {
1.485     albertel 1255: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1256: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1257: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1258: 	    foreach my $part (sort(@$partlist)) {
                   1259: 		my $display_part=
                   1260: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1261: 		$gradeTable.=
                   1262: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1263: 	    }
1.301     albertel 1264: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1265: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1266: 	}
                   1267: 	$loop++;
1.126     ng       1268: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1269:     }
1.474     albertel 1270:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1271: 
1.45      ng       1272:     my $ctr = 0;
1.294     albertel 1273:     foreach my $student (sort 
                   1274: 			 {
                   1275: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1276: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1277: 			     }
                   1278: 			     return $a cmp $b;
                   1279: 			 }
                   1280: 			 (keys(%$fullname))) {
1.41      ng       1281: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1282: 
1.110     ng       1283: 	my %status = ();
1.301     albertel 1284: 
                   1285: 	if ($submitonly eq 'queued') {
                   1286: 	    my %queue_status = 
                   1287: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1288: 							$udom,$uname);
                   1289: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1290: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1291: 	}
                   1292: 
1.618     www      1293: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1294: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1295: 	    my $submitted = 0;
1.164     albertel 1296: 	    my $graded = 0;
1.248     albertel 1297: 	    my $incorrect = 0;
1.110     ng       1298: 	    foreach (keys(%status)) {
1.145     albertel 1299: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1300: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1301: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1302: 		
1.110     ng       1303: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1304: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1305: 		    $submitted = 0;
1.150     albertel 1306: 		    my ($part)=split(/\./,$partid);
1.110     ng       1307: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1308: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1309: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1310: 		}
1.41      ng       1311: 	    }
1.248     albertel 1312: 	    
1.156     albertel 1313: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1314: 				     $submitonly eq 'incorrect' ||
                   1315: 				     $submitonly eq 'graded'));
1.248     albertel 1316: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1317: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1318: 	}
1.34      ng       1319: 
1.45      ng       1320: 	$ctr++;
1.249     albertel 1321: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1322:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1323: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1324: 	    if ($ctr%2 ==1) {
                   1325: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1326: 	    }
1.126     ng       1327: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1328:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1329:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1330: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1331: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1332: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1333: 
1.618     www      1334: 	    if ($submitonly ne 'all') {
1.524     raeburn  1335: 		foreach (sort(keys(%status))) {
1.485     albertel 1336: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1337: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1338: 		}
1.41      ng       1339: 	    }
1.126     ng       1340: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1341: 	    if ($ctr%2 ==0) {
                   1342: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1343: 	    }
1.41      ng       1344: 	}
                   1345:     }
1.110     ng       1346:     if ($ctr%2 ==1) {
1.126     ng       1347: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1348: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1349: 		foreach (@$partlist) {
                   1350: 		    $gradeTable.='<td>&nbsp;</td>';
                   1351: 		}
1.301     albertel 1352: 	    } elsif ($submitonly eq 'queued') {
                   1353: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1354: 	    }
1.474     albertel 1355: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1356:     }
                   1357: 
1.474     albertel 1358:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1359:         '<input type="button" '.
                   1360:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1361:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1362:     if ($ctr == 0) {
1.96      albertel 1363: 	my $num_students=(scalar(keys(%$fullname)));
                   1364: 	if ($num_students eq 0) {
1.485     albertel 1365: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1366: 	} else {
1.171     albertel 1367: 	    my $submissions='submissions';
                   1368: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1369: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1370: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1371: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1372: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1373: 		    $num_students).
                   1374: 		'</span><br />';
1.96      albertel 1375: 	}
1.46      ng       1376:     } elsif ($ctr == 1) {
1.474     albertel 1377: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1378:     }
                   1379:     $request->print($gradeTable);
1.44      ng       1380:     return '';
1.10      ng       1381: }
                   1382: 
1.44      ng       1383: #---- Called from the listStudents routine
1.249     albertel 1384: 
                   1385: sub check_script {
1.766     raeburn  1386:     my ($form,$type) = @_;
                   1387:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1388:     function checkall() {
                   1389:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1390:             ele = document.forms.'.$form.'.elements[i];
                   1391:             if (ele.name == "'.$type.'") {
                   1392:             document.forms.'.$form.'.elements[i].checked=true;
                   1393:                                        }
                   1394:         }
                   1395:     }
                   1396: 
                   1397:     function checksec() {
                   1398:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1399:             ele = document.forms.'.$form.'.elements[i];
                   1400:            string = document.forms.'.$form.'.chksec.value;
                   1401:            if
                   1402:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1403:               document.forms.'.$form.'.elements[i].checked=true;
                   1404:             }
                   1405:         }
                   1406:     }
                   1407: 
                   1408: 
                   1409:     function uncheckall() {
                   1410:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1411:             ele = document.forms.'.$form.'.elements[i];
                   1412:             if (ele.name == "'.$type.'") {
                   1413:             document.forms.'.$form.'.elements[i].checked=false;
                   1414:                                        }
                   1415:         }
                   1416:     }
                   1417: 
1.597     wenzelju 1418: '."\n");
1.249     albertel 1419:     return $chkallscript;
                   1420: }
                   1421: 
                   1422: sub check_buttons {
1.485     albertel 1423:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1424:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1425:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1426:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1427:     return $buttons;
                   1428: }
                   1429: 
1.44      ng       1430: #     Displays the submissions for one student or a group of students
1.34      ng       1431: sub processGroup {
1.766     raeburn  1432:     my ($request,$symb) = @_;
1.41      ng       1433:     my $ctr        = 0;
1.155     albertel 1434:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1435:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1436: 
1.396     banghart 1437:     foreach my $student (@stuchecked) {
                   1438: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1439: 	$env{'form.student'}        = $uname;
                   1440: 	$env{'form.userdom'}        = $udom;
                   1441: 	$env{'form.fullname'}       = $fullname;
1.619     www      1442: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1443: 	$ctr++;
                   1444:     }
                   1445:     return '';
1.35      ng       1446: }
1.34      ng       1447: 
1.44      ng       1448: #------------------------------------------------------------------------------------
                   1449: #
                   1450: #-------------------------- Next few routines handles grading by student, essentially
                   1451: #                           handles essay response type problem/part
                   1452: #
                   1453: #--- Javascript to handle the submission page functionality ---
                   1454: sub sub_page_js {
                   1455:     my $request = shift;
1.736     damieng  1456:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1457:     &js_escape(\$alertmsg);
1.597     wenzelju 1458:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1459:     function updateRadio(formname,id,weight) {
1.125     ng       1460: 	var gradeBox = formname["GD_BOX"+id];
                   1461: 	var radioButton = formname["RADVAL"+id];
                   1462: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1463: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1464: 	gradeBox.value = pts;
                   1465: 	var resetbox = false;
                   1466: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1467: 	    alert("$alertmsg"+pts);
1.71      ng       1468: 	    for (var i=0; i<radioButton.length; i++) {
                   1469: 		if (radioButton[i].checked) {
                   1470: 		    gradeBox.value = i;
                   1471: 		    resetbox = true;
                   1472: 		}
                   1473: 	    }
                   1474: 	    if (!resetbox) {
                   1475: 		formtextbox.value = "";
                   1476: 	    }
                   1477: 	    return;
1.44      ng       1478: 	}
1.71      ng       1479: 
                   1480: 	if (pts > weight) {
                   1481: 	    var resp = confirm("You entered a value ("+pts+
                   1482: 			       ") greater than the weight for the part. Accept?");
                   1483: 	    if (resp == false) {
1.125     ng       1484: 		gradeBox.value = oldpts;
1.71      ng       1485: 		return;
                   1486: 	    }
1.44      ng       1487: 	}
1.13      albertel 1488: 
1.71      ng       1489: 	for (var i=0; i<radioButton.length; i++) {
                   1490: 	    radioButton[i].checked=false;
                   1491: 	    if (pts == i && pts != "") {
                   1492: 		radioButton[i].checked=true;
                   1493: 	    }
                   1494: 	}
                   1495: 	updateSelect(formname,id);
1.125     ng       1496: 	formname["stores"+id].value = "0";
1.41      ng       1497:     }
1.5       albertel 1498: 
1.72      ng       1499:     function writeBox(formname,id,pts) {
1.125     ng       1500: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1501: 	if (checkSolved(formname,id) == 'update') {
                   1502: 	    gradeBox.value = pts;
                   1503: 	} else {
1.125     ng       1504: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1505: 	    gradeBox.value = oldpts;
1.125     ng       1506: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1507: 	    for (var i=0; i<radioButton.length; i++) {
                   1508: 		radioButton[i].checked=false;
1.72      ng       1509: 		if (i == oldpts) {
1.71      ng       1510: 		    radioButton[i].checked=true;
                   1511: 		}
                   1512: 	    }
1.41      ng       1513: 	}
1.125     ng       1514: 	formname["stores"+id].value = "0";
1.71      ng       1515: 	updateSelect(formname,id);
                   1516: 	return;
1.41      ng       1517:     }
1.44      ng       1518: 
1.71      ng       1519:     function clearRadBox(formname,id) {
                   1520: 	if (checkSolved(formname,id) == 'noupdate') {
                   1521: 	    updateSelect(formname,id);
                   1522: 	    return;
                   1523: 	}
1.125     ng       1524: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1525: 	for (var i=0; i<gradeSelect.length; i++) {
                   1526: 	    if (gradeSelect[i].selected) {
                   1527: 		var selectx=i;
                   1528: 	    }
                   1529: 	}
1.125     ng       1530: 	var stores = formname["stores"+id];
1.71      ng       1531: 	if (selectx == stores.value) { return };
1.125     ng       1532: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1533: 	gradeBox.value = "";
1.125     ng       1534: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1535: 	for (var i=0; i<radioButton.length; i++) {
                   1536: 	    radioButton[i].checked=false;
                   1537: 	}
                   1538: 	stores.value = selectx;
                   1539:     }
1.5       albertel 1540: 
1.71      ng       1541:     function checkSolved(formname,id) {
1.125     ng       1542: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1543: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1544: 	    if (!reply) {return "noupdate";}
1.120     ng       1545: 	    formname.overRideScore.value = 'yes';
1.41      ng       1546: 	}
1.71      ng       1547: 	return "update";
1.13      albertel 1548:     }
1.71      ng       1549: 
                   1550:     function updateSelect(formname,id) {
1.125     ng       1551: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1552: 	return;
1.41      ng       1553:     }
1.33      ng       1554: 
1.121     ng       1555: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1556:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1557: 	formname.gradeOpt.value = val;
1.71      ng       1558: 	if (val == "Save & Next") {
                   1559: 	    for (i=0;i<=total;i++) {
                   1560: 		for (j=0;j<parttot;j++) {
1.125     ng       1561: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1562: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1563: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1564: 			if (points == "") {
1.125     ng       1565: 			    var name = formname["name"+i].value;
1.129     ng       1566: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1567: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1568: 					       ", part "+partid+". Continue?");
1.71      ng       1569: 			    if (resp == false) {
1.125     ng       1570: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1571: 				return false;
                   1572: 			    }
                   1573: 			}
                   1574: 		    }
                   1575: 		}
                   1576: 	    }
                   1577: 	}
1.120     ng       1578: 	formname.submit();
                   1579:     }
                   1580: 
1.71      ng       1581: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1582:     function checkSubmitPage(formname,total) {
                   1583: 	noscore = new Array(100);
                   1584: 	var ptr = 0;
                   1585: 	for (i=1;i<total;i++) {
1.125     ng       1586: 	    var partid = formname["q_"+i].value;
1.127     ng       1587: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1588: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1589: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1590: 		if (points == "" && status != "correct_by_student") {
                   1591: 		    noscore[ptr] = i;
                   1592: 		    ptr++;
                   1593: 		}
                   1594: 	    }
                   1595: 	}
                   1596: 	if (ptr != 0) {
                   1597: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1598: 	    var prolist = "";
                   1599: 	    if (ptr == 1) {
                   1600: 		prolist = noscore[0];
                   1601: 	    } else {
                   1602: 		var i = 0;
                   1603: 		while (i < ptr-1) {
                   1604: 		    prolist += noscore[i]+", ";
                   1605: 		    i++;
                   1606: 		}
                   1607: 		prolist += "and "+noscore[i];
                   1608: 	    }
                   1609: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1610: 	    if (resp == false) {
                   1611: 		return false;
                   1612: 	    }
                   1613: 	}
1.45      ng       1614: 
1.71      ng       1615: 	formname.submit();
                   1616:     }
                   1617: SUBJAVASCRIPT
                   1618: }
1.45      ng       1619: 
1.773     raeburn  1620: #--- javascript for grading message center
                   1621: sub sub_grademessage_js {
1.71      ng       1622:     my $request = shift;
1.80      ng       1623:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1624:     &commonJSfunctions($request);
1.350     albertel 1625: 
1.629     www      1626:     my $inner_js_msg_central= (<<INNERJS);
                   1627: <script type="text/javascript">
1.350     albertel 1628:     function checkInput() {
                   1629:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1630:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1631:       var usrctr = document.msgcenter.usrctr.value;
                   1632:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1633:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1634: 
                   1635:       var msgchk = "";
                   1636:       if (document.msgcenter.subchk.checked) {
                   1637:          msgchk = "msgsub,";
                   1638:       }
                   1639:       var includemsg = 0;
                   1640:       for (var i=1; i<=nmsg; i++) {
                   1641:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1642:           var frmmsg = document.msgcenter["msg"+i];
                   1643:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1644:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1645:           showflg.value = "1";
                   1646:           var chkbox = document.msgcenter["msgn"+i];
                   1647:           if (chkbox.checked) {
                   1648:              msgchk += "savemsg"+i+",";
                   1649:              includemsg = 1;
                   1650:           }
                   1651:       }
                   1652:       if (document.msgcenter.newmsgchk.checked) {
                   1653:          msgchk += "newmsg"+usrctr;
                   1654:          includemsg = 1;
                   1655:       }
                   1656:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1657:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1658:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1659:       includemsg.value = msgchk;
                   1660: 
                   1661:       self.close()
                   1662: 
                   1663:     }
1.629     www      1664: </script>
1.350     albertel 1665: INNERJS
                   1666: 
1.773     raeburn  1667:     my $start_page_msg_central =
1.351     albertel 1668:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1669: 				       {'js_ready'  => 1,
                   1670: 					'only_body' => 1,
                   1671: 					'bgcolor'   =>'#FFFFFF',});
1.773     raeburn  1672:     my $end_page_msg_central =
1.350     albertel 1673: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1674: 
1.219     www      1675:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1676:     $docopen=~s/^document\.//;
1.773     raeburn  1677: 
1.736     damieng  1678:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1679:                 comp => 'Compose Message for: ',
                   1680:                 incl => 'Include',
1.656     raeburn  1681:                 type => 'Type',
1.652     raeburn  1682:                 subj => 'Subject',
                   1683:                 mesa => 'Message',
                   1684:                 new  => 'New',
                   1685:                 save => 'Save',
                   1686:                 canc => 'Cancel',
                   1687:              );
1.736     damieng  1688:     &html_escape(\%html_js_lt);
                   1689:     &js_escape(\%html_js_lt);
1.597     wenzelju 1690:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1691: 
1.44      ng       1692: //===================== Script to view submitted by ==================
                   1693:   function viewSubmitter(submitter) {
                   1694:     document.SCORE.refresh.value = "on";
                   1695:     document.SCORE.NCT.value = "1";
                   1696:     document.SCORE.unamedom0.value = submitter;
                   1697:     document.SCORE.submit();
                   1698:     return;
                   1699:   }
                   1700: 
                   1701: //====================== Script for composing message ==============
1.80      ng       1702:    // preload images
                   1703:    img1 = new Image();
                   1704:    img1.src = "$iconpath/mailbkgrd.gif";
                   1705:    img2 = new Image();
                   1706:    img2.src = "$iconpath/mailto.gif";
                   1707: 
1.44      ng       1708:   function msgCenter(msgform,usrctr,fullname) {
                   1709:     var Nmsg  = msgform.savemsgN.value;
                   1710:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1711:     var subject = msgform.msgsub.value;
1.127     ng       1712:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1713:     re = /msgsub/;
                   1714:     var shwsel = "";
                   1715:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1716:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1717:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1718:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1719: 	var testmsg = "savemsg"+i+",";
                   1720: 	re = new RegExp(testmsg,"g");
1.44      ng       1721: 	shwsel = "";
                   1722: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1723: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1724: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1725: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1726: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1727:     }
1.125     ng       1728:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1729:     shwsel = "";
                   1730:     re = /newmsg/;
                   1731:     if (re.test(msgchk)) { shwsel = "checked" }
                   1732:     newMsg(newmsg,shwsel);
                   1733:     msgTail(); 
                   1734:     return;
                   1735:   }
                   1736: 
1.123     ng       1737:   function checkEntities(strx) {
                   1738:     if (strx.length == 0) return strx;
                   1739:     var orgStr = ["&", "<", ">", '"']; 
                   1740:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1741:     var counter = 0;
                   1742:     while (counter < 4) {
                   1743: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1744: 	counter++;
                   1745:     }
                   1746:     return strx;
                   1747:   }
                   1748: 
                   1749:   function strReplace(strx, orgStr, newStr) {
                   1750:     return strx.split(orgStr).join(newStr);
                   1751:   }
                   1752: 
1.44      ng       1753:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1754:     var height = 70*Nmsg+250;
1.44      ng       1755:     if (height > 600) {
                   1756: 	height = 600;
                   1757:     }
1.118     ng       1758:     var xpos = (screen.width-600)/2;
                   1759:     xpos = (xpos < 0) ? '0' : xpos;
                   1760:     var ypos = (screen.height-height)/2-30;
                   1761:     ypos = (ypos < 0) ? '0' : ypos;
                   1762: 
1.668     www      1763:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1764:     pWin.focus();
                   1765:     pDoc = pWin.document;
1.219     www      1766:     pDoc.$docopen;
1.351     albertel 1767:     pDoc.write('$start_page_msg_central');
1.76      ng       1768: 
                   1769:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1770:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1771:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1772: 
1.676     golterma 1773:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1774:     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       1775: }
                   1776:     function displaySubject(msg,shwsel) {
1.76      ng       1777:     pDoc = pWin.document;
1.676     golterma 1778:     pDoc.write("<tr>");
                   1779:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1780:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1781:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1782: }
                   1783: 
1.72      ng       1784:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1785:     pDoc = pWin.document;
1.676     golterma 1786:     pDoc.write("<tr>");
                   1787:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1788:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1789:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1790: }
                   1791: 
                   1792:   function newMsg(newmsg,shwsel) {
1.76      ng       1793:     pDoc = pWin.document;
1.676     golterma 1794:     pDoc.write("<tr>");
                   1795:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1796:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1797:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1798: }
                   1799: 
                   1800:   function msgTail() {
1.76      ng       1801:     pDoc = pWin.document;
1.676     golterma 1802:     //pDoc.write("<\\/table>");
1.465     albertel 1803:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1804:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1805:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1806:     pDoc.write("<\\/form>");
1.351     albertel 1807:     pDoc.write('$end_page_msg_central');
1.128     ng       1808:     pDoc.close();
1.44      ng       1809: }
                   1810: 
1.773     raeburn  1811: SUBJAVASCRIPT
                   1812: }
                   1813: 
                   1814: #--- javascript for essay type problem --
                   1815: sub sub_page_kw_js {
                   1816:     my $request = shift;
                   1817: 
                   1818:     unless ($env{'form.compmsg'}) {
                   1819:         &commonJSfunctions($request);
                   1820:     }
                   1821: 
                   1822:     my $inner_js_highlight_central= (<<INNERJS);
                   1823: <script type="text/javascript">
                   1824:     function updateChoice(flag) {
                   1825:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1826:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1827:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1828:       opener.document.SCORE.refresh.value = "on";
                   1829:       if (opener.document.SCORE.keywords.value!=""){
                   1830:          opener.document.SCORE.submit();
                   1831:       }
                   1832:       self.close()
                   1833:     }
                   1834: </script>
                   1835: INNERJS
                   1836: 
                   1837:     my $start_page_highlight_central =
                   1838:         &Apache::loncommon::start_page('Highlight Central',
                   1839:                                        $inner_js_highlight_central,
                   1840:                                        {'js_ready'  => 1,
                   1841:                                         'only_body' => 1,
                   1842:                                         'bgcolor'   =>'#FFFFFF',});
                   1843:     my $end_page_highlight_central =
                   1844:         &Apache::loncommon::end_page({'js_ready' => 1});
                   1845: 
                   1846:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   1847:     $docopen=~s/^document\.//;
                   1848: 
                   1849:     my %js_lt = &Apache::lonlocal::texthash(
                   1850:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1851:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1852:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1853:                 col1 => 'red',
                   1854:                 col2 => 'green',
                   1855:                 col3 => 'blue',
                   1856:                 siz1 => 'normal',
                   1857:                 siz2 => '+1',
                   1858:                 siz3 => '+2',
                   1859:                 sty1 => 'normal',
                   1860:                 sty2 => 'italic',
                   1861:                 sty3 => 'bold',
                   1862:              );
                   1863:     my %html_js_lt = &Apache::lonlocal::texthash(
                   1864:                 save => 'Save',
                   1865:                 canc => 'Cancel',
                   1866:                 kehi => 'Keyword Highlight Options',
                   1867:                 txtc => 'Text Color',
                   1868:                 font => 'Font Size',
                   1869:                 fnst => 'Font Style',
                   1870:              );
                   1871:     &js_escape(\%js_lt);
                   1872:     &html_escape(\%html_js_lt);
                   1873:     &js_escape(\%html_js_lt);
                   1874:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   1875: 
                   1876: //===================== Show list of keywords ====================
                   1877:   function keywords(formname) {
                   1878:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   1879:     if (nret==null) return;
                   1880:     formname.keywords.value = nret;
                   1881: 
                   1882:     if (formname.keywords.value != "") {
                   1883:         formname.refresh.value = "on";
                   1884:         formname.submit();
                   1885:     }
                   1886:     return;
                   1887:   }
                   1888: 
                   1889: //===================== Script to add keyword(s) ==================
                   1890:   function getSel() {
                   1891:     if (document.getSelection) txt = document.getSelection();
                   1892:     else if (document.selection) txt = document.selection.createRange().text;
                   1893:     else return;
                   1894:     if (typeof(txt) != 'string') {
                   1895:         txt = String(txt);
                   1896:     }
                   1897:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1898:     if (cleantxt=="") {
                   1899:         alert("$js_lt{'plse'}");
                   1900:         return;
                   1901:     }
                   1902:     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   1903:     if (nret==null) return;
                   1904:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   1905:     if (document.SCORE.keywords.value != "") {
                   1906:         document.SCORE.refresh.value = "on";
                   1907:         document.SCORE.submit();
                   1908:     }
                   1909:     return;
                   1910:   }
                   1911: 
1.44      ng       1912: //====================== Script for keyword highlight options ==============
                   1913:   function kwhighlight() {
                   1914:     var kwclr    = document.SCORE.kwclr.value;
                   1915:     var kwsize   = document.SCORE.kwsize.value;
                   1916:     var kwstyle  = document.SCORE.kwstyle.value;
                   1917:     var redsel = "";
                   1918:     var grnsel = "";
                   1919:     var blusel = "";
1.736     damieng  1920:     var txtcol1 = "$js_lt{'col1'}";
                   1921:     var txtcol2 = "$js_lt{'col2'}";
                   1922:     var txtcol3 = "$js_lt{'col3'}";
                   1923:     var txtsiz1 = "$js_lt{'siz1'}";
                   1924:     var txtsiz2 = "$js_lt{'siz2'}";
                   1925:     var txtsiz3 = "$js_lt{'siz3'}";
                   1926:     var txtsty1 = "$js_lt{'sty1'}";
                   1927:     var txtsty2 = "$js_lt{'sty2'}";
                   1928:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1929:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1930:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1931:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1932:     var sznsel = "";
                   1933:     var sz1sel = "";
                   1934:     var sz2sel = "";
1.718     bisitz   1935:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1936:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1937:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1938:     var synsel = "";
                   1939:     var syisel = "";
                   1940:     var sybsel = "";
1.718     bisitz   1941:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1942:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1943:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1944:     highlightCentral();
1.718     bisitz   1945:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1946:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1947:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1948:     highlightend();
                   1949:     return;
                   1950:   }
                   1951: 
                   1952:   function highlightCentral() {
1.76      ng       1953: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1954:     var xpos = (screen.width-400)/2;
                   1955:     xpos = (xpos < 0) ? '0' : xpos;
                   1956:     var ypos = (screen.height-330)/2-30;
                   1957:     ypos = (ypos < 0) ? '0' : ypos;
                   1958: 
1.206     albertel 1959:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1960:     hwdWin.focus();
                   1961:     var hDoc = hwdWin.document;
1.219     www      1962:     hDoc.$docopen;
1.351     albertel 1963:     hDoc.write('$start_page_highlight_central');
1.76      ng       1964:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1965:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1966: 
1.718     bisitz   1967:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1968:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1969:   }
                   1970: 
                   1971:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1972:     var hDoc = hwdWin.document;
1.718     bisitz   1973:     hDoc.write("<tr>");
1.76      ng       1974:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1975:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1976:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1977:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1978:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1979:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1980:     hDoc.write("<\\/tr>");
1.44      ng       1981:   }
                   1982: 
                   1983:   function highlightend() { 
1.76      ng       1984:     var hDoc = hwdWin.document;
1.718     bisitz   1985:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1986:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1987:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1988:     hDoc.write("<\\/form>");
1.351     albertel 1989:     hDoc.write('$end_page_highlight_central');
1.128     ng       1990:     hDoc.close();
1.44      ng       1991:   }
                   1992: 
                   1993: SUBJAVASCRIPT
                   1994: }
                   1995: 
1.349     albertel 1996: sub get_increment {
1.348     bowersj2 1997:     my $increment = $env{'form.increment'};
                   1998:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1999:         $increment != .1) {
                   2000:         $increment = 1;
                   2001:     }
                   2002:     return $increment;
                   2003: }
                   2004: 
1.585     bisitz   2005: sub gradeBox_start {
                   2006:     return (
                   2007:         &Apache::loncommon::start_data_table()
                   2008:        .&Apache::loncommon::start_data_table_header_row()
                   2009:        .'<th>'.&mt('Part').'</th>'
                   2010:        .'<th>'.&mt('Points').'</th>'
                   2011:        .'<th>&nbsp;</th>'
                   2012:        .'<th>'.&mt('Assign Grade').'</th>'
                   2013:        .'<th>'.&mt('Weight').'</th>'
                   2014:        .'<th>'.&mt('Grade Status').'</th>'
                   2015:        .&Apache::loncommon::end_data_table_header_row()
                   2016:     );
                   2017: }
                   2018: 
                   2019: sub gradeBox_end {
                   2020:     return (
                   2021:         &Apache::loncommon::end_data_table()
                   2022:     );
                   2023: }
1.71      ng       2024: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   2025: sub gradeBox {
1.322     albertel 2026:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 2027:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2028: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2029:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2030:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2031:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2032:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2033:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2034: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   2035:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2036:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2037:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2038: 				       [$partid]);
                   2039:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2040:     if ($last_resets{$partid}) {
                   2041:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2042:     }
1.695     bisitz   2043:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2044:     my $ctr = 0;
1.348     bowersj2 2045:     my $thisweight = 0;
1.349     albertel 2046:     my $increment = &get_increment();
1.485     albertel 2047: 
                   2048:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2049:     while ($thisweight<=$wgt) {
1.532     bisitz   2050: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2051:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2052: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2053: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2054: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2055:         $thisweight += $increment;
1.71      ng       2056: 	$ctr++;
                   2057:     }
1.485     albertel 2058:     $radio.='</tr></table>';
                   2059: 
                   2060:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2061: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2062: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2063: 	$wgt.')" /></td>'."\n";
1.485     albertel 2064:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2065: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2066: 	' </td>'."\n";
                   2067:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2068: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2069:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2070: 	$line.='<option></option>'.
                   2071: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2072:     } else {
1.485     albertel 2073: 	$line.='<option selected="selected"></option>'.
                   2074: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2075:     }
1.485     albertel 2076:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2077: 
                   2078: 
                   2079:     $result .= 
1.695     bisitz   2080: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   2081:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   2082:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2083:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2084: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2085: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2086: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2087:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2088:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2089:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2090:         $aggtries.'" />'."\n";
1.582     raeburn  2091:     my $res_error;
                   2092:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   2093:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2094:     if ($res_error) {
                   2095:         return &navmap_errormsg();
                   2096:     }
1.318     banghart 2097:     return $result;
                   2098: }
1.322     albertel 2099: 
                   2100: sub handback_box {
1.623     www      2101:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773     raeburn  2102:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   2103:     return unless ($numessay);
1.323     banghart 2104:     my (@respids);
1.652     raeburn  2105:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2106:     foreach my $part_response_id (@part_response_id) {
                   2107:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2108:         if ($part eq $partid) {
1.375     albertel 2109:             push(@respids,$resp);
1.323     banghart 2110:         }
                   2111:     }
1.318     banghart 2112:     my $result;
1.323     banghart 2113:     foreach my $respid (@respids) {
1.322     albertel 2114: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2115: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2116: 	next if (!@$files);
1.654     raeburn  2117: 	my $file_counter = 0;
1.313     banghart 2118: 	foreach my $file (@$files) {
1.368     banghart 2119: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  2120:                 $file_counter++;
1.368     banghart 2121:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  2122:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 2123:     	        $file_disp = "$name.$ext";
                   2124:     	        $file = $file_path.$file_disp;
                   2125:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2126:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2127:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  2128:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2129: 	    }
1.322     albertel 2130: 	}
1.654     raeburn  2131:         if ($file_counter) {
                   2132:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2133:                        '<span class="LC_info">'.
                   2134:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2135:         }
1.313     banghart 2136:     }
1.318     banghart 2137:     return $result;    
1.71      ng       2138: }
1.44      ng       2139: 
1.58      albertel 2140: sub show_problem {
1.382     albertel 2141:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2142:     my $rendered;
1.382     albertel 2143:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2144:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2145:     if ($mode eq 'both' or $mode eq 'text') {
                   2146: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2147: 						       $env{'request.course.id'},
                   2148: 						       undef,\%form);
1.144     albertel 2149:     }
1.58      albertel 2150:     if ($removeform) {
                   2151: 	$rendered=~s|<form(.*?)>||g;
                   2152: 	$rendered=~s|</form>||g;
1.374     albertel 2153: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2154:     }
1.144     albertel 2155:     my $companswer;
                   2156:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2157: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2158: 	$companswer=
                   2159: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2160: 						    $env{'request.course.id'},
                   2161: 						    %form);
1.144     albertel 2162:     }
1.58      albertel 2163:     if ($removeform) {
                   2164: 	$companswer=~s|<form(.*?)>||g;
                   2165: 	$companswer=~s|</form>||g;
1.144     albertel 2166: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2167:     }
1.671     raeburn  2168:     my $renderheading = &mt('View of the problem');
                   2169:     my $answerheading = &mt('Correct answer');
                   2170:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2171:         my $stu_fullname = $env{'form.fullname'};
                   2172:         if ($stu_fullname eq '') {
                   2173:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2174:         }
                   2175:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2176:         if ($forwhom ne '') {
                   2177:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2178:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2179:         }
                   2180:     }
1.468     albertel 2181:     $rendered=
1.588     bisitz   2182:         '<div class="LC_Box">'
1.671     raeburn  2183:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2184:        .$rendered
                   2185:        .'</div>';
1.468     albertel 2186:     $companswer=
1.588     bisitz   2187:         '<div class="LC_Box">'
1.671     raeburn  2188:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2189:        .$companswer
                   2190:        .'</div>';
1.468     albertel 2191:     my $result;
1.144     albertel 2192:     if ($mode eq 'both') {
1.588     bisitz   2193:         $result=$rendered.$companswer;
1.144     albertel 2194:     } elsif ($mode eq 'text') {
1.588     bisitz   2195:         $result=$rendered;
1.144     albertel 2196:     } elsif ($mode eq 'answer') {
1.588     bisitz   2197:         $result=$companswer;
1.144     albertel 2198:     }
1.71      ng       2199:     return $result;
1.58      albertel 2200: }
1.397     albertel 2201: 
1.396     banghart 2202: sub files_exist {
                   2203:     my ($r, $symb) = @_;
                   2204:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2205:     foreach my $student (@students) {
                   2206:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2207:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2208: 					      $udom,$uname);
1.792     raeburn  2209:         my ($string)= &get_last_submission(\%record);
1.397     albertel 2210:         foreach my $submission (@$string) {
                   2211:             my ($partid,$respid) =
                   2212: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2213:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2214: 					   \%record);
                   2215:             return 1 if (@$files);
1.396     banghart 2216:         }
                   2217:     }
1.397     albertel 2218:     return 0;
1.396     banghart 2219: }
1.397     albertel 2220: 
1.394     banghart 2221: sub download_all_link {
                   2222:     my ($r,$symb) = @_;
1.621     www      2223:     unless (&files_exist($r, $symb)) {
1.766     raeburn  2224:         $r->print(&mt('There are currently no submitted documents.'));
                   2225:         return;
1.621     www      2226:     }
1.395     albertel 2227:     my $all_students = 
                   2228: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2229: 
                   2230:     my $parts =
                   2231: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2232: 
1.394     banghart 2233:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2234:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2235:                              'cgi.'.$identifier.'.symb' => $symb,
                   2236:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2237:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2238: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2239:     return;
                   2240: }
                   2241: 
                   2242: sub submit_download_link {
                   2243:     my ($request,$symb) = @_;
                   2244:     if (!$symb) { return ''; }
1.750     raeburn  2245:     my $res_error;
1.773     raeburn  2246:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   2247:         &response_type($symb,\$res_error);
                   2248:     if ($res_error) {
                   2249:         $request->print(&mt('An error occurred retrieving response types'));
                   2250:         return;
                   2251:     }
                   2252:     unless ($numessay) {
                   2253:         $request->print(&mt('No essayresponse items found'));
                   2254:         return;
1.750     raeburn  2255:     }
1.773     raeburn  2256:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2257:     if (@chosenparts) {
                   2258:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   2259:                                           undef,undef,1));
1.750     raeburn  2260:     }
1.773     raeburn  2261:     if ($numessay) {
1.750     raeburn  2262:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2263:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2264:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2265:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2266:         if (ref($fullname) eq 'HASH') {
                   2267:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2268:             if (@students) {
                   2269:                 @{$env{'form.stuinfo'}} = @students;
1.773     raeburn  2270:                 if ($numdropbox) {
1.750     raeburn  2271:                     &download_all_link($request,$symb);
1.773     raeburn  2272:                 } else {
                   2273:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  2274:                 }
1.773     raeburn  2275: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  2276: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2277:             } else {
                   2278:                 $request->print(&mt('No students match the criteria you selected'));
                   2279:             }
                   2280:         } else {
                   2281:             $request->print(&mt('Could not retrieve student information'));
                   2282:         }
                   2283:     } else {
                   2284:         $request->print(&mt('No essayresponse items found'));
                   2285:     }
                   2286:     return;
1.394     banghart 2287: }
1.395     albertel 2288: 
1.432     banghart 2289: sub build_section_inputs {
                   2290:     my $section_inputs;
                   2291:     if ($env{'form.section'} eq '') {
                   2292:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2293:     } else {
                   2294:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2295:         foreach my $section (@sections) {
1.432     banghart 2296:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2297:         }
                   2298:     }
                   2299:     return $section_inputs;
                   2300: }
                   2301: 
1.44      ng       2302: # --------------------------- show submissions of a student, option to grade 
                   2303: sub submission {
1.773     raeburn  2304:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2305:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2306:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2307:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2308:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2309: 
1.324     albertel 2310:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773     raeburn  2311:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  2312:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  2313:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2314: 
                   2315:     if (!&canview($usec)) {
1.712     bisitz   2316:         $request->print(
                   2317:             '<span class="LC_warning">'.
1.713     bisitz   2318:             &mt('Unable to view requested student.').
1.712     bisitz   2319:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2320:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2321:             '</span>');
1.104     albertel 2322: 	return;
                   2323:     }
                   2324: 
1.773     raeburn  2325:     my $res_error;
                   2326:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   2327:         &response_type($symb,\$res_error);
                   2328:     if ($res_error) {
                   2329:         $request->print(&navmap_errormsg());
                   2330:         return;
                   2331:     }
                   2332: 
1.257     albertel 2333:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2334:     unless ($is_tool) { 
                   2335:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2336:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2337:     }
1.773     raeburn  2338:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   2339:         $env{'form.compmsg'} = 1;
                   2340:     }
1.257     albertel 2341:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2342:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2343: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2344: 	'/check.gif" height="16" border="0" />';
1.41      ng       2345: 
                   2346:     # header info
                   2347:     if ($counter == 0) {
1.773     raeburn  2348:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2349:         if (@chosenparts) {
                   2350:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   2351:         } elsif ($divforres) {
                   2352:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   2353:         } else {
                   2354:             $request->print('<br clear="all" />');
                   2355:         }
1.41      ng       2356: 	&sub_page_js($request);
1.773     raeburn  2357:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   2358: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       2359: 
1.44      ng       2360: 	# option to display problem, only once else it cause problems 
                   2361:         # with the form later since the problem has a form.
1.257     albertel 2362: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2363: 	    my $mode;
1.257     albertel 2364: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2365: 		$mode='both';
1.257     albertel 2366: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2367: 		$mode='text';
1.257     albertel 2368: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2369: 		$mode='answer';
                   2370: 	    }
1.329     albertel 2371: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2372: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2373: 	}
1.441     www      2374: 
1.41      ng       2375: 	my %keyhash = ();
1.773     raeburn  2376: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       2377: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2378: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2379: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773     raeburn  2380: 	}
                   2381: 	# kwclr is the only variable that is guaranteed not to be blank
                   2382: 	# if this subroutine has been called once.
                   2383: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 2384: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2385: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2386: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2387: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2388: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773     raeburn  2389: 	}
                   2390: 	if ($env{'form.compmsg'}) {
                   2391: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      2392: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2393: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2394: 	}
1.773     raeburn  2395: 
1.257     albertel 2396: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2397: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2398: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2399: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2400: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2401: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2402: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2403: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2404: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2405: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2406: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2407: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2408: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773     raeburn  2409: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 2410: 			&build_section_inputs().
1.326     albertel 2411: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2412: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2413: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773     raeburn  2414: 	if ($env{'form.compmsg'}) {
                   2415: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   2416: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   2417: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   2418: 	}
                   2419: 	if ($numessay) {
1.257     albertel 2420: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2421: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2422: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773     raeburn  2423: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       2424: 	}
1.773     raeburn  2425: 
1.41      ng       2426: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2427: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2428: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2429: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2430: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2431: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2432: 		'" />'."\n".
                   2433: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2434: 	    $cts++;
                   2435: 	}
                   2436: 	$request->print($prnmsg);
1.32      ng       2437: 
1.773     raeburn  2438: 	if ($numessay) {
1.652     raeburn  2439: 
                   2440:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2441:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2442:                           keyw => 'Keyword Options',
1.655     raeburn  2443:                           list => 'List',
1.652     raeburn  2444:                           past => 'Paste Selection to List',
1.661     www      2445:                           high => 'Highlight Attribute',
1.773     raeburn  2446:                      );
1.88      www      2447: #
                   2448: # Print out the keyword options line
                   2449: #
1.718     bisitz   2450: 	    $request->print(
                   2451:                 '<div class="LC_columnSection">'
                   2452:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2453:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2454:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2455:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2456:  class="page">'.$lt{'past'}.'</a>',
                   2457:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2458:                     {legend => $lt{'keyw'}})
                   2459:                .'</fieldset></div>'
                   2460:             );
                   2461: 
1.88      www      2462: #
                   2463: # Load the other essays for similarity check
                   2464: #
1.753     raeburn  2465:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2466:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2467:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2468:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2469:                 if ($cdom ne '' && $cnum ne '') {
                   2470:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2471:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2472:                         my $apath = $1.'_'.$id;
                   2473:                         $apath=~s/\W/\_/gs;
                   2474:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2475:                     }
                   2476:                 }
                   2477:             } else {
                   2478: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2479: 	        $apath=&escape($apath);
                   2480: 	        $apath=~s/\W/\_/gs;
                   2481:                 &init_old_essays($symb,$apath,$adom,$aname);
                   2482:             }
1.41      ng       2483:         }
                   2484:     }
1.44      ng       2485: 
1.441     www      2486: # This is where output for one specific student would start
1.592     bisitz   2487:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2488:     $request->print(
                   2489:         "\n\n"
                   2490:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2491:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2492:        ."\n"
                   2493:     );
1.441     www      2494: 
1.592     bisitz   2495:     # Show additional functions if allowed
                   2496:     if ($perm{'vgr'}) {
                   2497:         $request->print(
                   2498:             &Apache::loncommon::track_student_link(
1.708     bisitz   2499:                 'View recent activity',
1.592     bisitz   2500:                 $uname,$udom,'check')
                   2501:            .' '
                   2502:         );
                   2503:     }
                   2504:     if ($perm{'opa'}) {
                   2505:         $request->print(
                   2506:             &Apache::loncommon::pprmlink(
                   2507:                 &mt('Set/Change parameters'),
                   2508:                 $uname,$udom,$symb,'check'));
                   2509:     }
                   2510: 
                   2511:     # Show Problem
1.257     albertel 2512:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2513: 	my $mode;
1.257     albertel 2514: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2515: 	    $mode='both';
1.257     albertel 2516: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2517: 	    $mode='text';
1.257     albertel 2518: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2519: 	    $mode='answer';
                   2520: 	}
1.329     albertel 2521: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2522: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2523:     }
1.144     albertel 2524: 
1.257     albertel 2525:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       2526: 
1.44      ng       2527:     # Display student info
1.41      ng       2528:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2529: 
1.745     raeburn  2530:     my $boxtitle = &mt('Submissions');
                   2531:     if ($is_tool) {
                   2532:         $boxtitle = &mt('Transactions')
                   2533:     }
1.590     bisitz   2534:     my $result='<div class="LC_Box">'
1.745     raeburn  2535:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2536:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2537:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773     raeburn  2538:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   2539:         $result.='<p class="LC_info">'
                   2540:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2541:                 ."</p>\n";
1.469     albertel 2542:     }
                   2543: 
1.773     raeburn  2544:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 2545:     my $fullname;
                   2546:     my $col_fullnames = [];
1.773     raeburn  2547:     if ($numessay) {
1.464     albertel 2548: 	(my $sub_result,$fullname,$col_fullnames)=
                   2549: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2550: 				 $counter);
                   2551: 	$result.=$sub_result;
1.41      ng       2552:     }
1.44      ng       2553:     $request->print($result."\n");
1.773     raeburn  2554: 
1.44      ng       2555:     # print student answer/submission
1.773     raeburn  2556:     # Options are (1) Last submission only
                   2557:     #             (2) Last submission (with detailed information for that submission)
                   2558:     #             (3) All transactions (by date)
                   2559:     #             (4) The whole record (with detailed information for all transactions)
                   2560: 
1.793     raeburn  2561:     my ($lastsubonly,$partinfo) =
                   2562:         &show_last_submission($uname,$udom,$symb,$essayurl,$responseType,$env{'form.lastSub'},
                   2563:                               $is_tool,$fullname,\%record,\%coursedesc_by_cid);
                   2564:     $request->print($partinfo);
                   2565:     $request->print($lastsubonly);
                   2566: 
                   2567:     if ($env{'form.lastSub'} eq 'datesub') {
                   2568:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2569: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
                   2570:     }
                   2571:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2572:         my $identifier = (&canmodify($usec)? $counter : '');
                   2573:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
                   2574: 								 $env{'request.course.id'},
                   2575: 								 $last,'.submission',
                   2576: 								 'Apache::grades::keywords_highlight',
                   2577:                                                                  $usec,$identifier));
                   2578:     }
                   2579:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2580: 	.$udom.'" />'."\n");
                   2581:     # return if view submission with no grading option
                   2582:     if (!&canmodify($usec)) {
                   2583: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   2584: 	return;
                   2585:     } else {
                   2586: 	$request->print('</div>'."\n");
                   2587:     }
                   2588: 
                   2589:     # grading message center
                   2590: 
                   2591:     if ($env{'form.compmsg'}) {
                   2592:         my $result='<div class="LC_Box">'.
                   2593:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2594:                    '<div class="LC_grade_message_center_body">';
                   2595:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2596:         my $msgfor = $givenn.' '.$lastname;
                   2597:         if (scalar(@$col_fullnames) > 0) {
                   2598:             my $lastone = pop(@$col_fullnames);
                   2599:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2600:         }
                   2601:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2602:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2603:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2604:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2605:                  ',\''.$msgfor.'\');" target="_self">'.
                   2606:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2607:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2608:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2609:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2610:                  '<br />&nbsp;('.
                   2611:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2612:                  '</div></div>';
                   2613:         $request->print($result);
                   2614:     }
                   2615: 
                   2616:     my %seen = ();
                   2617:     my @partlist;
                   2618:     my @gradePartRespid;
                   2619:     my @part_response_id;
                   2620:     if ($is_tool) {
                   2621:         @part_response_id = ([0,'']);
                   2622:     } else {
                   2623:         @part_response_id = &flatten_responseType($responseType);
                   2624:     }
                   2625:     $request->print(
                   2626:         '<div class="LC_Box">'
                   2627:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
                   2628:     );
                   2629:     $request->print(&gradeBox_start());
                   2630:     foreach my $part_response_id (@part_response_id) {
                   2631:     	my ($partid,$respid) = @{ $part_response_id };
                   2632: 	my $part_resp = join('_',@{ $part_response_id });
                   2633: 	next if ($seen{$partid} > 0);
                   2634: 	$seen{$partid}++;
                   2635: 	push(@partlist,$partid);
                   2636: 	push(@gradePartRespid,$partid.'.'.$respid);
                   2637: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
                   2638:     }
                   2639:     $request->print(&gradeBox_end()); # </div>
                   2640:     $request->print('</div>');
                   2641: 
                   2642:     $request->print('<div class="LC_grade_info_links">');
                   2643:     $request->print('</div>');
                   2644: 
                   2645:     $result='<input type="hidden" name="partlist'.$counter.
                   2646: 	'" value="'.(join ":",@partlist).'" />'."\n";
                   2647:     $result.='<input type="hidden" name="gradePartRespid'.
                   2648: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
                   2649:     my $ctr = 0;
                   2650:     while ($ctr < scalar(@partlist)) {
                   2651: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2652: 	    $partlist[$ctr].'" />'."\n";
                   2653: 	$ctr++;
                   2654:     }
                   2655:     $request->print($result.''."\n");
                   2656: 
                   2657: # Done with printing info for one student
                   2658: 
                   2659:     $request->print('</div>');#LC_grade_show_user
                   2660: 
                   2661: 
                   2662:     # print end of form
                   2663:     if ($counter == $total) {
                   2664:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
                   2665: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
                   2666: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
                   2667: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
                   2668: 	my $ntstu ='<select name="NTSTU">'.
                   2669: 	    '<option>1</option><option>2</option>'.
                   2670: 	    '<option>3</option><option>5</option>'.
                   2671: 	    '<option>7</option><option>10</option></select>'."\n";
                   2672: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
                   2673: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
                   2674:         $endform.=&mt('[_1]student(s)',$ntstu);
                   2675: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
                   2676: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
                   2677: 	    '<input type="button" value="'.&mt('Next').'" '.
                   2678: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
                   2679:         $endform.='<span class="LC_warning">'.
                   2680:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2681:                   '</span>'."\n" ;
                   2682:         $endform.="<input type='hidden' value='".&get_increment().
                   2683:             "' name='increment' />";
                   2684: 	$endform.='</td></tr></table></form>';
                   2685: 	$request->print($endform);
                   2686:     }
                   2687:     return '';
                   2688: }
                   2689: 
                   2690: sub show_last_submission {
                   2691:     my ($uname,$udom,$symb,$essayurl,$responseType,$viewtype,$is_tool,$fullname,
                   2692:         $record,$coursedesc_by_cid) = @_;
1.792     raeburn  2693:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
1.793     raeburn  2694:         &get_last_submission($record,$is_tool);
1.468     albertel 2695: 
1.793     raeburn  2696:     my ($lastsubonly,$partinfo);
1.792     raeburn  2697:     if ($timestamp eq '') {
1.793     raeburn  2698:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>';
1.745     raeburn  2699:     } elsif ($is_tool) {
                   2700:         $lastsubonly =
                   2701:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  2702:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$timestamp."</div>\n";
1.702     kruse    2703:     } else {
1.792     raeburn  2704:         my ($shownsubmdate,$showngradedate);
                   2705:         if ($lastsubmittime && $lastgradetime) {
                   2706:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
                   2707:             if ($lastgradetime > $lastsubmittime) {
                   2708:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
                   2709:              }
                   2710:         } else {
                   2711:             $shownsubmdate = $timestamp;
                   2712:         }
1.702     kruse    2713:         $lastsubonly =
                   2714:             '<div class="LC_grade_submissions_body">'
1.792     raeburn  2715:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
                   2716:         if ($showngradedate) {
                   2717:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
                   2718:         }
1.702     kruse    2719: 
1.793     raeburn  2720:         my %seenparts;
                   2721:         my @part_response_id = &flatten_responseType($responseType);
                   2722:         foreach my $part (@part_response_id) {
                   2723:             my ($partid,$respid) = @{ $part };
                   2724:             my $display_part=&get_display_part($partid,$symb);
                   2725:             if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2726:                 if (exists($seenparts{$partid})) { next; }
                   2727:                 $seenparts{$partid}=1;
                   2728:                 $partinfo .=
1.702     kruse    2729:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2730:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2731:                                '<a href="javascript:viewSubmitter(\''.
                   2732:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2733:                                '\');" target="_self">'.
                   2734:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
1.793     raeburn  2735:                     '<br />';
                   2736:                 next;
                   2737:             }
                   2738:             my $responsetype = $responseType->{$partid}->{$respid};
                   2739:             if (!exists($record->{"resource.$partid.$respid.submission"})) {
1.702     kruse    2740:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2741:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2742:                     ' <span class="LC_internal_info">'.
                   2743:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2744:                     '</span>&nbsp; &nbsp;'.
1.793     raeburn  2745:                     '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2746:                 next;
                   2747:             }
                   2748:             foreach my $submission (@$string) {
                   2749:                 my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2750:                 if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2751:                 my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   2752:                 # Similarity check
1.702     kruse    2753:                 my $similar='';
                   2754:                 my ($type,$trial,$rndseed);
                   2755:                 if ($hide eq 'rand') {
                   2756:                     $type = 'randomizetry';
1.793     raeburn  2757:                     $trial = $record->{"resource.$partid.tries"};
                   2758:                     $rndseed = $record->{"resource.$partid.rndseed"};
1.702     kruse    2759:                 }
1.793     raeburn  2760:                 if ($env{'form.checkPlag'}) {
                   2761:                     my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2762:                     &most_similar($uname,$udom,$symb,$subval);
                   2763:                     if ($osim) {
                   2764:                         $osim=int($osim*100.0);
1.702     kruse    2765:                         if ($hide eq 'anon') {
                   2766:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2767:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2768:                         } else {
1.793     raeburn  2769:                             $similar='<hr />';
1.753     raeburn  2770:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2771:                                 $similar .= '<h3><span class="LC_warning">'.
                   2772:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2773:                                                 $osim,
                   2774:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2775:                                             '</span></h3>';
                   2776:                             } else {
                   2777:                                 my %old_course_desc;
                   2778:                                 if ($ocrsid ne '') {
1.793     raeburn  2779:                                     if (ref($coursedesc_by_cid->{$ocrsid}) eq 'HASH') {
                   2780:                                         %old_course_desc = %{$coursedesc_by_cid->{$ocrsid}};
1.753     raeburn  2781:                                     } else {
                   2782:                                         my $args;
                   2783:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   2784:                                             $args = {'one_time' => 1};
                   2785:                                         }
                   2786:                                         %old_course_desc =
                   2787:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
1.793     raeburn  2788:                                         $coursedesc_by_cid->{$ocrsid} = \%old_course_desc;
1.753     raeburn  2789:                                     }
                   2790:                                     $similar .=
                   2791:                                         '<h3><span class="LC_warning">'.
                   2792:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2793:                                             $osim,
                   2794:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2795:                                             $old_course_desc{'description'},
                   2796:                                             $old_course_desc{'num'},
                   2797:                                             $old_course_desc{'domain'}).
                   2798:                                         '</span></h3>';
                   2799:                                 } else {
                   2800:                                     $similar .=
                   2801:                                         '<h3><span class="LC_warning">'.
                   2802:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2803:                                             $osim,
                   2804:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2805:                                         '</span></h3>';
                   2806:                                 }
                   2807:                             }
                   2808:                             $similar .= '<blockquote><i>'.
                   2809:                                         &keywords_highlight($oessay).
                   2810:                                         '</i></blockquote><hr />';
1.702     kruse    2811:                         }
1.793     raeburn  2812:                     }
                   2813:                 }
                   2814:                 my $order=&get_order($partid,$respid,$symb,$uname,$udom,
1.702     kruse    2815:                                      undef,$type,$trial,$rndseed);
1.793     raeburn  2816:                 if (($viewtype eq 'lastonly') ||
                   2817:                     ($viewtype eq 'datesub')  ||
                   2818:                     ($viewtype =~ /^(last|all)$/)) {
                   2819:                     my $display_part=&get_display_part($partid,$symb);
1.702     kruse    2820:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2821:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2822:                         ' <span class="LC_internal_info">'.
                   2823:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2824:                         '</span>&nbsp; &nbsp;';
1.793     raeburn  2825:                     my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2826:                     if (@$files) {
1.702     kruse    2827:                         if ($hide eq 'anon') {
                   2828:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2829:                         } else {
                   2830:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2831:                                         .'<br /><span class="LC_warning">';
                   2832:                             if(@$files == 1) {
                   2833:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2834:                             } else {
1.702     kruse    2835:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2836:                             }
1.774     raeburn  2837:                             $lastsubonly .= '</span>';
1.702     kruse    2838:                             foreach my $file (@$files) {
                   2839:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2840:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2841:                             }
                   2842:                         }
1.793     raeburn  2843:                         $lastsubonly.='<br />';
1.702     kruse    2844:                     }
                   2845:                     if ($hide eq 'anon') {
1.793     raeburn  2846:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
1.702     kruse    2847:                     } else {
1.774     raeburn  2848:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  2849:                         if ($draft) {
                   2850:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2851:                         }
                   2852:                         $subval =
1.793     raeburn  2853:                             &cleanRecord($subval,$responsetype,$symb,$partid,
                   2854:                                          $respid,$record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2855:                         if ($responsetype eq 'essay') {
                   2856:                             $subval =~ s{\n}{<br />}g;
                   2857:                         }
                   2858:                         $lastsubonly.=$subval."\n";
1.702     kruse    2859:                     }
1.774     raeburn  2860:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.793     raeburn  2861:                     $lastsubonly.='</div>';
                   2862:                 }
1.702     kruse    2863:             }
1.773     raeburn  2864:         }
1.793     raeburn  2865:         $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.118     ng       2866:     }
1.793     raeburn  2867:     return ($lastsubonly,$partinfo);
1.38      ng       2868: }
                   2869: 
1.464     albertel 2870: sub check_collaborators {
                   2871:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2872:     my ($result,@col_fullnames);
                   2873:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2874:     foreach my $part (keys(%$handgrade)) {
                   2875: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2876: 					'.maxcollaborators',
                   2877: 					$symb,$udom,$uname);
                   2878: 	next if ($ncol <= 0);
                   2879: 	$part =~ s/\_/\./g;
                   2880: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2881: 	my (@good_collaborators, @bad_collaborators);
                   2882: 	foreach my $possible_collaborator
1.630     www      2883: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2884: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2885: 	    next if ($possible_collaborator eq '');
1.631     www      2886: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2887: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2888: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2889: 	    # Doing this grep allows 'fuzzy' specification
                   2890: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2891: 			       keys(%$classlist));
                   2892: 	    if (! scalar(@matches)) {
                   2893: 		push(@bad_collaborators, $possible_collaborator);
                   2894: 	    } else {
                   2895: 		push(@good_collaborators, @matches);
                   2896: 	    }
                   2897: 	}
                   2898: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2899: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2900: 	    foreach my $name (@good_collaborators) {
                   2901: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2902: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2903: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2904: 	    }
1.630     www      2905: 	    $result.='</ol><br />'."\n";
1.466     albertel 2906: 	    my ($part)=split(/\./,$part);
1.464     albertel 2907: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2908: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2909: 		"\n";
                   2910: 	}
                   2911: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2912: 	    $result.='<div class="LC_warning">';
1.464     albertel 2913: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2914: 	    $result .= '</div>';
                   2915: 	}         
                   2916: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2917: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2918: 	    $result .= &mt('This student has submitted too many '.
                   2919: 		'collaborators.  Maximum is [_1].',$ncol);
                   2920: 	    $result .= '</div>';
                   2921: 	}
                   2922:     }
                   2923:     return ($result,$fullname,\@col_fullnames);
                   2924: }
                   2925: 
1.44      ng       2926: #--- Retrieve the last submission for all the parts
1.38      ng       2927: sub get_last_submission {
1.745     raeburn  2928:     my ($returnhash,$is_tool)=@_;
1.792     raeburn  2929:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
1.119     ng       2930:     if ($$returnhash{'version'}) {
1.46      ng       2931: 	my %lasthash=();
1.792     raeburn  2932:         my %prevsolved=();
                   2933:         my %solved=();
                   2934: 	my $version;
1.119     ng       2935: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.792     raeburn  2936:             my %handgraded = ();
1.397     albertel 2937: 	    foreach my $key (sort(split(/\:/,
                   2938: 					$$returnhash{$version.':keys'}))) {
                   2939: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
1.792     raeburn  2940:                 if ($key =~ /\.([^.]+)\.regrader$/) {
                   2941:                     $handgraded{$1} = 1;
                   2942:                 } elsif ($key =~ /\.portfiles$/) {
                   2943:                     if (($$returnhash{$version.':'.$key} ne '') &&
                   2944:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
                   2945:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   2946:                     }
                   2947:                 } elsif ($key =~ /\.submission$/) {
                   2948:                     if ($$returnhash{$version.':'.$key} ne '') {
                   2949:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   2950:                     }
                   2951:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
                   2952:                     $prevsolved{$1} = $solved{$1};
                   2953:                     $solved{$1} = $lasthash{$key};
                   2954:                 }
                   2955:             }
                   2956:             foreach my $partid (keys(%handgraded)) {
                   2957:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
                   2958:                     (($solved{$partid} eq 'incorrect_by_override') ||
                   2959:                      ($solved{$partid} eq 'correct_by_override'))) {
                   2960:                     $lastgradetime = $$returnhash{$version.':timestamp'};
                   2961:                 }
                   2962:                 if ($solved{$partid} ne '') {
                   2963:                     $prevsolved{$partid} = $solved{$partid};
                   2964:                 }
1.46      ng       2965: 	    }
                   2966: 	}
1.795   ! raeburn  2967: #
        !          2968: # Timestamp is for last transaction for this resource, which does not
        !          2969: # necessarily correspond to the time of last submission for problem (or part).
        !          2970: #
        !          2971:         if ($lasthash{'timestamp'} ne '') {
        !          2972:             $timestamp = &Apache::lonlocal::locallocaltime($lasthash{'timestamp'});
        !          2973:         }
1.640     raeburn  2974:         my (%typeparts,%randombytry);
1.596     raeburn  2975:         my $showsurv = 
                   2976:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2977:         foreach my $key (sort(keys(%lasthash))) {
                   2978:             if ($key =~ /\.type$/) {
                   2979:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2980:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2981:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2982:                     my ($ign,@parts) = split(/\./,$key);
                   2983:                     pop(@parts);
1.641     raeburn  2984:                     my $id = join('.',@parts);
1.640     raeburn  2985:                     if ($lasthash{$key} eq 'randomizetry') {
                   2986:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2987:                     } else {
                   2988:                         unless ($showsurv) {
                   2989:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2990:                         }
1.596     raeburn  2991:                     }
                   2992:                     delete($lasthash{$key});
                   2993:                 }
                   2994:             }
                   2995:         }
                   2996:         my @hidden = keys(%typeparts);
1.640     raeburn  2997:         my @randomize = keys(%randombytry);
1.397     albertel 2998: 	foreach my $key (keys(%lasthash)) {
                   2999: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  3000:             my $hide;
                   3001:             if (@hidden) {
                   3002:                 foreach my $id (@hidden) {
                   3003:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  3004:                         $hide = 'anon';
1.596     raeburn  3005:                         last;
                   3006:                     }
                   3007:                 }
                   3008:             }
1.640     raeburn  3009:             unless ($hide) {
                   3010:                 if (@randomize) {
1.732     raeburn  3011:                     foreach my $id (@randomize) {
1.640     raeburn  3012:                         if ($key =~ /^\Q$id\E/) {
                   3013:                             $hide = 'rand';
                   3014:                             last;
                   3015:                         }
                   3016:                     }
                   3017:                 }
                   3018:             }
1.397     albertel 3019: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  3020: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   3021:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   3022:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   3023:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       3024: 	}
                   3025:     }
1.397     albertel 3026:     if (!@string) {
1.745     raeburn  3027:         my $msg;
                   3028:         if ($is_tool) {
1.747     raeburn  3029:             $msg = &mt('No grade passed back.');
1.745     raeburn  3030:         } else {
                   3031:             $msg = &mt('Nothing submitted - no attempts.');
                   3032:         }
1.397     albertel 3033: 	$string[0] =
1.745     raeburn  3034: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 3035:     }
1.792     raeburn  3036:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       3037: }
1.35      ng       3038: 
1.44      ng       3039: #--- High light keywords, with style choosen by user.
1.38      ng       3040: sub keywords_highlight {
1.44      ng       3041:     my $string    = shift;
1.257     albertel 3042:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   3043:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       3044:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 3045:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 3046:     foreach my $keyword (@keylist) {
                   3047: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       3048:     }
                   3049:     return $string;
1.38      ng       3050: }
1.36      ng       3051: 
1.671     raeburn  3052: # For Tasks provide a mechanism to display previous version for one specific student
                   3053: 
                   3054: sub show_previous_task_version {
                   3055:     my ($request,$symb) = @_;
                   3056:     if ($symb eq '') {
1.717     bisitz   3057:         $request->print(
                   3058:             '<span class="LC_error">'.
                   3059:             &mt('Unable to handle ambiguous references.').
                   3060:             '</span>');
1.671     raeburn  3061:         return '';
                   3062:     }
                   3063:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3064:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3065:     if (!&canview($usec)) {
1.712     bisitz   3066:         $request->print(
                   3067:             '<span class="LC_warning">'.
1.713     bisitz   3068:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   3069:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3070:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3071:             '</span>');
1.671     raeburn  3072:         return;
                   3073:     }
                   3074:     my $mode = 'both';
                   3075:     my $isTask = ($symb =~/\.task$/);
                   3076:     if ($isTask) {
                   3077:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   3078:             if ($env{'form.fullname'} eq '') {
                   3079:                 $env{'form.fullname'} =
                   3080:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3081:             }
                   3082:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   3083:             $request->print("\n\n".
                   3084:                             '<div class="LC_grade_show_user">'.
                   3085:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   3086:                             '</h2>'."\n");
                   3087:             &Apache::lonxml::clear_problem_counter();
                   3088:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   3089:                             {'previousversion' => $env{'form.previousversion'} }));
                   3090:             $request->print("\n</div>");
                   3091:         }
                   3092:     }
                   3093:     return;
                   3094: }
                   3095: 
                   3096: sub choose_task_version_form {
                   3097:     my ($symb,$uname,$udom,$nomenu) = @_;
                   3098:     my $isTask = ($symb =~/\.task$/);
                   3099:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   3100:     if ($isTask) {
                   3101:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3102:                                               $udom,$uname);
                   3103:         if (($record{'resource.0.version'} eq '') ||
                   3104:             ($record{'resource.0.version'} < 2)) {
                   3105:             return ($record{'resource.0.version'},
                   3106:                     $record{'resource.0.version'},$result,$js);
                   3107:         } else {
                   3108:             $current = $record{'resource.0.version'};
                   3109:         }
                   3110:         if ($env{'form.previousversion'}) {
                   3111:             $displayed = $env{'form.previousversion'};
                   3112:             $rowtitle = &mt('Choose another version:')
                   3113:         } else {
                   3114:             $displayed = $current;
                   3115:             $rowtitle = &mt('Show earlier version:');
                   3116:         }
                   3117:         $result = '<div class="LC_left_float">';
                   3118:         my $list;
                   3119:         my $numversions = 0;
                   3120:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3121:             if ($i == $current) {
                   3122:                 if (!$env{'form.previousversion'} || $nomenu) {
                   3123:                     next;
                   3124:                 } else {
                   3125:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3126:                     $numversions ++;
                   3127:                 }
                   3128:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3129:                 unless ($i == $env{'form.previousversion'}) {
                   3130:                     $numversions ++;
                   3131:                 }
                   3132:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3133:             }
                   3134:         }
                   3135:         if ($numversions) {
                   3136:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3137:             $result .=
                   3138:                 '<form name="getprev" method="post" action=""'.
                   3139:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3140:                 &Apache::loncommon::start_data_table().
                   3141:                 &Apache::loncommon::start_data_table_row().
                   3142:                 '<th align="left">'.$rowtitle.'</th>'.
                   3143:                 '<td><select name="version">'.
                   3144:                 '<option>'.&mt('Select').'</option>'.
                   3145:                 $list.
                   3146:                 '</select></td>'.
                   3147:                 &Apache::loncommon::end_data_table_row();
                   3148:             unless ($nomenu) {
                   3149:                 $result .= &Apache::loncommon::start_data_table_row().
                   3150:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3151:                 '<td><span class="LC_nobreak">'.
                   3152:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3153:                 &mt('Yes').'</label>'.
                   3154:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3155:                 '</span></td>'.
                   3156:                 &Apache::loncommon::end_data_table_row();
                   3157:             }
                   3158:             $result .=
                   3159:                 &Apache::loncommon::start_data_table_row().
                   3160:                 '<th align="left">&nbsp;</th>'.
                   3161:                 '<td>'.
                   3162:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3163:                 '</td>'.
                   3164:                 &Apache::loncommon::end_data_table_row().
                   3165:                 &Apache::loncommon::end_data_table().
                   3166:                 '</form>';
                   3167:             $js = &previous_display_javascript($nomenu,$current);
                   3168:         } elsif ($displayed && $nomenu) {
                   3169:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3170:         } else {
                   3171:             $result .= &mt('No previous versions to show for this student');
                   3172:         }
                   3173:         $result .= '</div>';
                   3174:     }
                   3175:     return ($current,$displayed,$result,$js);
                   3176: }
                   3177: 
                   3178: sub previous_display_javascript {
                   3179:     my ($nomenu,$current) = @_;
                   3180:     my $js = <<"JSONE";
                   3181: <script type="text/javascript">
                   3182: // <![CDATA[
                   3183: function previousVersion(uname,udom,symb) {
                   3184:     var current = '$current';
                   3185:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3186:     var prevstr = new RegExp("^\\\\d+\$");
                   3187:     if (!prevstr.test(version)) {
                   3188:         return false;
                   3189:     }
                   3190:     var url = '';
                   3191:     if (version == current) {
                   3192:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3193:     } else {
                   3194:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3195:     }
                   3196: JSONE
                   3197:     if ($nomenu) {
                   3198:         $js .= <<"JSTWO";
                   3199:     document.location.href = url;
                   3200: JSTWO
                   3201:     } else {
                   3202:         $js .= <<"JSTHREE";
                   3203:     var newwin = 0;
                   3204:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3205:         if (document.getprev.prevwin[i].checked == true) {
                   3206:             newwin = document.getprev.prevwin[i].value;
                   3207:         }
                   3208:     }
                   3209:     if (newwin == 1) {
                   3210:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3211:         url = url+'&inhibitmenu=yes';
                   3212:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3213:             previousWin = window.open(url,'',options,1);
                   3214:         } else {
                   3215:             previousWin.location.href = url;
                   3216:         }
                   3217:         previousWin.focus();
                   3218:         return false;
                   3219:     } else {
                   3220:         document.location.href = url;
                   3221:         return false;
                   3222:     }
                   3223: JSTHREE
                   3224:     }
                   3225:     $js .= <<"ENDJS";
                   3226:     return false;
                   3227: }
                   3228: // ]]>
                   3229: </script>
                   3230: ENDJS
                   3231: 
                   3232: }
                   3233: 
1.44      ng       3234: #--- Called from submission routine
1.38      ng       3235: sub processHandGrade {
1.608     www      3236:     my ($request,$symb) = @_;
1.324     albertel 3237:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3238:     my $button = $env{'form.gradeOpt'};
                   3239:     my $ngrade = $env{'form.NCT'};
                   3240:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3241:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3242:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.786     raeburn  3243:     my ($res_error,%queueable);
                   3244:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3245:     if ($res_error) {
                   3246:         $request->print(&navmap_errormsg());
                   3247:         return;
                   3248:     } else {
                   3249:         foreach my $part (@{$partlist}) {
                   3250:             if (ref($responseType->{$part}) eq 'HASH') {
                   3251:                 foreach my $id (keys(%{$responseType->{$part}})) {
                   3252:                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   3253:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   3254:                         $queueable{$part} = 1;
                   3255:                         last;
                   3256:                     }
                   3257:                 }
                   3258:             }
                   3259:         }
                   3260:     }
1.301     albertel 3261: 
1.44      ng       3262:     if ($button eq 'Save & Next') {
                   3263: 	my $ctr = 0;
                   3264: 	while ($ctr < $ngrade) {
1.257     albertel 3265: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  3266: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
1.786     raeburn  3267:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
1.71      ng       3268: 	    if ($errorflag eq 'no_score') {
                   3269: 		$ctr++;
                   3270: 		next;
                   3271: 	    }
1.104     albertel 3272: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3273: 		$request->print(
                   3274:                     '<span class="LC_error">'
                   3275:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3276:                    .'</span>');
1.104     albertel 3277: 		$ctr++;
                   3278: 		next;
                   3279: 	    }
1.726     raeburn  3280:             if ($numhidden) {
                   3281:                 $request->print(
                   3282:                     '<span class="LC_info">'
                   3283:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3284:                    .'</span><br />');
                   3285:             }
1.257     albertel 3286: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3287: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3288: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3289:             my ($feedurl,$showsymb) =
                   3290: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3291: 	    my $messagetail;
1.62      albertel 3292: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3293: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3294: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3295: 		$subject.=' ['.$restitle.']';
1.44      ng       3296: 		my (@msgnum) = split(/,/,$includemsg);
                   3297: 		foreach (@msgnum) {
1.257     albertel 3298: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3299: 		}
1.80      ng       3300: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3301: 		if ($env{'form.withgrades'.$ctr}) {
                   3302: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3303: 		    $messagetail = " for <a href=\"".
1.605     www      3304: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3305: 		}
                   3306: 		$msgstatus = 
                   3307:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3308: 						     $message.$messagetail,
1.418     albertel 3309:                                                      undef,$feedurl,undef,
1.386     raeburn  3310:                                                      undef,undef,$showsymb,
                   3311:                                                      $restitle);
1.574     bisitz   3312: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3313: 				$msgstatus.'<br />');
1.44      ng       3314: 	    }
1.257     albertel 3315: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3316: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3317: 		foreach my $collabstr (@collabstrs) {
                   3318: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3319: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3320: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3321: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.786     raeburn  3322: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 3323: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3324: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3325: 			    next;
1.418     albertel 3326: 			} elsif ($message ne '') {
                   3327: 			    my ($baseurl,$showsymb) = 
                   3328: 				&get_feedurl_and_symb($symb,$collaborator,
                   3329: 						      $udom);
                   3330: 			    if ($env{'form.withgrades'.$ctr}) {
                   3331: 				$messagetail = " for <a href=\"".
1.605     www      3332:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3333: 			    }
1.418     albertel 3334: 			    $msgstatus = 
                   3335: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3336: 			}
1.44      ng       3337: 		    }
                   3338: 		}
                   3339: 	    }
                   3340: 	    $ctr++;
                   3341: 	}
                   3342:     }
                   3343: 
1.773     raeburn  3344:     my %keyhash = ();
                   3345:     if ($numessay) {
1.119     ng       3346: 	# Keywords sorted in alphabatical order
1.257     albertel 3347: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3348: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  3349: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3350: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3351: 	$env{'form.keywords'} = join(' ',@keywords);
                   3352: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3353: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3354: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3355: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3356: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  3357:     }
1.119     ng       3358: 
1.773     raeburn  3359:     if ($env{'form.compmsg'}) {
1.119     ng       3360: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3361: 	# New messages are saved in env for the next student.
1.119     ng       3362: 	# All messages are saved in nohist_handgrade.db
                   3363: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3364: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3365: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3366: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3367: 		$idx++;
                   3368: 	    }
                   3369: 	    $ctr++;
1.41      ng       3370: 	}
1.119     ng       3371: 	$ctr = 0;
                   3372: 	while ($ctr < $ngrade) {
1.257     albertel 3373: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  3374: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3375: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3376: 	        $idx++;
1.119     ng       3377: 	    }
                   3378: 	    $ctr++;
1.41      ng       3379: 	}
1.257     albertel 3380: 	$env{'form.savemsgN'} = --$idx;
                   3381: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       3382:     }
1.773     raeburn  3383:     if (($numessay) || ($env{'form.compmsg'})) {
                   3384:         my $putresult = &Apache::lonnet::put
                   3385:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   3386:     }
                   3387: 
1.44      ng       3388:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3389:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3390:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3391: 	my ($ctr,$total) = (0,0);
                   3392: 	while ($ctr < $ngrade) {
1.257     albertel 3393: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3394: 	    $ctr++;
                   3395: 	}
1.257     albertel 3396: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3397: 	$ctr = 0;
                   3398: 	while ($ctr < $total) {
1.257     albertel 3399: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3400: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3401: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3402: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3403: 	    $ctr++;
                   3404: 	}
                   3405: 	return '';
                   3406:     }
1.36      ng       3407: 
1.44      ng       3408:     # Get the next/previous one or group of students
1.257     albertel 3409:     my $firststu = $env{'form.unamedom0'};
                   3410:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3411:     my $ctr = 2;
1.41      ng       3412:     while ($laststu eq '') {
1.257     albertel 3413: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3414: 	$ctr++;
                   3415: 	$laststu = $firststu if ($ctr > $ngrade);
                   3416:     }
1.44      ng       3417: 
1.41      ng       3418:     my (@parsedlist,@nextlist);
                   3419:     my ($nextflg) = 0;
1.524     raeburn  3420:     foreach my $item (sort 
1.294     albertel 3421: 	     {
                   3422: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3423: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3424: 		 }
                   3425: 		 return $a cmp $b;
                   3426: 	     } (keys(%$fullname))) {
1.41      ng       3427: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3428: 	    push(@parsedlist,$item);
1.41      ng       3429: 	}
1.524     raeburn  3430: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3431: 	if ($button eq 'Previous') {
1.524     raeburn  3432: 	    last if ($item eq $firststu);
                   3433: 	    push(@parsedlist,$item);
1.41      ng       3434: 	}
                   3435:     }
                   3436:     $ctr = 0;
                   3437:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3438:     foreach my $student (@parsedlist) {
1.257     albertel 3439: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3440: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3441: 	
                   3442: 	if ($submitonly eq 'queued') {
                   3443: 	    my %queue_status = 
                   3444: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3445: 							$udom,$uname);
                   3446: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3447: 	}
                   3448: 
1.156     albertel 3449: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3450: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3451: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3452: 	    my $submitted = 0;
1.248     albertel 3453: 	    my $ungraded = 0;
                   3454: 	    my $incorrect = 0;
1.524     raeburn  3455: 	    foreach my $item (keys(%status)) {
                   3456: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3457: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3458: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3459: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3460: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3461: 		    $submitted = 0;
                   3462: 		}
1.41      ng       3463: 	    }
1.156     albertel 3464: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3465: 				     $submitonly eq 'incorrect' ||
                   3466: 				     $submitonly eq 'graded'));
1.248     albertel 3467: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3468: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3469: 	}
1.524     raeburn  3470: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3471: 	last if ($ctr == $ntstu);
1.41      ng       3472: 	$ctr++;
                   3473:     }
1.36      ng       3474: 
1.41      ng       3475:     $ctr = 0;
                   3476:     my $total = scalar(@nextlist)-1;
1.39      ng       3477: 
1.524     raeburn  3478:     foreach (sort(@nextlist)) {
1.41      ng       3479: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3480: 	$env{'form.student'}  = $uname;
                   3481: 	$env{'form.userdom'}  = $udom;
                   3482: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3483: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3484: 	$ctr++;
                   3485:     }
                   3486:     if ($total < 0) {
1.653     raeburn  3487: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3488: 	$request->print($the_end);
                   3489:     }
                   3490:     return '';
1.38      ng       3491: }
1.36      ng       3492: 
1.44      ng       3493: #---- Save the score and award for each student, if changed
1.38      ng       3494: sub saveHandGrade {
1.786     raeburn  3495:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
1.342     banghart 3496:     my @version_parts;
1.104     albertel 3497:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3498: 					   $env{'request.course.id'});
1.104     albertel 3499:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3500:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3501:     my @parts_graded;
1.77      ng       3502:     my %newrecord  = ();
1.726     raeburn  3503:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3504:     my %aggregate = ();
                   3505:     my $aggregateflag = 0;
1.726     raeburn  3506:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3507:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3508:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3509:         $totchg += $numchgs;
                   3510:     }
1.301     albertel 3511:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3512:     foreach my $new_part (@parts) {
1.337     banghart 3513: 	#collaborator ($submi may vary for different parts
1.259     banghart 3514: 	if ($submitter && $new_part ne $part) { next; }
                   3515: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3516: 	if ($dropMenu eq 'excused') {
1.259     banghart 3517: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3518: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3519: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3520: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3521: 		}
1.364     banghart 3522: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3523: 	    }
1.125     ng       3524: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3525: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3526: 	    foreach my $key (keys(%record)) {
1.259     banghart 3527: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3528: 	    }
1.259     banghart 3529: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3530: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3531:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3532: 
                   3533:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3534: 					       [$new_part]);
                   3535:             my $aggtries =$totaltries;
1.269     raeburn  3536:             if ($last_resets{$new_part}) {
1.270     albertel 3537:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3538: 					   $new_part);
1.269     raeburn  3539:             }
1.270     albertel 3540: 
                   3541:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3542:             if ($aggtries > 0) {
1.327     albertel 3543:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3544:                 $aggregateflag = 1;
                   3545:             }
1.125     ng       3546: 	} elsif ($dropMenu eq '') {
1.259     banghart 3547: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3548: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3549: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3550: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3551: 		next;
                   3552: 	    }
1.259     banghart 3553: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3554: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3555: 	    my $partial= $pts/$wgt;
1.259     banghart 3556: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3557: 		#do not update score for part if not changed.
1.346     banghart 3558:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3559: 		next;
1.251     banghart 3560: 	    } else {
1.524     raeburn  3561: 	        push(@parts_graded,$new_part);
1.153     albertel 3562: 	    }
1.259     banghart 3563: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3564: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3565: 	    }
1.259     banghart 3566: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3567: 	    if ($partial == 0) {
1.153     albertel 3568: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3569: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3570: 		}
1.41      ng       3571: 	    } else {
1.153     albertel 3572: 		if ($record{$reckey} ne 'correct_by_override') {
                   3573: 		    $newrecord{$reckey} = 'correct_by_override';
                   3574: 		}
                   3575: 	    }	    
                   3576: 	    if ($submitter && 
1.259     banghart 3577: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3578: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3579: 	    }
1.259     banghart 3580: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3581: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3582: 	}
1.259     banghart 3583: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3584: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3585: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3586: 	        $dropMenu eq 'reset status')
                   3587: 	   {
1.524     raeburn  3588: 	    push(@version_parts,$new_part);
1.259     banghart 3589: 	}
1.41      ng       3590:     }
1.301     albertel 3591:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3592:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3593: 
1.344     albertel 3594:     if (%newrecord) {
                   3595:         if (@version_parts) {
1.364     banghart 3596:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3597:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3598: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3599: 	    foreach my $new_part (@version_parts) {
                   3600: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3601: 				$new_part,\%newrecord);
                   3602: 	    }
1.259     banghart 3603:         }
1.44      ng       3604: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3605: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3606: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.786     raeburn  3607: 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       3608:     }
1.269     raeburn  3609:     if ($aggregateflag) {
                   3610:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3611: 			      $cdom,$cnum);
1.269     raeburn  3612:     }
1.726     raeburn  3613:     return ('',$pts,$wgt,$totchg);
                   3614: }
                   3615: 
                   3616: sub makehidden {
1.728     raeburn  3617:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3618:     return unless (ref($record) eq 'HASH');
                   3619:     my %modified;
                   3620:     my $numchanged = 0;
                   3621:     if (exists($record->{$version.':keys'})) {
                   3622:         my $partsregexp = $parts;
                   3623:         $partsregexp =~ s/,/|/g;
                   3624:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3625:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3626:                  my $item = $1;
                   3627:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3628:                      $modified{$key} = $record->{$version.':'.$key};
                   3629:                  }
                   3630:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3631:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3632:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3633:                 $modified{$key} = $record->{$version.':'.$key};
                   3634:             }
                   3635:         }
                   3636:         if (keys(%modified)) {
                   3637:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3638:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3639:                 $numchanged ++;
                   3640:             }
                   3641:         }
                   3642:     }
                   3643:     return $numchanged;
1.36      ng       3644: }
1.322     albertel 3645: 
1.380     albertel 3646: sub check_and_remove_from_queue {
1.786     raeburn  3647:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 3648:     my @ungraded_parts;
                   3649:     foreach my $part (@{$parts}) {
                   3650: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3651: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3652: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3653: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3654: 		) {
1.786     raeburn  3655:             if ($queueable->{$part}) {
                   3656: 	        push(@ungraded_parts, $part);
                   3657:             }
1.380     albertel 3658: 	}
                   3659:     }
                   3660:     if ( !@ungraded_parts ) {
                   3661: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3662: 					       $cnum,$domain,$stuname);
                   3663:     }
                   3664: }
                   3665: 
1.337     banghart 3666: sub handback_files {
                   3667:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3668:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3669:     my $res_error;
                   3670:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3671:     if ($res_error) {
                   3672:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3673:         return;
                   3674:     }
1.654     raeburn  3675:     my @handedback;
                   3676:     my $file_msg;
1.375     albertel 3677:     my @part_response_id = &flatten_responseType($responseType);
                   3678:     foreach my $part_response_id (@part_response_id) {
                   3679:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3680: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3681:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3682:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3683:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3684:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3685:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3686:                     my ($directory,$answer_file) = 
1.654     raeburn  3687:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3688:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3689: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3690: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3691:                     my $getpropath = 1;
1.773     raeburn  3692:                     my ($dir_list,$listerror) =
1.662     raeburn  3693:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3694:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3695: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3696:                     # fix filename
1.355     banghart 3697:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3698:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3699:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3700:             	                                $save_file_name);
1.337     banghart 3701:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3702:                         $request->print('<br /><span class="LC_error">'.
                   3703:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3704:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3705:                                         '</span>');
1.356     banghart 3706:                     } else {
1.360     banghart 3707:                         # mark the file as read only
1.654     raeburn  3708:                         push(@handedback,$save_file_name);
1.367     albertel 3709: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3710: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3711: 			}
                   3712:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3713: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3714:                     }
1.686     bisitz   3715:                     $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 3716:                 }
                   3717:             }
                   3718:         }
1.654     raeburn  3719:     }
                   3720:     if (@handedback > 0) {
                   3721:         $request->print('<br />');
                   3722:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3723:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3724:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3725:         my ($subject,$message);
                   3726:         if (scalar(@handedback) == 1) {
                   3727:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3728:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3729:         } else {
                   3730:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3731:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3732:         }
                   3733:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3734:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3735:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3736:         my ($feedurl,$showsymb) =
                   3737:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3738:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3739:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3740:         my $msgstatus =
                   3741:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3742:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3743:                  $restitle);
                   3744:         if ($msgstatus) {
                   3745:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3746:         }
                   3747:     }
1.338     banghart 3748:     return;
1.337     banghart 3749: }
                   3750: 
1.418     albertel 3751: sub get_feedurl_and_symb {
                   3752:     my ($symb,$uname,$udom) = @_;
                   3753:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3754:     $url = &Apache::lonnet::clutter($url);
                   3755:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3756: 					$symb,$udom,$uname);
                   3757:     if ($encrypturl =~ /^yes$/i) {
                   3758: 	&Apache::lonenc::encrypted(\$url,1);
                   3759: 	&Apache::lonenc::encrypted(\$symb,1);
                   3760:     }
                   3761:     return ($url,$symb);
                   3762: }
                   3763: 
1.313     banghart 3764: sub get_submitted_files {
                   3765:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3766:     my @files;
                   3767:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3768:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3769:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3770:     	    push(@files,$file_url.$file);
                   3771:         }
                   3772:     }
                   3773:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3774:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3775:     }
                   3776:     return (\@files);
                   3777: }
1.322     albertel 3778: 
1.269     raeburn  3779: # ----------- Provides number of tries since last reset.
                   3780: sub get_num_tries {
                   3781:     my ($record,$last_reset,$part) = @_;
                   3782:     my $timestamp = '';
                   3783:     my $num_tries = 0;
                   3784:     if ($$record{'version'}) {
                   3785:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3786:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3787:                 $timestamp = $$record{$version.':timestamp'};
                   3788:                 if ($timestamp > $last_reset) {
                   3789:                     $num_tries ++;
                   3790:                 } else {
                   3791:                     last;
                   3792:                 }
                   3793:             }
                   3794:         }
                   3795:     }
                   3796:     return $num_tries;
                   3797: }
                   3798: 
                   3799: # ----------- Determine decrements required in aggregate totals 
                   3800: sub decrement_aggs {
                   3801:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3802:     my %decrement = (
                   3803:                         attempts => 0,
                   3804:                         users => 0,
                   3805:                         correct => 0
                   3806:                     );
                   3807:     $decrement{'attempts'} = $aggtries;
                   3808:     if ($solvedstatus =~ /^correct/) {
                   3809:         $decrement{'correct'} = 1;
                   3810:     }
                   3811:     if ($aggtries == $totaltries) {
                   3812:         $decrement{'users'} = 1;
                   3813:     }
1.524     raeburn  3814:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3815:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3816:     }
                   3817:     return;
                   3818: }
                   3819: 
                   3820: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3821: sub get_last_resets {
1.270     albertel 3822:     my ($symb,$courseid,$partids) =@_;
                   3823:     my %last_resets;
1.269     raeburn  3824:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3825:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3826:     my @keys;
                   3827:     foreach my $part (@{$partids}) {
                   3828: 	push(@keys,"$symb\0$part\0resettime");
                   3829:     }
                   3830:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3831: 				     $cdom,$cname);
                   3832:     foreach my $part (@{$partids}) {
                   3833: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3834:     }
1.270     albertel 3835:     return %last_resets;
1.269     raeburn  3836: }
                   3837: 
1.251     banghart 3838: # ----------- Handles creating versions for portfolio files as answers
                   3839: sub version_portfiles {
1.343     banghart 3840:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3841:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3842:     my @returned_keys;
1.255     banghart 3843:     my $parts = join('|', @$parts_graded);
1.277     albertel 3844:     foreach my $key (keys(%$record)) {
1.259     banghart 3845:         my $new_portfiles;
1.263     banghart 3846:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3847:             my @versioned_portfiles;
1.367     albertel 3848:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3849:             if (@portfiles) {
                   3850:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3851:                                                       \@versioned_portfiles);
1.252     banghart 3852:             }
1.343     banghart 3853:             $$record{$key} = join(',',@versioned_portfiles);
                   3854:             push(@returned_keys,$key);
1.251     banghart 3855:         }
1.794     raeburn  3856:     }
                   3857:     return (@returned_keys);
1.305     banghart 3858: }
                   3859: 
1.44      ng       3860: #--------------------------------------------------------------------------------------
                   3861: #
                   3862: #-------------------------- Next few routines handles grading by section or whole class
                   3863: #
                   3864: #--- Javascript to handle grading by section or whole class
1.42      ng       3865: sub viewgrades_js {
                   3866:     my ($request) = shift;
                   3867: 
1.539     riegler  3868:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3869:     &js_escape(\$alertmsg);
1.597     wenzelju 3870:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3871:    function writePoint(partid,weight,point) {
1.125     ng       3872: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3873: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3874: 	if (point == "textval") {
1.125     ng       3875: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3876: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3877: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3878: 		var resetbox = false;
                   3879: 		for (var i=0; i<radioButton.length; i++) {
                   3880: 		    if (radioButton[i].checked) {
                   3881: 			textbox.value = i;
                   3882: 			resetbox = true;
                   3883: 		    }
                   3884: 		}
                   3885: 		if (!resetbox) {
                   3886: 		    textbox.value = "";
                   3887: 		}
                   3888: 		return;
                   3889: 	    }
1.109     matthew  3890: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3891: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3892: 				   ") greater than the weight for the part. Accept?");
                   3893: 		if (resp == false) {
                   3894: 		    textbox.value = "";
                   3895: 		    return;
                   3896: 		}
                   3897: 	    }
1.42      ng       3898: 	    for (var i=0; i<radioButton.length; i++) {
                   3899: 		radioButton[i].checked=false;
1.109     matthew  3900: 		if (parseFloat(point) == i) {
1.42      ng       3901: 		    radioButton[i].checked=true;
                   3902: 		}
                   3903: 	    }
1.41      ng       3904: 
1.42      ng       3905: 	} else {
1.125     ng       3906: 	    textbox.value = parseFloat(point);
1.42      ng       3907: 	}
1.41      ng       3908: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3909: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3910: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3911: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3912: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3913: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3914: 	    if (saveval != "correct") {
                   3915: 		scorename.value = point;
1.43      ng       3916: 		if (selname[0].selected != true) {
                   3917: 		    selname[0].selected = true;
                   3918: 		}
1.42      ng       3919: 	    }
                   3920: 	}
1.125     ng       3921: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3922:     }
                   3923: 
                   3924:     function writeRadText(partid,weight) {
1.125     ng       3925: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3926: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3927:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3928: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3929: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3930: 	    for (var i=0; i<radioButton.length; i++) {
                   3931: 		radioButton[i].checked=false;
                   3932: 
                   3933: 	    }
                   3934: 	    textbox.value = "";
                   3935: 
                   3936: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3937: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3938: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3939: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3940: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3941: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3942: 		if ((saveval != "correct") || override) {
1.42      ng       3943: 		    scorename.value = "";
1.125     ng       3944: 		    if (selval[1].selected) {
                   3945: 			selname[1].selected = true;
                   3946: 		    } else {
                   3947: 			selname[2].selected = true;
                   3948: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3949: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3950: 		    }
1.42      ng       3951: 		}
                   3952: 	    }
1.43      ng       3953: 	} else {
                   3954: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3955: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3956: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3957: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3958: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3959: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3960: 		if ((saveval != "correct") || override) {
1.125     ng       3961: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3962: 		    selname[0].selected = true;
                   3963: 		}
                   3964: 	    }
                   3965: 	}	    
1.42      ng       3966:     }
                   3967: 
                   3968:     function changeSelect(partid,user) {
1.125     ng       3969: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3970: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3971: 	var point  = textbox.value;
1.125     ng       3972: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3973: 
1.109     matthew  3974: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3975: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3976: 	    textbox.value = "";
                   3977: 	    return;
                   3978: 	}
1.109     matthew  3979: 	if (parseFloat(point) > parseFloat(weight)) {
                   3980: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3981: 			       ") greater than the weight of the part. Accept?");
                   3982: 	    if (resp == false) {
                   3983: 		textbox.value = "";
                   3984: 		return;
                   3985: 	    }
                   3986: 	}
1.42      ng       3987: 	selval[0].selected = true;
                   3988:     }
                   3989: 
                   3990:     function changeOneScore(partid,user) {
1.125     ng       3991: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3992: 	if (selval[1].selected || selval[2].selected) {
                   3993: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3994: 	    if (selval[2].selected) {
                   3995: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3996: 	    }
1.269     raeburn  3997:         }
1.42      ng       3998:     }
                   3999: 
                   4000:     function resetEntry(numpart) {
                   4001: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       4002: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   4003: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   4004: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   4005: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       4006: 	    for (var i=0; i<radioButton.length; i++) {
                   4007: 		radioButton[i].checked=false;
                   4008: 
                   4009: 	    }
                   4010: 	    textbox.value = "";
                   4011: 	    selval[0].selected = true;
                   4012: 
                   4013: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4014: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4015: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4016: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4017: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   4018: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   4019: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   4020: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4021: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4022: 		if (saveselval == "excused") {
1.43      ng       4023: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       4024: 		} else {
1.43      ng       4025: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       4026: 		}
                   4027: 	    }
1.41      ng       4028: 	}
1.42      ng       4029:     }
                   4030: 
1.41      ng       4031: VIEWJAVASCRIPT
1.42      ng       4032: }
                   4033: 
1.44      ng       4034: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       4035: sub viewgrades {
1.608     www      4036:     my ($request,$symb) = @_;
1.745     raeburn  4037:     my ($is_tool,$toolsymb);
                   4038:     if ($symb =~ /ext\.tool$/) {
                   4039:         $is_tool = 1;
                   4040:         $toolsymb = $symb;
                   4041:     }
1.42      ng       4042:     &viewgrades_js($request);
1.41      ng       4043: 
1.168     albertel 4044:     #need to make sure we have the correct data for later EXT calls, 
                   4045:     #thus invalidate the cache
                   4046:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4047:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4048:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4049:     &Apache::lonnet::clear_EXT_cache_status();
                   4050: 
1.398     albertel 4051:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       4052: 
                   4053:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 4054:     $result.=&jscriptNform($symb);
1.41      ng       4055: 
1.44      ng       4056:     #beginning of class grading form
1.442     banghart 4057:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       4058:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 4059: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       4060: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 4061: 	&build_section_inputs().
1.442     banghart 4062: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       4063: 
1.738     raeburn  4064:     #retrieve selected groups
                   4065:     my (@groups,$group_display);
                   4066:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   4067:     if (grep(/^all$/,@groups)) {
                   4068:         @groups = ('all');
                   4069:     } elsif (grep(/^none$/,@groups)) {
                   4070:         @groups = ('none');
                   4071:     } elsif (@groups > 0) {
                   4072:         $group_display = join(', ',@groups);
                   4073:     }
                   4074: 
                   4075:     my ($common_header,$specific_header,@sections,$section_display);
1.780     raeburn  4076:     if ($env{'request.course.sec'} ne '') {
                   4077:         @sections = ($env{'request.course.sec'});
                   4078:     } else {
                   4079:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   4080:     }
                   4081: 
                   4082: # Check if Save button should be usable
                   4083:     my $disabled = ' disabled="disabled"';
                   4084:     if ($perm{'mgr'}) {
                   4085:         if (grep(/^all$/,@sections)) {
                   4086:             undef($disabled);
                   4087:         } else {
                   4088:             foreach my $sec (@sections) {
                   4089:                 if (&canmodify($sec)) {
                   4090:                     undef($disabled);
                   4091:                     last;
                   4092:                 }
                   4093:             }
                   4094:         }
                   4095:     }
1.738     raeburn  4096:     if (grep(/^all$/,@sections)) {
                   4097:         @sections = ('all');
                   4098:         if ($group_display) {
                   4099:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4100:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4101:         } elsif (grep(/^none$/,@groups)) {
                   4102:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4103:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4104:         } else {
                   4105: 	    $common_header = &mt('Assign Common Grade to Class');
                   4106:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4107:         }
                   4108:     } elsif (grep(/^none$/,@sections)) {
                   4109:         @sections = ('none');
                   4110:         if ($group_display) {
                   4111:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4112:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4113:         } elsif (grep(/^none$/,@groups)) {
                   4114:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4115:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4116:         } else {
                   4117:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4118: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4119:         }
                   4120:     } else {
                   4121:         $section_display = join (", ",@sections);
                   4122:         if ($group_display) {
                   4123:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4124:                                  $section_display,$group_display);
                   4125:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4126:                                    $section_display,$group_display);
                   4127:         } elsif (grep(/^none$/,@groups)) {
                   4128:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4129:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4130:         } else {
                   4131:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4132: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4133:         }
                   4134:     }
                   4135:     my %submit_types = &substatus_options();
                   4136:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4137: 
                   4138:     if ($env{'form.submitonly'} eq 'all') {
                   4139:         $result.= '<h3>'.$common_header.'</h3>';
                   4140:     } else {
1.745     raeburn  4141:         my $text;
                   4142:         if ($is_tool) {
                   4143:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4144:         } else {
                   4145:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4146:         }
                   4147:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 4148:     }
1.738     raeburn  4149:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4150:     #radio buttons/text box for assigning points for a section or class.
                   4151:     #handles different parts of a problem
1.582     raeburn  4152:     my $res_error;
                   4153:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4154:     if ($res_error) {
                   4155:         return &navmap_errormsg();
                   4156:     }
1.42      ng       4157:     my %weight = ();
                   4158:     my $ctsparts = 0;
1.45      ng       4159:     my %seen = ();
1.745     raeburn  4160:     my @part_response_id;
                   4161:     if ($is_tool) {
                   4162:         @part_response_id = ([0,'']);
                   4163:     } else {
                   4164:         @part_response_id = &flatten_responseType($responseType);
                   4165:     }
1.375     albertel 4166:     foreach my $part_response_id (@part_response_id) {
                   4167:     	my ($partid,$respid) = @{ $part_response_id };
                   4168: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4169: 	next if $seen{$partid};
                   4170: 	$seen{$partid}++;
1.42      ng       4171: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4172: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4173: 
1.324     albertel 4174: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4175: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4176: 	my $ctr = 0;
1.42      ng       4177: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4178: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4179: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4180: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4181: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4182: 	    $ctr++;
                   4183: 	}
1.485     albertel 4184: 	$radio.='</tr></table>';
                   4185: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4186: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4187: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4188: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   4189:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4190:             '<select name="SELVAL_'.$partid.'" '.
                   4191:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   4192:                 $weight{$partid}.')"> '.
1.401     albertel 4193: 	    '<option selected="selected"> </option>'.
1.485     albertel 4194: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4195: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4196: 	    '</select></td>'.
                   4197:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4198: 	$line.='<input type="hidden" name="partid_'.
                   4199: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4200: 	$line.='<input type="hidden" name="weight_'.
                   4201: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4202: 
                   4203: 	$result.=
                   4204: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4205: 	    '<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 4206: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4207: 	$ctsparts++;
1.41      ng       4208:     }
1.474     albertel 4209:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4210: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4211:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4212: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4213: 
1.44      ng       4214:     #table listing all the students in a section/class
                   4215:     #header of table
1.738     raeburn  4216:     if ($env{'form.submitonly'} eq 'all') {
                   4217:         $result.= '<h3>'.$specific_header.'</h3>';
                   4218:     } else {
1.745     raeburn  4219:         my $text;
                   4220:         if ($is_tool) {
                   4221:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4222:         } else {
                   4223:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4224:         }
                   4225:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  4226:     }
                   4227:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4228: 	      &Apache::loncommon::start_data_table_header_row().
                   4229: 	      '<th>'.&mt('No.').'</th>'.
                   4230: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4231:     my $partserror;
                   4232:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4233:     if ($partserror) {
                   4234:         return &navmap_errormsg();
                   4235:     }
1.324     albertel 4236:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4237:     my @partids = ();
1.41      ng       4238:     foreach my $part (@parts) {
1.745     raeburn  4239: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  4240:         my $narrowtext = &mt('Tries');
                   4241: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  4242: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 4243: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4244:         push(@partids,$partid);
1.628     www      4245: #
                   4246: # FIXME: Looks like $display looks at English text
                   4247: #
1.324     albertel 4248: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4249: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4250: 	    $result.='<th>'.
1.697     bisitz   4251: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   4252: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4253: 	    next;
1.485     albertel 4254: 	    
1.207     albertel 4255: 	} else {
1.485     albertel 4256: 	    if ($display =~ /Problem Status/) {
                   4257: 		my $grade_status_mt = &mt('Grade Status');
                   4258: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4259: 	    }
                   4260: 	    my $part_mt = &mt('Part:');
                   4261: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4262: 	}
1.485     albertel 4263: 
1.474     albertel 4264: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4265:     }
1.474     albertel 4266:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4267: 
1.270     albertel 4268:     my %last_resets = 
                   4269: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4270: 
1.41      ng       4271:     #get info for each student
1.44      ng       4272:     #list all the students - with points and grade status
1.738     raeburn  4273:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4274:     my $ctr = 0;
1.294     albertel 4275:     foreach (sort 
                   4276: 	     {
                   4277: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4278: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4279: 		 }
                   4280: 		 return $a cmp $b;
                   4281: 	     } (keys(%$fullname))) {
1.324     albertel 4282: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  4283: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4284:     }
1.474     albertel 4285:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4286:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.780     raeburn  4287:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   4288: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4289:     if ($ctr == 0) {
1.442     banghart 4290:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4291:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4292:                 '<span class="LC_warning">';
                   4293:         if ($env{'form.submitonly'} eq 'all') {
                   4294:             if (grep(/^all$/,@sections)) {
                   4295:                 if (grep(/^all$/,@groups)) {
                   4296:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4297:                                    $stu_status);
                   4298:                 } elsif (grep(/^none$/,@groups)) {
                   4299:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4300:                                    $stu_status); 
                   4301:                 } else {
                   4302:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4303:                                    $group_display,$stu_status);
                   4304:                 }
                   4305:             } elsif (grep(/^none$/,@sections)) {
                   4306:                 if (grep(/^all$/,@groups)) {
                   4307:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4308:                                    $stu_status);
                   4309:                 } elsif (grep(/^none$/,@groups)) {
                   4310:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4311:                                    $stu_status);
                   4312:                 } else {
                   4313:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4314:                                    $group_display,$stu_status);
                   4315:                 }
                   4316:             } else {
                   4317:                 if (grep(/^all$/,@groups)) {
                   4318:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4319:                                    $section_display,$stu_status);
                   4320:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4321:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4322:                                    $section_display,$stu_status);
                   4323:                 } else {
                   4324:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4325:                                    $section_display,$group_display,$stu_status);
                   4326:                 }
                   4327:             }
                   4328:         } else {
                   4329:             if (grep(/^all$/,@sections)) {
                   4330:                 if (grep(/^all$/,@groups)) {
                   4331:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4332:                                    $stu_status,$submission_status);
                   4333:                 } elsif (grep(/^none$/,@groups)) {
                   4334:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4335:                                    $stu_status,$submission_status);
                   4336:                 } else {
                   4337:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4338:                                    $group_display,$stu_status,$submission_status);
                   4339:                 }
                   4340:             } elsif (grep(/^none$/,@sections)) {
                   4341:                 if (grep(/^all$/,@groups)) {
                   4342:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4343:                                    $stu_status,$submission_status);
                   4344:                 } elsif (grep(/^none$/,@groups)) {
                   4345:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4346:                                    $stu_status,$submission_status);
                   4347:                 } else {
                   4348:                     $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.',
                   4349:                                    $group_display,$stu_status,$submission_status);
                   4350:                 }
                   4351:             } else {
                   4352:                 if (grep(/^all$/,@groups)) {
                   4353: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4354: 	                           $section_display,$stu_status,$submission_status);
                   4355:                 } elsif (grep(/^none$/,@groups)) {
                   4356:                     $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.',
                   4357:                                    $section_display,$stu_status,$submission_status);
                   4358:                 } else {
                   4359:                     $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.',
                   4360:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4361:                 }
                   4362:             }
                   4363:         }
                   4364: 	$result .= '</span><br />';
1.96      albertel 4365:     }
1.41      ng       4366:     return $result;
                   4367: }
                   4368: 
1.738     raeburn  4369: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4370: sub viewstudentgrade {
1.745     raeburn  4371:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4372:     my ($uname,$udom) = split(/:/,$student);
                   4373:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4374:     my $submitonly = $env{'form.submitonly'};
                   4375:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4376:         my %partstatus = ();
                   4377:         if (ref($parts) eq 'ARRAY') {
                   4378:             foreach my $apart (@{$parts}) {
                   4379:                 my ($part,$type) = &split_part_type($apart);
                   4380:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4381:                 $status = 'nothing' if ($status eq '');
                   4382:                 $partstatus{$part}      = $status;
                   4383:                 my $subkey = "resource.$part.submitted_by";
                   4384:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4385:             }
                   4386:             my $submitted = 0;
                   4387:             my $graded = 0;
                   4388:             my $incorrect = 0;
                   4389:             foreach my $key (keys(%partstatus)) {
                   4390:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4391:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4392:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4393: 
                   4394:                 my $partid = (split(/\./,$key))[1];
                   4395:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4396:                     $submitted = 0;
                   4397:                 }
                   4398:             }
                   4399:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4400:                                        $submitonly eq 'incorrect' ||
                   4401:                                        $submitonly eq 'graded'));
                   4402:             return if (!$graded && ($submitonly eq 'graded'));
                   4403:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4404:         }
                   4405:     }
                   4406:     if ($submitonly eq 'queued') {
                   4407:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4408:         my %queue_status =
                   4409:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4410:                                                     $udom,$uname);
                   4411:         return if (!defined($queue_status{'gradingqueue'}));
                   4412:     }
                   4413:     $$ctr++;
                   4414:     my %aggregates = ();
1.474     albertel 4415:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4416: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4417: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4418: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4419: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4420: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4421:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4422:     foreach my $apart (@$parts) {
                   4423: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4424: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4425:         $result.='<td align="center">';
1.269     raeburn  4426:         my ($aggtries,$totaltries);
                   4427:         unless (exists($aggregates{$part})) {
1.270     albertel 4428: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4429: 	    $aggtries = $totaltries;
1.269     raeburn  4430:             if ($$last_resets{$part}) {  
1.270     albertel 4431:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4432: 					   $part);
                   4433:             }
1.269     raeburn  4434:             $result.='<input type="hidden" name="'.
                   4435:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4436:             $result.='<input type="hidden" name="'.
                   4437:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4438:             $aggregates{$part} = 1;
                   4439:         }
1.41      ng       4440: 	if ($type eq 'awarded') {
1.320     albertel 4441: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4442: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4443: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4444: 	    $result.='<input type="text" name="'.
1.89      albertel 4445: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4446:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4447: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4448: 	} elsif ($type eq 'solved') {
                   4449: 	    my ($status,$foo)=split(/_/,$score,2);
                   4450: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4451: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4452: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4453: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4454: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4455:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4456: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4457: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4458: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4459: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4460: 	} else {
                   4461: 	    $result.='<input type="hidden" name="'.
                   4462: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4463: 		    "\n";
1.233     albertel 4464: 	    $result.='<input type="text" name="'.
1.122     ng       4465: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4466: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4467: 	}
                   4468:     }
1.474     albertel 4469:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4470:     return $result;
1.38      ng       4471: }
                   4472: 
1.44      ng       4473: #--- change scores for all the students in a section/class
                   4474: #    record does not get update if unchanged
1.38      ng       4475: sub editgrades {
1.608     www      4476:     my ($request,$symb) = @_;
1.745     raeburn  4477:     my $toolsymb;
                   4478:     if ($symb =~ /ext\.tool$/) {
                   4479:         $toolsymb = $symb;
                   4480:     }
1.41      ng       4481: 
1.433     banghart 4482:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4483:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  4484:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4485: 
1.477     albertel 4486:     my $result= &Apache::loncommon::start_data_table().
                   4487: 	&Apache::loncommon::start_data_table_header_row().
                   4488: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4489: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4490:     my %scoreptr = (
                   4491: 		    'correct'  =>'correct_by_override',
                   4492: 		    'incorrect'=>'incorrect_by_override',
                   4493: 		    'excused'  =>'excused',
                   4494: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4495:                     'credited' =>'credit_attempted',
1.43      ng       4496: 		    'nothing'  => '',
                   4497: 		    );
1.257     albertel 4498:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4499: 
1.44      ng       4500:     my (@partid);
                   4501:     my %weight = ();
1.54      albertel 4502:     my %columns = ();
1.44      ng       4503:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4504: 
1.582     raeburn  4505:     my $partserror;
                   4506:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4507:     if ($partserror) {
                   4508:         return &navmap_errormsg();
                   4509:     }
1.54      albertel 4510:     my $header;
1.257     albertel 4511:     while ($ctr < $env{'form.totalparts'}) {
                   4512: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4513: 	push(@partid,$partid);
1.257     albertel 4514: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4515: 	$ctr++;
1.54      albertel 4516:     }
1.324     albertel 4517:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4518:     my $totcolspan = 0;
1.54      albertel 4519:     foreach my $partid (@partid) {
1.478     albertel 4520: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4521: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4522: 	$columns{$partid}=2;
                   4523: 	foreach my $stores (@parts) {
                   4524: 	    my ($part,$type) = &split_part_type($stores);
                   4525: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4526: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4527: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4528: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4529:             my $narrowtext = &mt('Tries');
                   4530: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4531: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4532: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4533: 	    $columns{$partid}+=2;
                   4534: 	}
1.748     raeburn  4535:         $totcolspan += $columns{$partid};
1.54      albertel 4536:     }
                   4537:     foreach my $partid (@partid) {
1.324     albertel 4538: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4539: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4540: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4541: 	    '</th>';
1.54      albertel 4542: 
1.44      ng       4543:     }
1.477     albertel 4544:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4545: 	&Apache::loncommon::start_data_table_header_row().
                   4546: 	$header.
                   4547: 	&Apache::loncommon::end_data_table_header_row();
                   4548:     my @noupdate;
1.126     ng       4549:     my ($updateCtr,$noupdateCtr) = (1,1);
1.786     raeburn  4550:     my ($got_types,%queueable);
1.257     albertel 4551:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4552: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4553: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4554: 	my %newrecord;
                   4555: 	my $updateflag = 0;
1.108     albertel 4556: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4557: 	my $canmodify = &canmodify($usec);
                   4558: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4559: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4560: 	if (!$canmodify) {
1.477     albertel 4561: 	    push(@noupdate,
1.748     raeburn  4562: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4563: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4564: 	    next;
                   4565: 	}
1.269     raeburn  4566:         my %aggregate = ();
                   4567:         my $aggregateflag = 0;
1.281     albertel 4568: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4569: 	foreach (@partid) {
1.257     albertel 4570: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4571: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4572: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4573: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4574: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4575: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4576: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4577: 	    my $score;
                   4578: 	    if ($partial eq '') {
1.257     albertel 4579: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4580: 	    } elsif ($partial > 0) {
                   4581: 		$score = 'correct_by_override';
                   4582: 	    } elsif ($partial == 0) {
                   4583: 		$score = 'incorrect_by_override';
                   4584: 	    }
1.257     albertel 4585: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4586: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4587: 
1.292     albertel 4588: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4589: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4590: 	    if ($dropMenu eq 'reset status' &&
                   4591: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4592: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4593: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4594: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4595: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4596: 		$updateflag = 1;
1.269     raeburn  4597:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4598:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4599:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4600:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4601:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4602:                     $aggregateflag = 1;
                   4603:                 }
1.139     albertel 4604: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4605: 		$updateflag = 1;
                   4606: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4607: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4608: 		$rec_update++;
1.125     ng       4609: 	    }
                   4610: 
1.93      albertel 4611: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4612: 		'<td align="center">'.$awarded.
                   4613: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4614: 
1.54      albertel 4615: 
                   4616: 	    my $partid=$_;
                   4617: 	    foreach my $stores (@parts) {
                   4618: 		my ($part,$type) = &split_part_type($stores);
                   4619: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4620: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4621: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4622: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4623: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4624: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4625: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4626: 		    $updateflag=1;
                   4627: 		}
1.93      albertel 4628: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4629: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4630: 	    }
1.44      ng       4631: 	}
1.477     albertel 4632: 	$line.="\n";
1.301     albertel 4633: 
                   4634: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4635: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4636: 
1.44      ng       4637: 	if ($updateflag) {
                   4638: 	    $count++;
1.257     albertel 4639: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4640: 				    $udom,$uname);
1.301     albertel 4641: 
                   4642: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4643: 					      $cnum,$udom,$uname)) {
                   4644: 		# need to figure out if should be in queue.
                   4645: 		my %record =  
                   4646: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4647: 					     $udom,$uname);
                   4648: 		my $all_graded = 1;
                   4649: 		my $none_graded = 1;
1.786     raeburn  4650:                 unless ($got_types) {
                   4651:                     my $error;
                   4652:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   4653:                     unless ($error) {
                   4654:                         foreach my $part (@parts) {
                   4655:                             if (ref($resptype->{$part}) eq 'HASH') {
                   4656:                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   4657:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   4658:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   4659:                                         $queueable{$part} = 1;
                   4660:                                         last;
                   4661:                                     }
                   4662:                                 }
                   4663:                             }
                   4664:                         }
                   4665:                     }
                   4666:                     $got_types = 1;
                   4667:                 }
1.301     albertel 4668: 		foreach my $part (@parts) {
1.786     raeburn  4669:                     if ($queueable{$part}) {
                   4670: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4671: 			    $all_graded = 0;
                   4672: 		        } else {
                   4673: 			    $none_graded = 0;
                   4674: 		        }
1.301     albertel 4675: 		    }
1.786     raeburn  4676:                 }
1.301     albertel 4677: 		if ($all_graded || $none_graded) {
                   4678: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4679: 							   $symb,$cdom,$cnum,
                   4680: 							   $udom,$uname);
                   4681: 		}
                   4682: 	    }
                   4683: 
1.477     albertel 4684: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4685: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4686: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4687: 	    $updateCtr++;
1.93      albertel 4688: 	} else {
1.477     albertel 4689: 	    push(@noupdate,
                   4690: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4691: 	    $noupdateCtr++;
1.44      ng       4692: 	}
1.269     raeburn  4693:         if ($aggregateflag) {
                   4694:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4695: 				  $cdom,$cnum);
1.269     raeburn  4696:         }
1.93      albertel 4697:     }
1.477     albertel 4698:     if (@noupdate) {
1.748     raeburn  4699:         my $numcols=$totcolspan+2;
1.477     albertel 4700: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4701: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4702: 	    &mt('No Changes Occurred For the Students Below').
                   4703: 	    '</td>'.
1.477     albertel 4704: 	    &Apache::loncommon::end_data_table_row();
                   4705: 	foreach my $line (@noupdate) {
                   4706: 	    $result.=
                   4707: 		&Apache::loncommon::start_data_table_row().
                   4708: 		$line.
                   4709: 		&Apache::loncommon::end_data_table_row();
                   4710: 	}
1.44      ng       4711:     }
1.614     www      4712:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4713:     my $msg = '<p><b>'.
                   4714: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4715: 	    $rec_update,$count).'</b><br />'.
                   4716: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4717: 	'</b></p>';
1.44      ng       4718:     return $title.$msg.$result;
1.5       albertel 4719: }
1.54      albertel 4720: 
                   4721: sub split_part_type {
                   4722:     my ($partstr) = @_;
                   4723:     my ($temp,@allparts)=split(/_/,$partstr);
                   4724:     my $type=pop(@allparts);
1.439     albertel 4725:     my $part=join('_',@allparts);
1.54      albertel 4726:     return ($part,$type);
                   4727: }
                   4728: 
1.44      ng       4729: #------------- end of section for handling grading by section/class ---------
                   4730: #
                   4731: #----------------------------------------------------------------------------
                   4732: 
1.5       albertel 4733: 
1.44      ng       4734: #----------------------------------------------------------------------------
                   4735: #
                   4736: #-------------------------- Next few routines handles grading by csv upload
                   4737: #
                   4738: #--- Javascript to handle csv upload
1.27      albertel 4739: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4740:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4741:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4742:   &js_escape(\$error1);
                   4743:   &js_escape(\$error2);
1.27      albertel 4744:   return(<<ENDPICK);
                   4745:   function verify(vf) {
                   4746:     var foundsomething=0;
                   4747:     var founduname=0;
1.243     albertel 4748:     var foundID=0;
1.743     raeburn  4749:     var foundclicker=0;
1.27      albertel 4750:     for (i=0;i<=vf.nfields.value;i++) {
                   4751:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4752:       if (i==0 && tw!=0) { foundID=1; }
                   4753:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4754:       if (i==2 && tw!=0) { foundclicker=1; }
                   4755:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4756:     }
1.743     raeburn  4757:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4758: 	alert('$error1');
                   4759: 	return;
1.27      albertel 4760:     }
                   4761:     if (foundsomething==0) {
1.246     albertel 4762: 	alert('$error2');
                   4763: 	return;
1.27      albertel 4764:     }
                   4765:     vf.submit();
                   4766:   }
                   4767:   function flip(vf,tf) {
                   4768:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4769:     var i;
                   4770:     for (i=0;i<=vf.nfields.value;i++) {
                   4771:       //can not pick the same destination field for both name and domain
                   4772:       if (((i ==0)||(i ==1)) && 
                   4773:           ((tf==0)||(tf==1)) && 
                   4774:           (i!=tf) &&
                   4775:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4776:         eval('vf.f'+i+'.selectedIndex=0;')
                   4777:       }
                   4778:     }
                   4779:   }
                   4780: ENDPICK
                   4781: }
                   4782: 
                   4783: sub csvupload_javascript_forward_associate {
1.743     raeburn  4784:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4785:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4786:   &js_escape(\$error1);
                   4787:   &js_escape(\$error2);
1.27      albertel 4788:   return(<<ENDPICK);
                   4789:   function verify(vf) {
                   4790:     var foundsomething=0;
                   4791:     var founduname=0;
1.243     albertel 4792:     var foundID=0;
1.743     raeburn  4793:     var foundclicker=0;
1.27      albertel 4794:     for (i=0;i<=vf.nfields.value;i++) {
                   4795:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4796:       if (tw==1) { foundID=1; }
                   4797:       if (tw==2) { founduname=1; }
1.745     raeburn  4798:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4799:       if (tw>4) { foundsomething=1; }
1.27      albertel 4800:     }
1.743     raeburn  4801:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4802: 	alert('$error1');
                   4803: 	return;
1.27      albertel 4804:     }
                   4805:     if (foundsomething==0) {
1.246     albertel 4806: 	alert('$error2');
                   4807: 	return;
1.27      albertel 4808:     }
                   4809:     vf.submit();
                   4810:   }
                   4811:   function flip(vf,tf) {
                   4812:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4813:     var i;
                   4814:     //can not pick the same destination field twice
                   4815:     for (i=0;i<=vf.nfields.value;i++) {
                   4816:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4817:         eval('vf.f'+i+'.selectedIndex=0;')
                   4818:       }
                   4819:     }
                   4820:   }
                   4821: ENDPICK
                   4822: }
                   4823: 
1.26      albertel 4824: sub csvuploadmap_header {
1.324     albertel 4825:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4826:     my $javascript;
1.257     albertel 4827:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4828: 	$javascript=&csvupload_javascript_reverse_associate();
                   4829:     } else {
                   4830: 	$javascript=&csvupload_javascript_forward_associate();
                   4831:     }
1.45      ng       4832: 
1.418     albertel 4833:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4834:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4835:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4836:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4837:     my $reverse=&mt("Reverse Association");
1.41      ng       4838:     $request->print(<<ENDPICK);
1.632     www      4839: <br />
                   4840: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4841: <input type="hidden" name="associate"  value="" />
                   4842: <input type="hidden" name="phase"      value="three" />
                   4843: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4844: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4845: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4846: <input type="hidden" name="upfile_associate" 
1.257     albertel 4847:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4848: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4849: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4850: <hr />
                   4851: ENDPICK
1.597     wenzelju 4852:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4853:     return '';
1.26      albertel 4854: 
                   4855: }
                   4856: 
                   4857: sub csvupload_fields {
1.582     raeburn  4858:     my ($symb,$errorref) = @_;
1.745     raeburn  4859:     my $toolsymb;
                   4860:     if ($symb =~ /ext\.tool$/) {
                   4861:         $toolsymb = $symb;
                   4862:     }
1.582     raeburn  4863:     my (@parts) = &getpartlist($symb,$errorref);
                   4864:     if (ref($errorref)) {
                   4865:         if ($$errorref) {
                   4866:             return;
                   4867:         }
                   4868:     }
                   4869: 
1.556     weissno  4870:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4871: 		['username','Student Username'],
1.743     raeburn  4872: 		['clicker','Clicker ID'],
1.243     albertel 4873: 		['domain','Student Domain']);
1.324     albertel 4874:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4875:     foreach my $part (sort(@parts)) {
                   4876: 	my @datum;
1.745     raeburn  4877: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4878: 	my $name=$part;
1.745     raeburn  4879: 	if (!$display) { $display = $name; }
1.41      ng       4880: 	@datum=($name,$display);
1.244     albertel 4881: 	if ($name=~/^stores_(.*)_awarded/) {
                   4882: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4883: 	}
1.41      ng       4884: 	push(@fields,\@datum);
                   4885:     }
                   4886:     return (@fields);
1.26      albertel 4887: }
                   4888: 
                   4889: sub csvuploadmap_footer {
1.41      ng       4890:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4891:     my $buttontext = &mt('Assign Grades');
1.41      ng       4892:     $request->print(<<ENDPICK);
1.26      albertel 4893: </table>
                   4894: <input type="hidden" name="nfields" value="$i" />
                   4895: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4896: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4897: </form>
                   4898: ENDPICK
                   4899: }
                   4900: 
1.283     albertel 4901: sub checkforfile_js {
1.638     www      4902:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4903:     &js_escape(\$alertmsg);
1.597     wenzelju 4904:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4905:     function checkUpload(formname) {
                   4906: 	if (formname.upfile.value == "") {
1.539     riegler  4907: 	    alert("$alertmsg");
1.86      ng       4908: 	    return false;
                   4909: 	}
                   4910: 	formname.submit();
                   4911:     }
                   4912: CSVFORMJS
1.283     albertel 4913:     return $result;
                   4914: }
                   4915: 
                   4916: sub upcsvScores_form {
1.608     www      4917:     my ($request,$symb) = @_;
1.283     albertel 4918:     if (!$symb) {return '';}
                   4919:     my $result=&checkforfile_js();
1.632     www      4920:     $result.=&Apache::loncommon::start_data_table().
                   4921:              &Apache::loncommon::start_data_table_header_row().
                   4922:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4923:              &Apache::loncommon::end_data_table_header_row().
                   4924:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4925:     my $upload=&mt("Upload Scores");
1.86      ng       4926:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4927:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4928:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4929:     $result.=<<ENDUPFORM;
1.106     albertel 4930: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4931: <input type="hidden" name="symb" value="$symb" />
                   4932: <input type="hidden" name="command" value="csvuploadmap" />
                   4933: $upfile_select
1.589     bisitz   4934: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4935: </form>
                   4936: ENDUPFORM
1.370     www      4937:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4938:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4939:              '</td>'.
                   4940:             &Apache::loncommon::end_data_table_row().
                   4941:             &Apache::loncommon::end_data_table();
1.86      ng       4942:     return $result;
                   4943: }
                   4944: 
                   4945: 
1.26      albertel 4946: sub csvuploadmap {
1.768     raeburn  4947:     my ($request,$symb) = @_;
1.41      ng       4948:     if (!$symb) {return '';}
1.72      ng       4949: 
1.41      ng       4950:     my $datatoken;
1.257     albertel 4951:     if (!$env{'form.datatoken'}) {
1.41      ng       4952: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4953:     } else {
1.742     raeburn  4954: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4955:         if ($datatoken ne '') {
                   4956: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4957:         }
1.26      albertel 4958:     }
1.41      ng       4959:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4960:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4961:     my ($i,$keyfields);
                   4962:     if (@records) {
1.582     raeburn  4963:         my $fieldserror;
                   4964: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4965:         if ($fieldserror) {
                   4966:             $request->print(&navmap_errormsg());
                   4967:             return;
                   4968:         }
1.257     albertel 4969: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4970: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4971: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4972: 							  \@fields);
                   4973: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4974: 	    chop($keyfields);
                   4975: 	} else {
                   4976: 	    unshift(@fields,['none','']);
                   4977: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4978: 							    \@fields);
1.311     banghart 4979:             foreach my $rec (@records) {
                   4980:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4981:                 if (%temp) {
                   4982:                     $keyfields=join(',',sort(keys(%temp)));
                   4983:                     last;
                   4984:                 }
                   4985:             }
1.41      ng       4986: 	}
                   4987:     }
                   4988:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4989: 
1.41      ng       4990:     return '';
1.27      albertel 4991: }
                   4992: 
1.246     albertel 4993: sub csvuploadoptions {
1.608     www      4994:     my ($request,$symb)= @_;
1.632     www      4995:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4996:     $request->print(<<ENDPICK);
                   4997: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4998: <input type="hidden" name="command"    value="csvuploadassign" />
                   4999: <p>
                   5000: <label>
                   5001:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      5002:    $overwrite
1.246     albertel 5003: </label>
                   5004: </p>
                   5005: ENDPICK
                   5006:     my %fields=&get_fields();
                   5007:     if (!defined($fields{'domain'})) {
1.257     albertel 5008: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      5009: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 5010:     }
1.257     albertel 5011:     foreach my $key (sort(keys(%env))) {
1.246     albertel 5012: 	if ($key !~ /^form\.(.*)$/) { next; }
                   5013: 	my $cleankey=$1;
                   5014: 	if ($cleankey eq 'command') { next; }
                   5015: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 5016: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 5017:     }
                   5018:     # FIXME do a check for any duplicated user ids...
                   5019:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   5020:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 5021: <hr /></form>'."\n");
1.246     albertel 5022:     return '';
                   5023: }
                   5024: 
                   5025: sub get_fields {
                   5026:     my %fields;
1.257     albertel 5027:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   5028:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   5029: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   5030: 	    if ($env{'form.f'.$i} ne 'none') {
                   5031: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       5032: 	    }
                   5033: 	} else {
1.257     albertel 5034: 	    if ($env{'form.f'.$i} ne 'none') {
                   5035: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       5036: 	    }
                   5037: 	}
1.27      albertel 5038:     }
1.246     albertel 5039:     return %fields;
                   5040: }
                   5041: 
                   5042: sub csvuploadassign {
1.766     raeburn  5043:     my ($request,$symb) = @_;
1.246     albertel 5044:     if (!$symb) {return '';}
1.345     bowersj2 5045:     my $error_msg = '';
1.742     raeburn  5046:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5047:     if ($datatoken ne '') { 
                   5048:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5049:     }
1.246     albertel 5050:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   5051:     my %fields=&get_fields();
1.257     albertel 5052:     my $courseid=$env{'request.course.id'};
1.97      albertel 5053:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 5054:     my @notallowed;
1.41      ng       5055:     my @skipped;
1.657     raeburn  5056:     my @warnings;
1.41      ng       5057:     my $countdone=0;
                   5058:     foreach my $grade (@gradedata) {
                   5059: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 5060: 	my $domain;
                   5061: 	if ($entries{$fields{'domain'}}) {
                   5062: 	    $domain=$entries{$fields{'domain'}};
                   5063: 	} else {
1.257     albertel 5064: 	    $domain=$env{'form.default_domain'};
1.246     albertel 5065: 	}
1.243     albertel 5066: 	$domain=~s/\s//g;
1.41      ng       5067: 	my $username=$entries{$fields{'username'}};
1.160     albertel 5068: 	$username=~s/\s//g;
1.243     albertel 5069: 	if (!$username) {
                   5070: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 5071: 	    $id=~s/\s//g;
1.737     raeburn  5072:             if ($id ne '') {
                   5073: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   5074: 	        $username=$ids{$id};
                   5075:             } else {
                   5076:                 if ($entries{$fields{'clicker'}}) {
                   5077:                     my $clicker = $entries{$fields{'clicker'}};
                   5078:                     $clicker=~s/\s//g;
                   5079:                     if ($clicker ne '') {
                   5080:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   5081:                         if ($clickers{$clicker} ne '') {  
                   5082:                             my $match = 0;
                   5083:                             my @inclass;
                   5084:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   5085:                                 if (exists($$classlist{"$poss:$domain"})) {
                   5086:                                     $username = $poss;
                   5087:                                     push(@inclass,$poss);
                   5088:                                     $match ++;
                   5089:                                     
                   5090:                                 }
                   5091:                             }
                   5092:                             if ($match > 1) {
                   5093:                                 undef($username); 
                   5094:                                 $request->print('<p class="LC_warning">'.
                   5095:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   5096:                                                 $clicker,join(', ',@inclass)).'</p>');
                   5097:                             }
                   5098:                         }
                   5099:                     }
                   5100:                 }
                   5101:             }
1.243     albertel 5102: 	}
1.41      ng       5103: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 5104: 	    my $id=$entries{$fields{'ID'}};
                   5105: 	    $id=~s/\s//g;
1.737     raeburn  5106:             my $clicker = $entries{$fields{'clicker'}};
                   5107:             $clicker=~s/\s//g;
                   5108:             if ($clicker) {
                   5109:                 push(@skipped,"$clicker:$domain");
                   5110: 	    } elsif ($id) {
1.247     albertel 5111: 		push(@skipped,"$id:$domain");
                   5112: 	    } else {
                   5113: 		push(@skipped,"$username:$domain");
                   5114: 	    }
1.41      ng       5115: 	    next;
                   5116: 	}
1.108     albertel 5117: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 5118: 	if (!&canmodify($usec)) {
                   5119: 	    push(@notallowed,"$username:$domain");
                   5120: 	    next;
                   5121: 	}
1.244     albertel 5122: 	my %points;
1.41      ng       5123: 	my %grades;
                   5124: 	foreach my $dest (keys(%fields)) {
1.244     albertel 5125: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   5126: 		$dest eq 'domain') { next; }
                   5127: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   5128: 	    if ($dest=~/stores_(.*)_points/) {
                   5129: 		my $part=$1;
                   5130: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   5131: 					      $symb,$domain,$username);
1.345     bowersj2 5132:                 if ($wgt) {
                   5133:                     $entries{$fields{$dest}}=~s/\s//g;
                   5134:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5135:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5136:                                           : 'correct_by_override';
1.638     www      5137:                     if ($pcr>1) {
1.657     raeburn  5138:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      5139:                     }
1.345     bowersj2 5140:                     $grades{"resource.$part.awarded"}=$pcr;
                   5141:                     $grades{"resource.$part.solved"}=$award;
                   5142:                     $points{$part}=1;
                   5143:                 } else {
                   5144:                     $error_msg = "<br />" .
                   5145:                         &mt("Some point values were assigned"
                   5146:                             ." for problems with a weight "
                   5147:                             ."of zero. These values were "
                   5148:                             ."ignored.");
                   5149:                 }
1.244     albertel 5150: 	    } else {
                   5151: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5152: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5153: 		my $store_key=$dest;
                   5154: 		$store_key=~s/^stores/resource/;
                   5155: 		$store_key=~s/_/\./g;
                   5156: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5157: 	    }
1.41      ng       5158: 	}
1.766     raeburn  5159: 	if (! %grades) {
1.508     www      5160:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5161:         } else {
                   5162: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5163: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5164: 					   $env{'request.course.id'},
                   5165: 					   $domain,$username);
1.508     www      5166: 	   if ($result eq 'ok') {
1.627     www      5167: # Successfully stored
1.508     www      5168: 	      $request->print('.');
1.627     www      5169: # Remove from grading queue
                   5170:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5171:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5172:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5173:                                              $domain,$username);
                   5174:               $countdone++;
                   5175:            } else {
1.508     www      5176: 	      $request->print("<p><span class=\"LC_error\">".
                   5177:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5178:                                   "$username:$domain",$result)."</span></p>");
                   5179: 	   }
                   5180: 	   $request->rflush();
                   5181:         }
1.41      ng       5182:     }
1.570     www      5183:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  5184:     if (@warnings) {
                   5185:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5186:         $request->print(join(', ',@warnings));
                   5187:     }
1.41      ng       5188:     if (@skipped) {
1.571     www      5189: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5190:         $request->print(join(', ',@skipped));
1.106     albertel 5191:     }
                   5192:     if (@notallowed) {
1.571     www      5193: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5194: 	$request->print(join(', ',@notallowed));
1.41      ng       5195:     }
1.106     albertel 5196:     $request->print("<br />\n");
1.345     bowersj2 5197:     return $error_msg;
1.26      albertel 5198: }
1.44      ng       5199: #------------- end of section for handling csv file upload ---------
                   5200: #
                   5201: #-------------------------------------------------------------------
                   5202: #
1.122     ng       5203: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5204: #
                   5205: #--- Select a page/sequence and a student to grade
1.68      ng       5206: sub pickStudentPage {
1.608     www      5207:     my ($request,$symb) = @_;
1.68      ng       5208: 
1.539     riegler  5209:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  5210:     &js_escape(\$alertmsg);
1.597     wenzelju 5211:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5212: 
                   5213: function checkPickOne(formname) {
1.76      ng       5214:     if (radioSelection(formname.student) == null) {
1.539     riegler  5215: 	alert("$alertmsg");
1.68      ng       5216: 	return;
                   5217:     }
1.125     ng       5218:     ptr = pullDownSelection(formname.selectpage);
                   5219:     formname.page.value = formname["page"+ptr].value;
                   5220:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5221:     formname.submit();
                   5222: }
                   5223: 
                   5224: LISTJAVASCRIPT
1.118     ng       5225:     &commonJSfunctions($request);
1.608     www      5226: 
1.257     albertel 5227:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5228:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5229:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  5230:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5231: 
1.398     albertel 5232:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5233: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5234: 
1.80      ng       5235:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5236:     my $map_error;
                   5237:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5238:     if ($map_error) {
                   5239:         $request->print(&navmap_errormsg());
                   5240:         return; 
                   5241:     }
1.137     albertel 5242:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5243: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5244: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   5245: 
                   5246:     # Collection of hidden fields
1.70      ng       5247:     my $ctr=0;
1.68      ng       5248:     foreach (@$titles) {
1.700     bisitz   5249:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5250:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5251:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5252:         $ctr++;
1.68      ng       5253:     }
1.700     bisitz   5254:     $result.='<input type="hidden" name="page" />'."\n".
                   5255:         '<input type="hidden" name="title" />'."\n";
                   5256: 
                   5257:     $result.=&build_section_inputs();
                   5258:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5259:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   5260: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   5261: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 5262: 
1.700     bisitz   5263:     # Show grading options
                   5264:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5265:     my $select = '<select name="selectpage">'."\n";
1.70      ng       5266:     $ctr=0;
                   5267:     foreach (@$titles) {
                   5268: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   5269: 	$select.='<option value="'.$ctr.'"'.
                   5270: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5271: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       5272: 	$ctr++;
                   5273:     }
1.700     bisitz   5274:     $select.= '</select>';
1.68      ng       5275: 
1.700     bisitz   5276:     $result.=
                   5277:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5278:        .$select
                   5279:        .&Apache::lonhtmlcommon::row_closure();
                   5280: 
                   5281:     $result.=
                   5282:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5283:        .'<label><input type="radio" name="vProb" value="no"'
                   5284:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5285:        .'<label><input type="radio" name="vProb" value="yes" />'
                   5286:            .&mt('yes').'</label>'."\n"
                   5287:        .&Apache::lonhtmlcommon::row_closure();
                   5288: 
                   5289:     $result.=
                   5290:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5291:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5292:            .&mt('none').' </label>'."\n"
                   5293:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5294:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5295:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5296:            .&mt('all submissions with details').' </label>'
                   5297:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 5298:     
1.700     bisitz   5299:     $result.=
                   5300:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5301:        .'<input type="text" name="CODE" value="" />'
                   5302:        .&Apache::lonhtmlcommon::row_closure(1)
                   5303:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5304: 
1.700     bisitz   5305:     # Show list of students to select for grading
                   5306:     $result.='<br /><input type="button" '.
1.589     bisitz   5307:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5308: 
1.68      ng       5309:     $request->print($result);
                   5310: 
1.485     albertel 5311:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5312: 	&Apache::loncommon::start_data_table().
                   5313: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5314: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5315: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5316: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5317: 	'<th>'.&nameUserString('header').'</th>'.
                   5318: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5319:  
1.761     raeburn  5320:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5321:     my $ptr = 1;
1.294     albertel 5322:     foreach my $student (sort 
                   5323: 			 {
                   5324: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5325: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5326: 			     }
                   5327: 			     return $a cmp $b;
                   5328: 			 } (keys(%$fullname))) {
1.68      ng       5329: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5330: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5331:                                   : '</td>');
1.126     ng       5332: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5333: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5334: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5335: 	$studentTable.=
                   5336: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5337:                          : '');
1.68      ng       5338: 	$ptr++;
                   5339:     }
1.484     albertel 5340:     if ($ptr%2 == 0) {
                   5341: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5342: 	    &Apache::loncommon::end_data_table_row();
                   5343:     }
                   5344:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5345:     $studentTable.='<input type="button" '.
1.589     bisitz   5346:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5347: 
                   5348:     $request->print($studentTable);
                   5349: 
                   5350:     return '';
                   5351: }
                   5352: 
                   5353: sub getSymbMap {
1.582     raeburn  5354:     my ($map_error) = @_;
1.132     bowersj2 5355:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5356:     unless (ref($navmap)) {
                   5357:         if (ref($map_error)) {
                   5358:             $$map_error = 'navmap';
                   5359:         }
                   5360:         return;
                   5361:     }
1.68      ng       5362:     my %symbx = ();
                   5363:     my @titles = ();
1.117     bowersj2 5364:     my $minder = 0;
                   5365: 
                   5366:     # Gather every sequence that has problems.
1.240     albertel 5367:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5368: 					       1,0,1);
1.117     bowersj2 5369:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5370: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5371: 	    my $title = $minder.'.'.
                   5372: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5373: 	    push(@titles, $title); # minder in case two titles are identical
                   5374: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5375: 	    $minder++;
1.241     albertel 5376: 	}
1.68      ng       5377:     }
                   5378:     return \@titles,\%symbx;
                   5379: }
                   5380: 
1.72      ng       5381: #
                   5382: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5383: sub displayPage {
1.608     www      5384:     my ($request,$symb) = @_;
1.257     albertel 5385:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5386:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5387:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5388:     my $pageTitle = $env{'form.page'};
1.103     albertel 5389:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5390:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5391:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5392: 
                   5393:     #need to make sure we have the correct data for later EXT calls, 
                   5394:     #thus invalidate the cache
                   5395:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5396:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5397:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5398:     &Apache::lonnet::clear_EXT_cache_status();
                   5399: 
1.103     albertel 5400:     if (!&canview($usec)) {
1.712     bisitz   5401:         $request->print(
                   5402:             '<span class="LC_warning">'.
                   5403:             &mt('Unable to view requested student. ([_1])',
                   5404:                     $env{'form.student'}).
                   5405:             '</span>');
                   5406:         return;
1.103     albertel 5407:     }
1.398     albertel 5408:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5409:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5410: 	'</h3>'."\n";
1.500     albertel 5411:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5412:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5413: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5414:     } else {
                   5415: 	delete($env{'form.CODE'});
                   5416:     }
1.71      ng       5417:     &sub_page_js($request);
                   5418:     $request->print($result);
                   5419: 
1.132     bowersj2 5420:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5421:     unless (ref($navmap)) {
                   5422:         $request->print(&navmap_errormsg());
                   5423:         return;
                   5424:     }
1.257     albertel 5425:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5426:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5427:     if (!$map) {
1.485     albertel 5428: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5429: 	return; 
                   5430:     }
1.68      ng       5431:     my $iterator = $navmap->getIterator($map->map_start(),
                   5432: 					$map->map_finish());
                   5433: 
1.71      ng       5434:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5435: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5436: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5437: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5438: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5439: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5440: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5441: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5442: 
1.382     albertel 5443:     if (defined($env{'form.CODE'})) {
                   5444: 	$studentTable.=
                   5445: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5446:     }
1.381     albertel 5447:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5448: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5449: 
1.594     bisitz   5450:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5451:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5452:         '</span>'."\n".
1.484     albertel 5453: 	&Apache::loncommon::start_data_table().
                   5454: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5455: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5456: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5457: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5458: 
1.329     albertel 5459:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5460:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5461:     $iterator->next(); # skip the first BEGIN_MAP
                   5462:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5463:     while ($depth > 0) {
1.68      ng       5464:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5465:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5466: 
1.745     raeburn  5467:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5468: 	    my $parts = $curRes->parts();
1.68      ng       5469:             my $title = $curRes->compTitle();
1.71      ng       5470: 	    my $symbx = $curRes->symb();
1.746     raeburn  5471:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5472: 	    $studentTable.=
                   5473: 		&Apache::loncommon::start_data_table_row().
                   5474: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5475: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5476: 		                        : '<br />('.&mt('[_1]parts',
                   5477: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5478: 		 ).
                   5479: 		 '</td>';
1.71      ng       5480: 	    $studentTable.='<td valign="top">';
1.382     albertel 5481: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5482:             if ($is_tool) {
                   5483:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5484:             } else {
1.745     raeburn  5485: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5486: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5487: 					         undef,'both',\%form);
                   5488: 	        } else {
                   5489: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5490: 		    $companswer =~ s|<form(.*?)>||g;
                   5491: 		    $companswer =~ s|</form>||g;
                   5492: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5493: #		        $companswer =~ s/$1/ /ms;
                   5494: #		        $request->print('match='.$1."<br />\n");
                   5495: #		    }
                   5496: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5497: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5498: 		}
1.71      ng       5499: 	    }
                   5500: 
1.257     albertel 5501: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5502: 
1.257     albertel 5503: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5504: 		if ($record{'version'} eq '') {
1.745     raeburn  5505:                     my $msg = &mt('No recorded submission for this problem.');
                   5506:                     if ($is_tool) {
                   5507:                         $msg = &mt('No recorded transactions for this external tool');
                   5508:                     }
                   5509: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5510: 		} else {
1.116     ng       5511: 		    my %responseType = ();
                   5512: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5513: 			my @responseIds =$curRes->responseIds($partid);
                   5514: 			my @responseType =$curRes->responseType($partid);
                   5515: 			my %responseIds;
                   5516: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5517: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5518: 			}
                   5519: 			$responseType{$partid} = \%responseIds;
1.116     ng       5520: 		    }
1.148     albertel 5521: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5522: 		}
1.257     albertel 5523: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5524: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5525:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5526: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5527: 									$env{'request.course.id'},
1.726     raeburn  5528: 									'','.submission',undef,
                   5529:                                                                         $usec,$identifier);
1.71      ng       5530:  
                   5531: 	    }
1.103     albertel 5532: 	    if (&canmodify($usec)) {
1.585     bisitz   5533:             $studentTable.=&gradeBox_start();
1.103     albertel 5534: 		foreach my $partid (@{$parts}) {
                   5535: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5536: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5537: 		    $question++;
                   5538: 		}
1.585     bisitz   5539:             $studentTable.=&gradeBox_end();
1.196     albertel 5540: 		$prob++;
1.71      ng       5541: 	    }
                   5542: 	    $studentTable.='</td></tr>';
1.68      ng       5543: 
1.103     albertel 5544: 	}
1.68      ng       5545:         $curRes = $iterator->next();
                   5546:     }
1.780     raeburn  5547:     my $disabled;
                   5548:     unless (&canmodify($usec)) {
                   5549:         $disabled = ' disabled="disabled"';
                   5550:     }
1.68      ng       5551: 
1.589     bisitz   5552:     $studentTable.=
                   5553:         '</table>'."\n".
1.780     raeburn  5554:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5555:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5556:         '</form>'."\n";
1.71      ng       5557:     $request->print($studentTable);
                   5558: 
                   5559:     return '';
1.119     ng       5560: }
                   5561: 
                   5562: sub displaySubByDates {
1.148     albertel 5563:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5564:     my $isCODE=0;
1.335     albertel 5565:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5566:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5567:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5568:     my $studentTable=&Apache::loncommon::start_data_table().
                   5569: 	&Apache::loncommon::start_data_table_header_row().
                   5570: 	'<th>'.&mt('Date/Time').'</th>'.
                   5571: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5572:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5573: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5574: 	'<th>'.&mt('Status').'</th>'.
                   5575: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5576:     my ($version);
                   5577:     my %mark;
1.148     albertel 5578:     my %orders;
1.119     ng       5579:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5580:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5581:         if ($is_tool) {
                   5582:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5583:         } else {
                   5584:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5585:         }
1.147     albertel 5586:     }
1.335     albertel 5587: 
                   5588:     my $interaction;
1.525     raeburn  5589:     my $no_increment = 1;
1.735     raeburn  5590:     my (%lastrndseed,%lasttype);
1.119     ng       5591:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5592: 	my $timestamp = 
                   5593: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5594: 	if (exists($$record{$version.':resource.0.version'})) {
                   5595: 	    $interaction = $$record{$version.':resource.0.version'};
                   5596: 	}
1.671     raeburn  5597:         if ($isTask && $env{'form.previousversion'}) {
                   5598:             next unless ($interaction == $env{'form.previousversion'});
                   5599:         }
1.335     albertel 5600: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5601: 		             : "$version:resource");
1.467     albertel 5602: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5603: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5604: 	if ($isCODE) {
                   5605: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5606: 	}
1.671     raeburn  5607:         if ($isTask) {
                   5608:             $studentTable.='<td>'.$interaction.'</td>';
                   5609:         }
1.119     ng       5610: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5611: 	my @displaySub = ();
                   5612: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5613:             my ($hidden,$type);
                   5614:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5615:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5616:                 $hidden = 1;
                   5617:             }
1.749     raeburn  5618:             my @matchKey;
                   5619:             if ($isTask) {
1.769     raeburn  5620:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  5621:             } elsif ($is_tool) {
1.769     raeburn  5622:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  5623:             } else {
1.769     raeburn  5624:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  5625:             }
1.122     ng       5626: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5627: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5628: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5629: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5630: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5631:                     if ($is_tool) {
                   5632:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5633:                     } else {
1.749     raeburn  5634: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5635: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5636:                         $displaySub[0].='<span class="LC_nobreak">';
                   5637:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5638:                                        .' <span class="LC_internal_info">'
                   5639:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5640:                                        .'</span>'
                   5641:                                        .' <b>';
                   5642:                         if ($hidden) {
                   5643:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5644:                         } else {
                   5645:                             my ($trial,$rndseed,$newvariation);
                   5646:                             if ($type eq 'randomizetry') {
                   5647:                                 $trial = $$record{"$where.$partid.tries"};
                   5648:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5649:                             }
                   5650: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5651: 			        $displaySub[0].=&mt('Trial not counted');
                   5652: 		            } else {
                   5653: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5654: 					        $$record{"$where.$partid.tries"});
                   5655:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5656:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5657:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5658:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5659:                                     }
1.640     raeburn  5660:                                 }
1.749     raeburn  5661:                                 $lastrndseed{$partid} = $rndseed;
                   5662:                                 $lasttype{$partid} = $type;
                   5663: 		            }
                   5664: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5665:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5666: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5667: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5668: 			        $orders{$partid}->{$responseId}=
                   5669: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5670:                                                $no_increment,$type,$trial,$rndseed);
                   5671: 		            }
                   5672: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5673: 		            $displaySub[0].='&nbsp; '.
                   5674: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5675:                         }
1.596     raeburn  5676:                     }
1.147     albertel 5677: 		}
                   5678: 	    }
1.335     albertel 5679: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5680: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5681: 				    $$record{"$where.$partid.checkedin"},
                   5682: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5683: 					'<br />';
1.335     albertel 5684: 	    }
                   5685: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5686: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5687: 		    lc($$record{"$where.$partid.award"}).' '.
                   5688: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5689: 		    '<br />';
1.749     raeburn  5690: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5691: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5692: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5693: 		}
1.147     albertel 5694: 	    }
1.335     albertel 5695: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5696: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5697: 		unless ($is_tool) {
                   5698: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5699: 		}
1.335     albertel 5700: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5701: 		$displaySub[2].=
1.749     raeburn  5702: 		    $$record{"$version:resource.$partid.regrader"};
                   5703:                 unless ($is_tool) {
                   5704: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5705:                 }
1.147     albertel 5706: 	    }
                   5707: 	}
                   5708: 	# needed because old essay regrader has not parts info
                   5709: 	if (exists $$record{"$version:resource.regrader"}) {
                   5710: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5711: 	}
                   5712: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5713: 	if ($displaySub[2]) {
1.467     albertel 5714: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5715: 	}
1.467     albertel 5716: 	$studentTable.='&nbsp;</td>'.
                   5717: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5718:     }
1.467     albertel 5719:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5720:     return $studentTable;
1.71      ng       5721: }
                   5722: 
                   5723: sub updateGradeByPage {
1.608     www      5724:     my ($request,$symb) = @_;
1.71      ng       5725: 
1.257     albertel 5726:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5727:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5728:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5729:     my $pageTitle = $env{'form.page'};
1.103     albertel 5730:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5731:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5732:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5733:     if (!&canmodify($usec)) {
1.526     raeburn  5734: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5735: 	return;
                   5736:     }
1.398     albertel 5737:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5738:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5739: 	'</h3>'."\n";
1.70      ng       5740: 
1.68      ng       5741:     $request->print($result);
                   5742: 
1.582     raeburn  5743: 
1.132     bowersj2 5744:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5745:     unless (ref($navmap)) {
                   5746:         $request->print(&navmap_errormsg());
                   5747:         return;
                   5748:     }
1.257     albertel 5749:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5750:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5751:     if (!$map) {
1.527     raeburn  5752: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5753: 	return; 
                   5754:     }
1.71      ng       5755:     my $iterator = $navmap->getIterator($map->map_start(),
                   5756: 					$map->map_finish());
1.70      ng       5757: 
1.484     albertel 5758:     my $studentTable=
                   5759: 	&Apache::loncommon::start_data_table().
                   5760: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5761: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5762: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5763: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5764: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5765: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5766: 
                   5767:     $iterator->next(); # skip the first BEGIN_MAP
                   5768:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5769:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5770:     while ($depth > 0) {
1.71      ng       5771:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5772:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5773: 
1.385     albertel 5774:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5775: 	    my $parts = $curRes->parts();
1.71      ng       5776:             my $title = $curRes->compTitle();
                   5777: 	    my $symbx = $curRes->symb();
1.484     albertel 5778: 	    $studentTable.=
                   5779: 		&Apache::loncommon::start_data_table_row().
                   5780: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5781: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5782:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5783: 		.')').'</td>';
1.71      ng       5784: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5785: 
                   5786: 	    my %newrecord=();
                   5787: 	    my @displayPts=();
1.269     raeburn  5788:             my %aggregate = ();
                   5789:             my $aggregateflag = 0;
1.787     raeburn  5790:             my %queueable;
1.726     raeburn  5791:             if ($env{'form.HIDE'.$prob}) {
                   5792:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5793:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5794:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5795:                 $hideflag += $numchgs;
                   5796:             }
1.71      ng       5797: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5798: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5799: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.787     raeburn  5800:                 my @types = $curRes->responseType($partid);
1.786     raeburn  5801:                 if (grep(/^essay$/,@types)) {
                   5802:                     $queueable{$partid} = 1;
                   5803:                 } else {
1.787     raeburn  5804:                     my @ids = $curRes->responseIds($partid);
1.786     raeburn  5805:                     for (my $i=0; $i < scalar(@ids); $i++) {
1.787     raeburn  5806:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
1.786     raeburn  5807:                                                           '.handgrade',$symb);
                   5808:                         if (lc($hndgrd) eq 'yes') {
                   5809:                             $queueable{$partid} = 1;
                   5810:                             last;
                   5811:                         }
                   5812:                     }
                   5813:                 }
1.257     albertel 5814: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5815: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5816: 		my $partial = $newpts/$wgt;
                   5817: 		my $score;
                   5818: 		if ($partial > 0) {
                   5819: 		    $score = 'correct_by_override';
1.125     ng       5820: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5821: 		    $score = 'incorrect_by_override';
                   5822: 		}
1.257     albertel 5823: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5824: 		if ($dropMenu eq 'excused') {
1.71      ng       5825: 		    $partial = '';
                   5826: 		    $score = 'excused';
1.125     ng       5827: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5828: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5829: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5830: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5831: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5832: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5833: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5834: 		    $changeflag++;
                   5835: 		    $newpts = '';
1.269     raeburn  5836:                     
                   5837:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5838:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5839:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5840:                     if ($aggtries > 0) {
                   5841:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5842:                         $aggregateflag = 1;
                   5843:                     }
1.71      ng       5844: 		}
1.324     albertel 5845: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5846: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5847: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5848: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5849: 		    '&nbsp;<br />';
1.526     raeburn  5850: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5851: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5852: 		    '&nbsp;<br />';
1.71      ng       5853: 		$question++;
1.380     albertel 5854: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5855: 
1.71      ng       5856: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5857: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5858: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5859: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5860: 
                   5861: 		$changeflag++;
                   5862: 	    }
                   5863: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5864: 		my %record = 
                   5865: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5866: 					     $udom,$uname);
                   5867: 
                   5868: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5869: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5870: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5871: 		    $newrecord{'resource.CODE'} = '';
                   5872: 		}
1.257     albertel 5873: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5874: 					$udom,$uname);
1.382     albertel 5875: 		%record = &Apache::lonnet::restore($symbx,
                   5876: 						   $env{'request.course.id'},
                   5877: 						   $udom,$uname);
1.380     albertel 5878: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.786     raeburn  5879: 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       5880: 	    }
1.380     albertel 5881: 	    
1.269     raeburn  5882:             if ($aggregateflag) {
                   5883:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5884:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5885:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5886:             }
1.125     ng       5887: 
1.71      ng       5888: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5889: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5890: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5891: 
1.196     albertel 5892: 	    $prob++;
1.68      ng       5893: 	}
1.71      ng       5894:         $curRes = $iterator->next();
1.68      ng       5895:     }
1.98      albertel 5896: 
1.484     albertel 5897:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5898:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5899: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5900: 		  $changeflag).'<br />');
                   5901:     my $hidemsg=($hideflag == 0 ? '' :
                   5902:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5903:                      $hideflag).'<br />');
                   5904:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5905: 
1.70      ng       5906:     return '';
                   5907: }
                   5908: 
1.72      ng       5909: #-------- end of section for handling grading by page/sequence ---------
                   5910: #
                   5911: #-------------------------------------------------------------------
                   5912: 
1.581     www      5913: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5914: #
                   5915: #------ start of section for handling grading by page/sequence ---------
                   5916: 
1.423     albertel 5917: =pod
                   5918: 
                   5919: =head1 Bubble sheet grading routines
                   5920: 
1.424     albertel 5921:   For this documentation:
                   5922: 
                   5923:    'scanline' refers to the full line of characters
                   5924:    from the file that we are parsing that represents one entire sheet
                   5925: 
                   5926:    'bubble line' refers to the data
1.659     raeburn  5927:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5928: 
                   5929: 
1.659     raeburn  5930: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5931: into a course. When a user wants to grade, they select a
1.659     raeburn  5932: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5933: one of the predefined configurations for what each scanline looks
                   5934: like.
                   5935: 
                   5936: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5937: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5938: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5939: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5940: invalid student/employee ID
1.424     albertel 5941: 
                   5942: If the CODE option is used that determines the randomization of the
1.556     weissno  5943: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5944: username:domain.
                   5945: 
                   5946: During the validation phase the instructor can choose to skip scanlines. 
                   5947: 
1.659     raeburn  5948: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5949: 
                   5950:   scantron_original_filename (unmodified original file)
                   5951:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5952:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5953: 
                   5954: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5955: correction information that isn't representable in the bubblesheet
1.424     albertel 5956: file (see &scantron_getfile() for more information)
                   5957: 
                   5958: After all scanlines are either valid, marked as valid or skipped, then
                   5959: foreach line foreach problem in the picked sequence, an ssi request is
                   5960: made that simulates a user submitting their selected letter(s) against
                   5961: the homework problem.
1.423     albertel 5962: 
                   5963: =over 4
                   5964: 
                   5965: 
                   5966: 
                   5967: =item defaultFormData
                   5968: 
                   5969:   Returns html hidden inputs used to hold context/default values.
                   5970: 
                   5971:  Arguments:
                   5972:   $symb - $symb of the current resource 
                   5973: 
                   5974: =cut
1.422     foxr     5975: 
1.81      albertel 5976: sub defaultFormData {
1.324     albertel 5977:     my ($symb)=@_;
1.766     raeburn  5978:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5979: }
                   5980: 
1.447     foxr     5981: 
1.423     albertel 5982: =pod 
                   5983: 
                   5984: =item getSequenceDropDown
                   5985: 
                   5986:    Return html dropdown of possible sequences to grade
                   5987:  
                   5988:  Arguments:
1.582     raeburn  5989:    $symb - $symb of the current resource
                   5990:    $map_error - ref to scalar which will container error if
                   5991:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5992: 
                   5993: =cut
1.422     foxr     5994: 
1.75      albertel 5995: sub getSequenceDropDown {
1.582     raeburn  5996:     my ($symb,$map_error)=@_;
1.75      albertel 5997:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5998:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5999:     if (ref($map_error)) {
                   6000:         return if ($$map_error);
                   6001:     }
1.137     albertel 6002:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 6003:     my $ctr=0;
                   6004:     foreach (@$titles) {
                   6005: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   6006: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 6007: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 6008: 	    '>'.$showtitle.'</option>'."\n";
                   6009: 	$ctr++;
                   6010:     }
                   6011:     $result.= '</select>';
                   6012:     return $result;
                   6013: }
                   6014: 
1.495     albertel 6015: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  6016:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 6017: 
                   6018: my %first_bubble_line;             # First bubble line no. for each bubble.
                   6019: 
1.509     raeburn  6020: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   6021:                                    # matchresponse or rankresponse, where 
                   6022:                                    # an individual response can have multiple 
                   6023:                                    # lines
1.503     raeburn  6024: 
                   6025: my %responsetype_per_response;     # responsetype for each response
                   6026: 
1.691     raeburn  6027: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   6028:                                    # numbered response. Needed when randomorder
                   6029:                                    # or randompick are in use. Key is ID, value 
                   6030:                                    # is response number.
                   6031: 
1.495     albertel 6032: # Save and restore the bubble lines array to the form env.
                   6033: 
                   6034: 
                   6035: sub save_bubble_lines {
                   6036:     foreach my $line (keys(%bubble_lines_per_response)) {
                   6037: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   6038: 	$env{"form.scantron.first_bubble_line.$line"} =
                   6039: 	    $first_bubble_line{$line};
1.503     raeburn  6040:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   6041:             $subdivided_bubble_lines{$line};
                   6042:         $env{"form.scantron.responsetype.$line"} =
                   6043:             $responsetype_per_response{$line};
1.495     albertel 6044:     }
1.691     raeburn  6045:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   6046:         my $line = $masterseq_id_responsenum{$resid};
                   6047:         $env{"form.scantron.residpart.$line"} = $resid;
                   6048:     }
1.495     albertel 6049: }
                   6050: 
                   6051: 
                   6052: sub restore_bubble_lines {
                   6053:     my $line = 0;
                   6054:     %bubble_lines_per_response = ();
1.691     raeburn  6055:     %masterseq_id_responsenum = ();
1.495     albertel 6056:     while ($env{"form.scantron.bubblelines.$line"}) {
                   6057: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   6058: 	$bubble_lines_per_response{$line} = $value;
                   6059: 	$first_bubble_line{$line}  =
                   6060: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  6061:         $subdivided_bubble_lines{$line} =
                   6062:             $env{"form.scantron.sub_bubblelines.$line"};
                   6063:         $responsetype_per_response{$line} =
                   6064:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  6065:         my $id = $env{"form.scantron.residpart.$line"};
                   6066:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 6067: 	$line++;
                   6068:     }
                   6069: }
                   6070: 
1.423     albertel 6071: =pod 
                   6072: 
                   6073: =item scantron_filenames
                   6074: 
                   6075:    Returns a list of the scantron files in the current course 
                   6076: 
                   6077: =cut
1.422     foxr     6078: 
1.202     albertel 6079: sub scantron_filenames {
1.257     albertel 6080:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6081:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  6082:     my $getpropath = 1;
1.662     raeburn  6083:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   6084:                                                         $cname,$getpropath);
1.202     albertel 6085:     my @possiblenames;
1.662     raeburn  6086:     if (ref($dirlist) eq 'ARRAY') {
                   6087:         foreach my $filename (sort(@{$dirlist})) {
                   6088: 	    ($filename)=split(/&/,$filename);
                   6089: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   6090: 	    $filename=~s/^scantron_orig_//;
                   6091: 	    push(@possiblenames,$filename);
                   6092:         }
1.202     albertel 6093:     }
                   6094:     return @possiblenames;
                   6095: }
                   6096: 
1.423     albertel 6097: =pod 
                   6098: 
                   6099: =item scantron_uploads
                   6100: 
                   6101:    Returns  html drop-down list of scantron files in current course.
                   6102: 
                   6103:  Arguments:
                   6104:    $file2grade - filename to set as selected in the dropdown
                   6105: 
                   6106: =cut
1.422     foxr     6107: 
1.202     albertel 6108: sub scantron_uploads {
1.209     ng       6109:     my ($file2grade) = @_;
1.202     albertel 6110:     my $result=	'<select name="scantron_selectfile">';
                   6111:     $result.="<option></option>";
                   6112:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 6113: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 6114:     }
                   6115:     $result.="</select>";
                   6116:     return $result;
                   6117: }
                   6118: 
1.423     albertel 6119: =pod 
                   6120: 
                   6121: =item scantron_scantab
                   6122: 
                   6123:   Returns html drop down of the scantron formats in the scantronformat.tab
                   6124:   file.
                   6125: 
                   6126: =cut
1.422     foxr     6127: 
1.82      albertel 6128: sub scantron_scantab {
                   6129:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 6130:     $result.='<option></option>'."\n";
1.754     raeburn  6131:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  6132:     if (@lines > 0) {
                   6133:         foreach my $line (@lines) {
                   6134:             next if (($line =~ /^\#/) || ($line eq ''));
                   6135: 	    my ($name,$descrip)=split(/:/,$line);
                   6136: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   6137:         }
1.82      albertel 6138:     }
                   6139:     $result.='</select>'."\n";
1.518     raeburn  6140:     return $result;
                   6141: }
                   6142: 
1.423     albertel 6143: =pod 
                   6144: 
                   6145: =item scantron_CODElist
                   6146: 
                   6147:   Returns html drop down of the saved CODE lists from current course,
                   6148:   generated from earlier printings.
                   6149: 
                   6150: =cut
1.422     foxr     6151: 
1.186     albertel 6152: sub scantron_CODElist {
1.257     albertel 6153:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6154:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 6155:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   6156:     my $namechoice='<option></option>';
1.225     albertel 6157:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 6158: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 6159: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 6160: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   6161:     }
                   6162:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6163:     return $namechoice;
                   6164: }
                   6165: 
1.423     albertel 6166: =pod 
                   6167: 
                   6168: =item scantron_CODEunique
                   6169: 
                   6170:   Returns the html for "Each CODE to be used once" radio.
                   6171: 
                   6172: =cut
1.422     foxr     6173: 
1.186     albertel 6174: sub scantron_CODEunique {
1.532     bisitz   6175:     my $result='<span class="LC_nobreak">
1.272     albertel 6176:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6177:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6178:                 </span>
1.532     bisitz   6179:                 <span class="LC_nobreak">
1.272     albertel 6180:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6181:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6182:                 </span>';
1.186     albertel 6183:     return $result;
                   6184: }
1.423     albertel 6185: 
                   6186: =pod 
                   6187: 
                   6188: =item scantron_selectphase
                   6189: 
1.659     raeburn  6190:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6191:   Allows for - starting a grading run.
1.424     albertel 6192:              - downloading existing scan data (original, corrected
1.423     albertel 6193:                                                 or skipped info)
                   6194: 
                   6195:              - uploading new scan data
                   6196: 
                   6197:  Arguments:
                   6198:   $r          - The Apache request object
                   6199:   $file2grade - name of the file that contain the scanned data to score
                   6200: 
                   6201: =cut
1.186     albertel 6202: 
1.75      albertel 6203: sub scantron_selectphase {
1.608     www      6204:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6205:     if (!$symb) {return '';}
1.582     raeburn  6206:     my $map_error;
                   6207:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6208:     if ($map_error) {
                   6209:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6210:         return;
                   6211:     }
1.324     albertel 6212:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6213:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6214:     my $format_selector=&scantron_scantab();
1.186     albertel 6215:     my $CODE_selector=&scantron_CODElist();
                   6216:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6217:     my $result;
1.422     foxr     6218: 
1.513     foxr     6219:     $ssi_error = 0;
                   6220: 
1.770     raeburn  6221:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 6222: 
                   6223: 	# Chunk of form to prompt for a scantron file upload.
                   6224: 
                   6225:         $r->print('
1.754     raeburn  6226:     <br />');
1.606     wenzelju 6227:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6228:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  6229:     my $csec= $env{'request.course.sec'};
1.736     damieng  6230:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6231:     &js_escape(\$alertmsg);
1.754     raeburn  6232:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 6233:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   6234:     function checkUpload(formname) {
                   6235: 	if (formname.upfile.value == "") {
1.736     damieng  6236: 	    alert("'.$alertmsg.'");
1.606     wenzelju 6237: 	    return false;
                   6238: 	}
                   6239: 	formname.submit();
1.756     raeburn  6240:     }'."\n".$formatjs));
1.606     wenzelju 6241:     $r->print('
                   6242:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6243:                 '.$default_form_data.'
                   6244:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  6245:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 6246:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6247:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  6248:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6249:               '.&Apache::loncommon::start_data_table_header_row().'
                   6250:                 <th>
                   6251:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6252:                 </th>
                   6253:               '.&Apache::loncommon::end_data_table_header_row().'
                   6254:               '.&Apache::loncommon::start_data_table_row().'
                   6255:             <td>
                   6256:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6257:     if ($formatoptions) {
                   6258:         $r->print('</td>
                   6259:                  '.&Apache::loncommon::end_data_table_row().'
                   6260:                  '.&Apache::loncommon::start_data_table_row().'
                   6261:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6262:                  </td>
                   6263:                  '.&Apache::loncommon::end_data_table_row().'
                   6264:                  '.&Apache::loncommon::start_data_table_row().'
                   6265:                  <td>'
                   6266:         );
                   6267:     } else {
                   6268:         $r->print(' <br />');
                   6269:     }
                   6270:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6271:               </td>
                   6272:              '.&Apache::loncommon::end_data_table_row().'
                   6273:              '.&Apache::loncommon::end_data_table().'
                   6274:              </form>'
                   6275:     );
1.606     wenzelju 6276: 
                   6277:     }
                   6278: 
1.422     foxr     6279:     # Chunk of form to prompt for a file to grade and how:
                   6280: 
1.489     albertel 6281:     $result.= '
                   6282:     <br />
                   6283:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6284:     <input type="hidden" name="command" value="scantron_warning" />
                   6285:     '.$default_form_data.'
                   6286:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6287:        '.&Apache::loncommon::start_data_table_header_row().'
                   6288:             <th colspan="2">
1.492     albertel 6289:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6290:             </th>
                   6291:        '.&Apache::loncommon::end_data_table_header_row().'
                   6292:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6293:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6294:        '.&Apache::loncommon::end_data_table_row().'
                   6295:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6296:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6297:        '.&Apache::loncommon::end_data_table_row().'
                   6298:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6299:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6300:        '.&Apache::loncommon::end_data_table_row().'
                   6301:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6302:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6303:        '.&Apache::loncommon::end_data_table_row().'
                   6304:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6305:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6306:        '.&Apache::loncommon::end_data_table_row().'
                   6307:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6308: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6309:             <td>
1.492     albertel 6310: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6311:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6312:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6313: 	    </td>
1.489     albertel 6314:        '.&Apache::loncommon::end_data_table_row().'
                   6315:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6316:             <td colspan="2">
1.572     www      6317:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6318:             </td>
1.489     albertel 6319:        '.&Apache::loncommon::end_data_table_row().'
                   6320:     '.&Apache::loncommon::end_data_table().'
                   6321:     </form>
                   6322: ';
1.162     albertel 6323:    
                   6324:     $r->print($result);
                   6325: 
1.422     foxr     6326:     # Chunk of the form that prompts to view a scoring office file,
                   6327:     # corrected file, skipped records in a file.
                   6328: 
1.489     albertel 6329:     $r->print('
                   6330:    <br />
                   6331:    <form action="/adm/grades" name="scantron_download">
                   6332:      '.$default_form_data.'
                   6333:      <input type="hidden" name="command" value="scantron_download" />
                   6334:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6335:        '.&Apache::loncommon::start_data_table_header_row().'
                   6336:               <th>
1.492     albertel 6337:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6338:               </th>
                   6339:        '.&Apache::loncommon::end_data_table_header_row().'
                   6340:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6341:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6342:                 <br />
1.492     albertel 6343:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6344:        '.&Apache::loncommon::end_data_table_row().'
                   6345:      '.&Apache::loncommon::end_data_table().'
                   6346:    </form>
                   6347:    <br />
                   6348: ');
1.162     albertel 6349: 
1.457     banghart 6350:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6351: 
1.694     bisitz   6352:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6353:              $default_form_data."\n".
                   6354:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6355:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6356:              '<th colspan="2">
1.572     www      6357:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6358:              '</th>'."\n".
                   6359:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6360:               &Apache::loncommon::start_data_table_row()."\n".
                   6361:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6362:               '<td> '.$sequence_selector.' </td>'.
                   6363:               &Apache::loncommon::end_data_table_row()."\n".
                   6364:               &Apache::loncommon::start_data_table_row()."\n".
                   6365:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6366:               '<td> '.$file_selector.' </td>'."\n".
                   6367:               &Apache::loncommon::end_data_table_row()."\n".
                   6368:               &Apache::loncommon::start_data_table_row()."\n".
                   6369:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6370:               '<td> '.$format_selector.' </td>'."\n".
                   6371:               &Apache::loncommon::end_data_table_row()."\n".
                   6372:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6373:               '<td> '.&mt('Options').' </td>'."\n".
                   6374:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6375:               &Apache::loncommon::end_data_table_row()."\n".
                   6376:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6377:               '<td colspan="2">'."\n".
                   6378:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6379:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6380:               '</td>'."\n".
                   6381:               &Apache::loncommon::end_data_table_row()."\n".
                   6382:               &Apache::loncommon::end_data_table()."\n".
                   6383:               '</form><br />');
                   6384:     return;
1.75      albertel 6385: }
                   6386: 
1.423     albertel 6387: =pod 
                   6388: 
                   6389: =item username_to_idmap
                   6390: 
1.556     weissno  6391:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6392:     student username:domain. If a single ID occurs for more than one student,
                   6393:     the status of the student is checked, and if Active, the value in the hash
                   6394:     will be set to the Active student.
1.423     albertel 6395: 
                   6396:   Arguments:
                   6397: 
                   6398:     $classlist - reference to the class list hash. This is a hash
                   6399:                  keyed by student name:domain  whose elements are references
1.424     albertel 6400:                  to arrays containing various chunks of information
1.423     albertel 6401:                  about the student. (See loncoursedata for more info).
                   6402: 
                   6403:   Returns
                   6404:     %idmap - the constructed hash
                   6405: 
                   6406: =cut
                   6407: 
1.82      albertel 6408: sub username_to_idmap {
                   6409:     my ($classlist)= @_;
                   6410:     my %idmap;
                   6411:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6412:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6413:         unless ($id eq '') {
                   6414:             if (!exists($idmap{$id})) {
                   6415:                 $idmap{$id} = $student;
                   6416:             } else {
                   6417:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6418:                 if ($status eq 'Active') {
                   6419:                     $idmap{$id} = $student;
                   6420:                 }
                   6421:             }
                   6422:         }
1.82      albertel 6423:     }
                   6424:     return %idmap;
                   6425: }
1.423     albertel 6426: 
                   6427: =pod
                   6428: 
1.424     albertel 6429: =item scantron_fixup_scanline
1.423     albertel 6430: 
                   6431:    Process a requested correction to a scanline.
                   6432: 
                   6433:   Arguments:
1.754     raeburn  6434:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6435:     $scan_data         - hash of correction information 
                   6436:                           (see &scantron_getfile())
                   6437:     $line              - existing scanline
                   6438:     $whichline         - line number of the passed in scanline
                   6439:     $field             - type of change to process 
                   6440:                          (either 
1.573     bisitz   6441:                           'ID'     -> correct the student/employee ID
1.423     albertel 6442:                           'CODE'   -> correct the CODE
                   6443:                           'answer' -> fixup the submitted answers)
                   6444:     
                   6445:    $args               - hash of additional info,
                   6446:                           - 'ID' 
                   6447:                                'newid' -> studentID to use in replacement
1.424     albertel 6448:                                           of existing one
1.423     albertel 6449:                           - 'CODE' 
                   6450:                                'CODE_ignore_dup' - set to true if duplicates
                   6451:                                                    should be ignored.
                   6452: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6453:                                         if the existing unfound code should
1.423     albertel 6454:                                         be used as is
                   6455:                           - 'answer'
                   6456:                                'response' - new answer or 'none' if blank
                   6457:                                'question' - the bubble line to change
1.503     raeburn  6458:                                'questionnum' - the question identifier,
                   6459:                                                may include subquestion. 
1.423     albertel 6460: 
                   6461:   Returns:
                   6462:     $line - the modified scanline
                   6463: 
                   6464:   Side effects: 
                   6465:     $scan_data - may be updated
                   6466: 
                   6467: =cut
                   6468: 
1.82      albertel 6469: 
1.157     albertel 6470: sub scantron_fixup_scanline {
                   6471:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6472:     if ($field eq 'ID') {
                   6473: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6474: 	    return ($line,1,'New value too large');
1.157     albertel 6475: 	}
                   6476: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6477: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6478: 				     $args->{'newid'});
                   6479: 	}
                   6480: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6481: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6482: 	if ($args->{'newid'}=~/^\s*$/) {
                   6483: 	    &scan_data($scan_data,"$whichline.user",
                   6484: 		       $args->{'username'}.':'.$args->{'domain'});
                   6485: 	}
1.186     albertel 6486:     } elsif ($field eq 'CODE') {
1.192     albertel 6487: 	if ($args->{'CODE_ignore_dup'}) {
                   6488: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6489: 	}
                   6490: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6491: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6492: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6493: 		return ($line,1,'New CODE value too large');
                   6494: 	    }
                   6495: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6496: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6497: 	    }
                   6498: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6499: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6500: 	}
1.157     albertel 6501:     } elsif ($field eq 'answer') {
1.497     foxr     6502: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6503: 	my $off=$scantron_config->{'Qoff'};
                   6504: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6505: 	my $answer=${off}x$length;
                   6506: 	if ($args->{'response'} eq 'none') {
                   6507: 	    &scan_data($scan_data,
1.503     raeburn  6508: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6509: 	} else {
                   6510: 	    if ($on eq 'letter') {
                   6511: 		my @alphabet=('A'..'Z');
                   6512: 		$answer=$alphabet[$args->{'response'}];
                   6513: 	    } elsif ($on eq 'number') {
                   6514: 		$answer=$args->{'response'}+1;
                   6515: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6516: 	    } else {
1.497     foxr     6517: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6518: 	    }
1.497     foxr     6519: 	    &scan_data($scan_data,
1.503     raeburn  6520: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6521: 	}
1.497     foxr     6522: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6523: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6524:     }
                   6525:     return $line;
                   6526: }
1.423     albertel 6527: 
                   6528: =pod
                   6529: 
                   6530: =item scan_data
                   6531: 
                   6532:     Edit or look up  an item in the scan_data hash.
                   6533: 
                   6534:   Arguments:
                   6535:     $scan_data  - The hash (see scantron_getfile)
                   6536:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6537:                   scantronfilename_key).
1.423     albertel 6538:     $data        - New value of the hash entry.
                   6539:     $delete      - If true, the entry is removed from the hash.
                   6540: 
                   6541:   Returns:
                   6542:     The new value of the hash table field (undefined if deleted).
                   6543: 
                   6544: =cut
                   6545: 
                   6546: 
1.157     albertel 6547: sub scan_data {
                   6548:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6549:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6550:     if (defined($value)) {
                   6551: 	$scan_data->{$filename.'_'.$key} = $value;
                   6552:     }
                   6553:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6554:     return $scan_data->{$filename.'_'.$key};
                   6555: }
1.423     albertel 6556: 
1.495     albertel 6557: # ----- These first few routines are general use routines.----
                   6558: 
                   6559: # Return the number of occurences of a pattern in a string.
                   6560: 
                   6561: sub occurence_count {
                   6562:     my ($string, $pattern) = @_;
                   6563: 
                   6564:     my @matches = ($string =~ /$pattern/g);
                   6565: 
                   6566:     return scalar(@matches);
                   6567: }
                   6568: 
                   6569: 
                   6570: # Take a string known to have digits and convert all the
                   6571: # digits into letters in the range J,A..I.
                   6572: 
                   6573: sub digits_to_letters {
                   6574:     my ($input) = @_;
                   6575: 
                   6576:     my @alphabet = ('J', 'A'..'I');
                   6577: 
                   6578:     my @input    = split(//, $input);
                   6579:     my $output ='';
                   6580:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6581: 	if ($input[$i] =~ /\d/) {
                   6582: 	    $output .= $alphabet[$input[$i]];
                   6583: 	} else {
                   6584: 	    $output .= $input[$i];
                   6585: 	}
                   6586:     }
                   6587:     return $output;
                   6588: }
                   6589: 
1.423     albertel 6590: =pod 
                   6591: 
                   6592: =item scantron_parse_scanline
                   6593: 
1.711     bisitz   6594:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6595: 
                   6596:  Arguments:
1.711     bisitz   6597:     line             - The text of the bubblesheet file line to process
1.423     albertel 6598:     whichline        - Line number
1.711     bisitz   6599:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6600:     scan_data        - Hash of extra information about the scanline
                   6601:                        (see scantron_getfile for more information)
                   6602:     just_header      - True if should not process question answers but only
                   6603:                        the stuff to the left of the answers.
1.691     raeburn  6604:     randomorder      - True if randomorder in use
                   6605:     randompick       - True if randompick in use
                   6606:     sequence         - Exam folder URL
                   6607:     master_seq       - Ref to array containing symbs in exam folder
                   6608:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6609:                        (corresponding values are resource objects)
                   6610:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6611:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6612:                        are refs to an array of resource objects, ordered
                   6613:                        according to order used for CODE, when randomorder
                   6614:                        and or randompick are in use.
                   6615:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6616:                        for current line to question number used for same question
                   6617:                         in "Master Sequence" (as seen by Course Coordinator).
                   6618:     startline        - Ref to hash where key is question number (0 is first)
                   6619:                        and value is number of first bubble line for current 
                   6620:                        student or code-based randompick and/or randomorder.
                   6621:     totalref         - Ref of scalar used to score total number of bubble
                   6622:                        lines needed for responses in a scan line (used when
                   6623:                        randompick in use. 
                   6624:     
1.423     albertel 6625:  Returns:
                   6626:    Hash containing the result of parsing the scanline
                   6627: 
                   6628:    Keys are all proceeded by the string 'scantron.'
                   6629: 
                   6630:        CODE    - the CODE in use for this scanline
                   6631:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6632:                  by the operator
                   6633:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6634:                             CODEs were selected, but the usage has been
                   6635:                             forced by the operator
1.556     weissno  6636:        ID  - student/employee ID
1.423     albertel 6637:        PaperID - if used, the ID number printed on the sheet when the 
                   6638:                  paper was scanned
                   6639:        FirstName - first name from the sheet
                   6640:        LastName  - last name from the sheet
                   6641: 
                   6642:      if just_header was not true these key may also exist
                   6643: 
1.447     foxr     6644:        missingerror - a list of bubble ranges that are considered to be answers
                   6645:                       to a single question that don't have any bubbles filled in.
                   6646:                       Of the form questionnumber:firstbubblenumber:count.
                   6647:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6648:                       to a single question that have more than one bubble filled in.
                   6649:                       Of the form questionnumber::firstbubblenumber:count
                   6650:    
                   6651:                 In the above, count is the number of bubble responses in the
                   6652:                 input line needed to represent the possible answers to the question.
                   6653:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6654:                 per line would have count = 2.
                   6655: 
1.423     albertel 6656:        maxquest     - the number of the last bubble line that was parsed
                   6657: 
                   6658:        (<number> starts at 1)
                   6659:        <number>.answer - zero or more letters representing the selected
                   6660:                          letters from the scanline for the bubble line 
                   6661:                          <number>.
                   6662:                          if blank there was either no bubble or there where
                   6663:                          multiple bubbles, (consult the keys missingerror and
                   6664:                          doubleerror if this is an error condition)
                   6665: 
                   6666: =cut
                   6667: 
1.82      albertel 6668: sub scantron_parse_scanline {
1.691     raeburn  6669:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6670:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6671:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6672: 
1.82      albertel 6673:     my %record;
1.691     raeburn  6674:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6675:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6676: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6677: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6678: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6679: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6680: 	    $record{'scantron.CODE'}=substr($data,
                   6681: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6682: 					    $$scantron_config{'CODElength'});
1.191     albertel 6683: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6684: 		$record{'scantron.useCODE'}=1;
                   6685: 	    }
1.192     albertel 6686: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6687: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6688: 	    }
1.82      albertel 6689: 	} else {
                   6690: 	    #FIXME interpret first N questions
                   6691: 	}
                   6692:     }
1.83      albertel 6693:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6694: 				  $$scantron_config{'IDlength'});
1.157     albertel 6695:     $record{'scantron.PaperID'}=
                   6696: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6697: 	       $$scantron_config{'PaperIDlength'});
                   6698:     $record{'scantron.FirstName'}=
                   6699: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6700: 	       $$scantron_config{'FirstNamelength'});
                   6701:     $record{'scantron.LastName'}=
                   6702: 	substr($data,$$scantron_config{'LastName'}-1,
                   6703: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6704:     if ($just_header) { return \%record; }
1.194     albertel 6705: 
1.82      albertel 6706:     my @alphabet=('A'..'Z');
                   6707:     my $questnum=0;
1.447     foxr     6708:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6709: 
1.691     raeburn  6710:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6711:     if ($randompick || $randomorder) {
                   6712:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6713:                                          $master_seq,$symb_to_resource,
                   6714:                                          $partids_by_symb,$orderedforcode,
                   6715:                                          $respnumlookup,$startline);
                   6716:         if ($total) {
                   6717:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6718:         }
                   6719:         if (ref($totalref)) {
                   6720:             $$totalref = $total;
                   6721:         }
                   6722:     }
                   6723:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6724:     chomp($questions);		# Get rid of any trailing \n.
                   6725:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6726:     while (length($questions)) {
1.691     raeburn  6727:         my $answers_needed;
                   6728:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6729:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6730:         } else {
                   6731: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6732:         }
1.503     raeburn  6733:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6734:                              || 1;
                   6735:         $questnum++;
                   6736:         my $quest_id = $questnum;
                   6737:         my $currentquest = substr($questions,0,$answer_length);
                   6738:         $questions       = substr($questions,$answer_length);
                   6739:         if (length($currentquest) < $answer_length) { next; }
                   6740: 
1.691     raeburn  6741:         my $subdivided;
                   6742:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6743:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6744:         } else {
                   6745:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6746:         }
                   6747:         if ($subdivided =~ /,/) {
1.503     raeburn  6748:             my $subquestnum = 1;
                   6749:             my $subquestions = $currentquest;
1.691     raeburn  6750:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6751:             foreach my $subans (@subanswers_needed) {
                   6752:                 my $subans_length =
                   6753:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6754:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6755:                 $subquestions   = substr($subquestions,$subans_length);
                   6756:                 $quest_id = "$questnum.$subquestnum";
                   6757:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6758:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6759:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6760:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6761:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6762:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6763:                 } else {
                   6764:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6765:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6766:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6767:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6768:                 }
                   6769:                 $subquestnum ++;
                   6770:             }
                   6771:         } else {
                   6772:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6773:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6774:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6775:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6776:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6777:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6778:             } else {
                   6779:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6780:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6781:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6782:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6783:             }
                   6784:         }
                   6785:     }
                   6786:     $record{'scantron.maxquest'}=$questnum;
                   6787:     return \%record;
                   6788: }
1.447     foxr     6789: 
1.691     raeburn  6790: sub get_master_seq {
1.788     raeburn  6791:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
1.691     raeburn  6792:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6793:                    (ref($symb_to_resource) eq 'HASH'));
1.788     raeburn  6794:     if ($need_symb_in_map) {
                   6795:         return unless (ref($symb_for_examcode) eq 'HASH');
                   6796:     }
1.691     raeburn  6797:     my $resource_error;
                   6798:     foreach my $resource (@{$resources}) {
                   6799:         my $ressymb;
                   6800:         if (ref($resource)) {
                   6801:             $ressymb = $resource->symb();
                   6802:             push(@{$master_seq},$ressymb);
                   6803:             $symb_to_resource->{$ressymb} = $resource;
1.788     raeburn  6804:             if ($need_symb_in_map) {
                   6805:                 unless ($resource->is_map()) {
                   6806:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   6807:                     unless (exists($symb_for_examcode->{$map})) {
                   6808:                         $symb_for_examcode->{$map} = $ressymb;
                   6809:                     }
                   6810:                 }
                   6811:             }
1.691     raeburn  6812:         } else {
                   6813:             $resource_error = 1;
                   6814:             last;
                   6815:         }
                   6816:     }
                   6817:     return $resource_error;
                   6818: }
                   6819: 
                   6820: sub get_respnum_lookups {
                   6821:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6822:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6823:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6824:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6825:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6826:                    (ref($startline) eq 'HASH'));
                   6827:     my ($user,$scancode);
                   6828:     if ((exists($record->{'scantron.CODE'})) &&
                   6829:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6830:         $scancode = $record->{'scantron.CODE'};
                   6831:     } else {
                   6832:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6833:     }
                   6834:     my @mapresources =
                   6835:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6836:                      $orderedforcode);
                   6837:     my $total = 0;
                   6838:     my $count = 0;
                   6839:     foreach my $resource (@mapresources) {
                   6840:         my $id = $resource->id();
                   6841:         my $symb = $resource->symb();
                   6842:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6843:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6844:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6845:                 if ($respnum ne '') {
                   6846:                     $respnumlookup->{$count} = $respnum;
                   6847:                     $startline->{$count} = $total;
                   6848:                     $total += $bubble_lines_per_response{$respnum};
                   6849:                     $count ++;
                   6850:                 }
                   6851:             }
                   6852:         }
                   6853:     }
                   6854:     return $total;
                   6855: }
                   6856: 
1.503     raeburn  6857: sub scantron_validator_lettnum {
                   6858:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6859:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6860:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6861: 
                   6862:     # Qon 'letter' implies for each slot in currquest we have:
                   6863:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6864:     #    about anything else (esp. a value of Qoff) for missing
                   6865:     #    bubbles.
                   6866:     #
                   6867:     # Qon 'number' implies each slot gives a digit that indexes the
                   6868:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6869:     #    and * or ? for double bubbles on a single line.
                   6870:     #
1.447     foxr     6871: 
1.503     raeburn  6872:     my $matchon;
                   6873:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6874:         $matchon = '[A-Z]';
                   6875:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6876:         $matchon = '\d';
                   6877:     }
                   6878:     my $occurrences = 0;
1.691     raeburn  6879:     my $responsenum = $questnum-1;
                   6880:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6881:        $responsenum = $respnumlookup->{$questnum-1} 
                   6882:     }
                   6883:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6884:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6885:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6886:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6887:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6888:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6889:         my @singlelines = split('',$currquest);
                   6890:         foreach my $entry (@singlelines) {
                   6891:             $occurrences = &occurence_count($entry,$matchon);
                   6892:             if ($occurrences > 1) {
                   6893:                 last;
                   6894:             }
1.691     raeburn  6895:         }
1.503     raeburn  6896:     } else {
                   6897:         $occurrences = &occurence_count($currquest,$matchon); 
                   6898:     }
                   6899:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6900:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6901:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6902:             my $bubble = substr($currquest,$ans,1);
                   6903:             if ($bubble =~ /$matchon/ ) {
                   6904:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6905:                     if ($bubble == 0) {
                   6906:                         $bubble = 10; 
                   6907:                     }
                   6908:                     $record->{"scantron.$ansnum.answer"} = 
                   6909:                         $alphabet->[$bubble-1];
                   6910:                 } else {
                   6911:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6912:                 }
                   6913:             } else {
                   6914:                 $record->{"scantron.$ansnum.answer"}='';
                   6915:             }
                   6916:             $ansnum++;
                   6917:         }
                   6918:     } elsif (!defined($currquest)
                   6919:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6920:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6921:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6922:             $record->{"scantron.$ansnum.answer"}='';
                   6923:             $ansnum++;
                   6924:         }
                   6925:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6926:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6927:         }
                   6928:     } else {
                   6929:         if ($$scantron_config{'Qon'} eq 'number') {
                   6930:             $currquest = &digits_to_letters($currquest);            
                   6931:         }
                   6932:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6933:             my $bubble = substr($currquest,$ans,1);
                   6934:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6935:             $ansnum++;
                   6936:         }
                   6937:     }
                   6938:     return $ansnum;
                   6939: }
1.447     foxr     6940: 
1.503     raeburn  6941: sub scantron_validator_positional {
                   6942:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6943:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6944:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6945: 
1.503     raeburn  6946:     # Otherwise there's a positional notation;
                   6947:     # each bubble line requires Qlength items, and there are filled in
                   6948:     # bubbles for each case where there 'Qon' characters.
                   6949:     #
1.447     foxr     6950: 
1.503     raeburn  6951:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6952: 
1.503     raeburn  6953:     # If the split only gives us one element.. the full length of the
                   6954:     # answer string, no bubbles are filled in:
1.447     foxr     6955: 
1.507     raeburn  6956:     if ($answers_needed eq '') {
                   6957:         return;
                   6958:     }
                   6959: 
1.503     raeburn  6960:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6961:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6962:             $record->{"scantron.$ansnum.answer"}='';
                   6963:             $ansnum++;
                   6964:         }
                   6965:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6966:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6967:         }
                   6968:     } elsif (scalar(@array) == 2) {
                   6969:         my $location = length($array[0]);
                   6970:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6971:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6972:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6973:             if ($ans eq $line_num) {
                   6974:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6975:             } else {
                   6976:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6977:             }
                   6978:             $ansnum++;
                   6979:          }
                   6980:     } else {
                   6981:         #  If there's more than one instance of a bubble character
                   6982:         #  That's a double bubble; with positional notation we can
                   6983:         #  record all the bubbles filled in as well as the
                   6984:         #  fact this response consists of multiple bubbles.
                   6985:         #
1.691     raeburn  6986:         my $responsenum = $questnum-1;
                   6987:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6988:             $responsenum = $respnumlookup->{$questnum-1}
                   6989:         }
                   6990:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6991:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6992:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6993:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6994:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6995:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6996:             my $doubleerror = 0;
                   6997:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6998:                    (!$doubleerror)) {
                   6999:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   7000:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   7001:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   7002:                if (length(@currarray) > 2) {
                   7003:                    $doubleerror = 1;
                   7004:                } 
                   7005:             }
                   7006:             if ($doubleerror) {
                   7007:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   7008:             }
                   7009:         } else {
                   7010:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   7011:         }
                   7012:         my $item = $ansnum;
                   7013:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   7014:             $record->{"scantron.$item.answer"} = '';
                   7015:             $item ++;
                   7016:         }
1.447     foxr     7017: 
1.503     raeburn  7018:         my @ans=@array;
                   7019:         my $i=0;
                   7020:         my $increment = 0;
                   7021:         while ($#ans) {
                   7022:             $i+=length($ans[0]) + $increment;
                   7023:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   7024:             my $bubble = $i%$$scantron_config{'Qlength'};
                   7025:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   7026:             shift(@ans);
                   7027:             $increment = 1;
                   7028:         }
                   7029:         $ansnum += $answers_needed;
1.82      albertel 7030:     }
1.503     raeburn  7031:     return $ansnum;
1.82      albertel 7032: }
                   7033: 
1.423     albertel 7034: =pod
                   7035: 
                   7036: =item scantron_add_delay
                   7037: 
                   7038:    Adds an error message that occurred during the grading phase to a
                   7039:    queue of messages to be shown after grading pass is complete
                   7040: 
                   7041:  Arguments:
1.424     albertel 7042:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 7043:    $scanline    - the scanline that caused the error
                   7044:    $errormesage - the error message
                   7045:    $errorcode   - a numeric code for the error
                   7046: 
                   7047:  Side Effects:
1.424     albertel 7048:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 7049: 
                   7050: =cut
                   7051: 
1.82      albertel 7052: sub scantron_add_delay {
1.140     albertel 7053:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   7054:     push(@$delayqueue,
                   7055: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   7056: 	  'ecode' => $errorcode }
                   7057: 	 );
1.82      albertel 7058: }
                   7059: 
1.423     albertel 7060: =pod
                   7061: 
                   7062: =item scantron_find_student
                   7063: 
1.424     albertel 7064:    Finds the username for the current scanline
                   7065: 
                   7066:   Arguments:
                   7067:    $scantron_record - hash result from scantron_parse_scanline
                   7068:    $scan_data       - hash of correction information 
                   7069:                       (see &scantron_getfile() form more information)
                   7070:    $idmap           - hash from &username_to_idmap()
                   7071:    $line            - number of current scanline
                   7072:  
                   7073:   Returns:
                   7074:    Either 'username:domain' or undef if unknown
                   7075: 
1.423     albertel 7076: =cut
                   7077: 
1.82      albertel 7078: sub scantron_find_student {
1.157     albertel 7079:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 7080:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 7081:     if ($scanID =~ /^\s*$/) {
                   7082:  	return &scan_data($scan_data,"$line.user");
                   7083:     }
1.83      albertel 7084:     foreach my $id (keys(%$idmap)) {
1.157     albertel 7085:  	if (lc($id) eq lc($scanID)) {
                   7086:  	    return $$idmap{$id};
                   7087:  	}
1.83      albertel 7088:     }
                   7089:     return undef;
                   7090: }
                   7091: 
1.423     albertel 7092: =pod
                   7093: 
                   7094: =item scantron_filter
                   7095: 
1.424     albertel 7096:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   7097:    hidden resources was selected
                   7098: 
1.423     albertel 7099: =cut
                   7100: 
1.83      albertel 7101: sub scantron_filter {
                   7102:     my ($curres)=@_;
1.331     albertel 7103: 
                   7104:     if (ref($curres) && $curres->is_problem()) {
                   7105: 	# if the user has asked to not have either hidden
                   7106: 	# or 'randomout' controlled resources to be graded
                   7107: 	# don't include them
                   7108: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7109: 	    && $curres->randomout) {
                   7110: 	    return 0;
                   7111: 	}
1.83      albertel 7112: 	return 1;
                   7113:     }
                   7114:     return 0;
1.82      albertel 7115: }
                   7116: 
1.423     albertel 7117: =pod
                   7118: 
                   7119: =item scantron_process_corrections
                   7120: 
1.424     albertel 7121:    Gets correction information out of submitted form data and corrects
                   7122:    the scanline
                   7123: 
1.423     albertel 7124: =cut
                   7125: 
1.157     albertel 7126: sub scantron_process_corrections {
                   7127:     my ($r) = @_;
1.754     raeburn  7128:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7129:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7130:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 7131:     my $which=$env{'form.scantron_line'};
1.200     albertel 7132:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 7133:     my ($skip,$err,$errmsg);
1.257     albertel 7134:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 7135: 	$skip=1;
1.257     albertel 7136:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   7137: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   7138: 	    $env{'form.scantron_domain'};
1.157     albertel 7139: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   7140: 	($line,$err,$errmsg)=
                   7141: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   7142: 				     'ID',{'newid'=>$newid,
1.257     albertel 7143: 				    'username'=>$env{'form.scantron_username'},
                   7144: 				    'domain'=>$env{'form.scantron_domain'}});
                   7145:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   7146: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 7147: 	my $newCODE;
1.192     albertel 7148: 	my %args;
1.190     albertel 7149: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 7150: 	    $newCODE='use_unfound';
1.190     albertel 7151: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 7152: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 7153: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 7154: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 7155: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 7156: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 7157: 	}
1.257     albertel 7158: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 7159: 	    $args{'CODE_ignore_dup'}=1;
                   7160: 	}
                   7161: 	$args{'CODE'}=$newCODE;
1.186     albertel 7162: 	($line,$err,$errmsg)=
                   7163: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7164: 				     'CODE',\%args);
1.257     albertel 7165:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7166: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7167: 	    ($line,$err,$errmsg)=
                   7168: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7169: 					 $which,'answer',
                   7170: 					 { 'question'=>$question,
1.503     raeburn  7171: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7172:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7173: 	    if ($err) { last; }
                   7174: 	}
                   7175:     }
                   7176:     if ($err) {
1.703     bisitz   7177:         $r->print(
                   7178:             '<p class="LC_error">'
                   7179:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7180:                 $errmsg)
1.704     raeburn  7181:            .'</p>');
1.157     albertel 7182:     } else {
1.200     albertel 7183: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7184: 	&scantron_putfile($scanlines,$scan_data);
                   7185:     }
                   7186: }
                   7187: 
1.423     albertel 7188: =pod
                   7189: 
                   7190: =item reset_skipping_status
                   7191: 
1.424     albertel 7192:    Forgets the current set of remember skipped scanlines (and thus
                   7193:    reverts back to considering all lines in the
                   7194:    scantron_skipped_<filename> file)
                   7195: 
1.423     albertel 7196: =cut
                   7197: 
1.200     albertel 7198: sub reset_skipping_status {
                   7199:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7200:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7201:     &scantron_putfile(undef,$scan_data);
                   7202: }
                   7203: 
1.423     albertel 7204: =pod
                   7205: 
                   7206: =item start_skipping
                   7207: 
1.424     albertel 7208:    Marks a scanline to be skipped. 
                   7209: 
1.423     albertel 7210: =cut
                   7211: 
1.376     albertel 7212: sub start_skipping {
1.200     albertel 7213:     my ($scan_data,$i)=@_;
                   7214:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7215:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7216: 	$remembered{$i}=2;
                   7217:     } else {
                   7218: 	$remembered{$i}=1;
                   7219:     }
1.200     albertel 7220:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7221: }
                   7222: 
1.423     albertel 7223: =pod
                   7224: 
                   7225: =item should_be_skipped
                   7226: 
1.424     albertel 7227:    Checks whether a scanline should be skipped.
                   7228: 
1.423     albertel 7229: =cut
                   7230: 
1.200     albertel 7231: sub should_be_skipped {
1.376     albertel 7232:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7233:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7234: 	# not redoing old skips
1.376     albertel 7235: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7236: 	return 0;
                   7237:     }
                   7238:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7239: 
                   7240:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7241: 	return 0;
                   7242:     }
1.200     albertel 7243:     return 1;
                   7244: }
                   7245: 
1.423     albertel 7246: =pod
                   7247: 
                   7248: =item remember_current_skipped
                   7249: 
1.424     albertel 7250:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7251:    file and remembers them into scan_data for later use.
                   7252: 
1.423     albertel 7253: =cut
                   7254: 
1.200     albertel 7255: sub remember_current_skipped {
                   7256:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7257:     my %to_remember;
                   7258:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7259: 	if ($scanlines->{'skipped'}[$i]) {
                   7260: 	    $to_remember{$i}=1;
                   7261: 	}
                   7262:     }
1.376     albertel 7263: 
1.200     albertel 7264:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7265:     &scantron_putfile(undef,$scan_data);
                   7266: }
                   7267: 
1.423     albertel 7268: =pod
                   7269: 
                   7270: =item check_for_error
                   7271: 
1.424     albertel 7272:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  7273:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7274:     something went wrong.
                   7275: 
1.423     albertel 7276: =cut
                   7277: 
1.200     albertel 7278: sub check_for_error {
                   7279:     my ($r,$result)=@_;
                   7280:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7281: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7282:     }
                   7283: }
1.157     albertel 7284: 
1.423     albertel 7285: =pod
                   7286: 
                   7287: =item scantron_warning_screen
                   7288: 
1.424     albertel 7289:    Interstitial screen to make sure the operator has selected the
                   7290:    correct options before we start the validation phase.
                   7291: 
1.423     albertel 7292: =cut
                   7293: 
1.203     albertel 7294: sub scantron_warning_screen {
1.650     raeburn  7295:     my ($button_text,$symb)=@_;
1.257     albertel 7296:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  7297:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7298:     my $CODElist;
1.284     albertel 7299:     if ($scantron_config{'CODElocation'} &&
                   7300: 	$scantron_config{'CODEstart'} &&
                   7301: 	$scantron_config{'CODElength'}) {
                   7302: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   7303: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7304: 	$CODElist=
1.492     albertel 7305: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7306: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7307:     }
1.663     raeburn  7308:     my $lastbubblepoints;
                   7309:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7310:         $lastbubblepoints =
                   7311:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7312:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7313:     }
1.770     raeburn  7314:     return '
1.203     albertel 7315: <p>
1.492     albertel 7316: <span class="LC_warning">
1.705     raeburn  7317: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7318: </p>
                   7319: <table>
1.492     albertel 7320: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7321: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  7322: '.$CODElist.$lastbubblepoints.'
1.203     albertel 7323: </table>
1.680     raeburn  7324: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  7325: '.&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  7326: ';
1.203     albertel 7327: }
                   7328: 
1.423     albertel 7329: =pod
                   7330: 
                   7331: =item scantron_do_warning
                   7332: 
1.424     albertel 7333:    Check if the operator has picked something for all required
                   7334:    fields. Error out if something is missing.
                   7335: 
1.423     albertel 7336: =cut
                   7337: 
1.203     albertel 7338: sub scantron_do_warning {
1.608     www      7339:     my ($r,$symb)=@_;
1.203     albertel 7340:     if (!$symb) {return '';}
1.324     albertel 7341:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7342:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7343:     if ( $env{'form.selectpage'} eq '' ||
                   7344: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7345: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7346: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7347: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7348: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7349: 	} 
1.257     albertel 7350: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7351: 	    $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  7352: 	}
1.257     albertel 7353: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7354: 	    $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  7355: 	}
1.237     albertel 7356:     } else {
1.650     raeburn  7357: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  7358:         my ($checksec,@possibles) = &gradable_sections();
                   7359:         my $gradesections;
                   7360:         if ($checksec) {
                   7361:             my $file=$env{'form.scantron_selectfile'};
                   7362:             if (&valid_file($file)) {
                   7363:                 my %bysec = &scantron_get_sections();
                   7364:                 my $table;
                   7365:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   7366:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   7367:                     $table = &Apache::loncommon::start_data_table()."\n".
                   7368:                              &Apache::loncommon::start_data_table_header_row().
                   7369:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   7370:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   7371:                     if ($bysec{'none'}) {
                   7372:                         $table .= &Apache::loncommon::start_data_table_row().
                   7373:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   7374:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7375:                     }
                   7376:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   7377:                         next if ($sec eq 'none');
                   7378:                         $table .= &Apache::loncommon::start_data_table_row().
                   7379:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   7380:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7381:                     }
                   7382:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   7383:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   7384:                                       '<p>'.$table.'</p>';
                   7385:                     if (@possibles) {
                   7386:                         $gradesections .= '<p>'.
                   7387:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   7388:                                               scalar(@possibles)).'<br />'.
                   7389:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   7390:                                               '<i>'.$checksec.'</i>').' ';
                   7391:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   7392:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   7393:                         }
                   7394:                         $gradesections .= '</p>';
                   7395:                     }
                   7396:                 }
                   7397:             } else {
                   7398:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   7399:             }
                   7400:         }
1.663     raeburn  7401:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7402: 	$r->print('
1.770     raeburn  7403: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 7404: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7405: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7406: ');
1.237     albertel 7407:     }
1.614     www      7408:     $r->print("</form><br />");
1.203     albertel 7409:     return '';
                   7410: }
                   7411: 
1.423     albertel 7412: =pod
                   7413: 
                   7414: =item scantron_form_start
                   7415: 
1.424     albertel 7416:     html hidden input for remembering all selected grading options
                   7417: 
1.423     albertel 7418: =cut
                   7419: 
1.203     albertel 7420: sub scantron_form_start {
                   7421:     my ($max_bubble)=@_;
                   7422:     my $result= <<SCANTRONFORM;
                   7423: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7424:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7425:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7426:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7427:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7428:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7429:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7430:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7431:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7432:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7433: SCANTRONFORM
1.447     foxr     7434: 
                   7435:   my $line = 0;
                   7436:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7437:        my $chunk =
                   7438: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7439:        $chunk .=
                   7440: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7441:        $chunk .= 
                   7442:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7443:        $chunk .=
                   7444:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7445:        $chunk .=
                   7446:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7447:        $result .= $chunk;
                   7448:        $line++;
1.691     raeburn  7449:     }
1.203     albertel 7450:     return $result;
                   7451: }
                   7452: 
1.423     albertel 7453: =pod
                   7454: 
                   7455: =item scantron_validate_file
                   7456: 
1.659     raeburn  7457:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7458: 
                   7459:     Also processes any necessary information resets that need to
                   7460:     occur before validation begins (ignore previous corrections,
                   7461:     restarting the skipped records processing)
                   7462: 
1.423     albertel 7463: =cut
                   7464: 
1.157     albertel 7465: sub scantron_validate_file {
1.608     www      7466:     my ($r,$symb) = @_;
1.157     albertel 7467:     if (!$symb) {return '';}
1.324     albertel 7468:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7469:     
1.703     bisitz   7470:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7471:     # them when doing the corrections reset
1.257     albertel 7472:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7473: 	&reset_skipping_status();
                   7474:     }
1.257     albertel 7475:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7476: 	&remember_current_skipped();
1.257     albertel 7477: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7478:     }
                   7479: 
1.257     albertel 7480:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7481: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7482: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7483: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7484: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7485:     }
1.200     albertel 7486: 
1.257     albertel 7487:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7488: 	&scantron_process_corrections($r);
                   7489:     }
1.770     raeburn  7490: 
                   7491:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   7492:     my ($checksec,@gradable);
                   7493:     if ($env{'request.course.sec'}) {
                   7494:         ($checksec,my @possibles) = &gradable_sections();
                   7495:         if ($checksec) {
                   7496:             if (@possibles) {
                   7497:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   7498:                 if (@chosensecs) {
                   7499:                     foreach my $sec (@chosensecs) {
                   7500:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   7501:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   7502:                                 push(@gradable,$sec);
                   7503:                             }
                   7504:                         }
                   7505:                     }
                   7506:                 }
                   7507:             }
                   7508:             $r->print('<p><table>');
                   7509:             if (@gradable) {
                   7510:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   7511:                 $r->print(
                   7512:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   7513:             } else {
                   7514:                 $r->print(
                   7515:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   7516:             }
                   7517:             $r->print('</table></p>');
                   7518:         }
                   7519:     }
                   7520:     $r->rflush();
                   7521: 
1.157     albertel 7522:     #get the student pick code ready
                   7523:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7524:     my $nav_error;
1.754     raeburn  7525:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7526:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7527:     if ($nav_error) {
                   7528:         $r->print(&navmap_errormsg());
                   7529:         return '';
                   7530:     }
1.203     albertel 7531:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7532:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7533:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7534:     }
1.157     albertel 7535:     $r->print($result);
                   7536:     
1.334     albertel 7537:     my @validate_phases=( 'sequence',
                   7538: 			  'ID',
1.157     albertel 7539: 			  'CODE',
                   7540: 			  'doublebubble',
                   7541: 			  'missingbubbles');
1.257     albertel 7542:     if (!$env{'form.validatepass'}) {
                   7543: 	$env{'form.validatepass'} = 0;
1.157     albertel 7544:     }
1.257     albertel 7545:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  7546:     my %skipbysec=();
1.448     foxr     7547: 
1.157     albertel 7548:     my $stop=0;
                   7549:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7550: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7551: 	$r->rflush();
1.691     raeburn  7552:      
1.157     albertel 7553: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7554: 	{
                   7555: 	    no strict 'refs';
1.770     raeburn  7556:             my @extras=();
                   7557:             if ($validate_phases[$currentphase] eq 'ID') {
                   7558:                 @extras = (\%skipbysec,$checksec,@gradable);
                   7559:             }
                   7560: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 7561: 	}
                   7562:     }
                   7563:     if (!$stop) {
1.650     raeburn  7564: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  7565:         my $secinfo;
                   7566:         if (keys(%skipbysec) > 0) {
                   7567:             my $seclist = '<ul>';
                   7568:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   7569:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   7570:             }
                   7571:             $seclist .= '</ul>';
                   7572:             $secinfo = '<p class="LC_info">'.
                   7573:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   7574:                            $seclist).
                   7575:                        '</p>';
                   7576:         }
1.542     raeburn  7577: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  7578:                   $secinfo.$warning.
1.542     raeburn  7579:                   &mt('Perform verification for each student after storage of submissions?').
                   7580:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7581:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7582:                   ('&nbsp;'x3).'<label>'.
                   7583:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7584:                   '</label></span><br />'.
                   7585:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7586:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7587:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7588:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7589:     } else {
                   7590: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7591: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7592:     }
                   7593:     if ($stop) {
1.334     albertel 7594: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7595: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7596: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7597: 
1.650     raeburn  7598: 	    $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 7599: 	} else {
1.503     raeburn  7600:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7601: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7602:             } else {
1.539     riegler  7603:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7604:             }
1.492     albertel 7605: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7606: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7607: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7608: 	}
1.157     albertel 7609:     }
1.614     www      7610:     $r->print(" </form><br />");
1.157     albertel 7611:     return '';
                   7612: }
                   7613: 
1.423     albertel 7614: 
                   7615: =pod
                   7616: 
                   7617: =item scantron_remove_file
                   7618: 
1.659     raeburn  7619:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7620:    scantron_original_<filename> is never removed
                   7621: 
                   7622: 
1.423     albertel 7623: =cut
                   7624: 
1.200     albertel 7625: sub scantron_remove_file {
1.192     albertel 7626:     my ($which)=@_;
1.257     albertel 7627:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7628:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7629:     my $file='scantron_';
1.200     albertel 7630:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7631: 	$file.=$which.'_';
1.192     albertel 7632:     } else {
                   7633: 	return 'refused';
                   7634:     }
1.257     albertel 7635:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7636:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7637: }
                   7638: 
1.423     albertel 7639: 
                   7640: =pod
                   7641: 
                   7642: =item scantron_remove_scan_data
                   7643: 
1.659     raeburn  7644:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7645:    data file.  (In the case that both the are doing skipped records we need
                   7646:    to remember the old skipped lines for the time being so that element
                   7647:    persists for a while.)
                   7648: 
1.423     albertel 7649: =cut
                   7650: 
1.200     albertel 7651: sub scantron_remove_scan_data {
1.257     albertel 7652:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7653:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7654:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7655:     my @todelete;
1.257     albertel 7656:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7657:     foreach my $key (@keys) {
                   7658: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7659: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7660: 		$key=~/remember_skipping/) {
                   7661: 		next;
                   7662: 	    }
1.192     albertel 7663: 	    push(@todelete,$key);
                   7664: 	}
                   7665:     }
1.200     albertel 7666:     my $result;
1.192     albertel 7667:     if (@todelete) {
1.491     albertel 7668: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7669: 				       \@todelete,$cdom,$cname);
                   7670:     } else {
                   7671: 	$result = 'ok';
1.192     albertel 7672:     }
                   7673:     return $result;
                   7674: }
                   7675: 
1.423     albertel 7676: 
                   7677: =pod
                   7678: 
                   7679: =item scantron_getfile
                   7680: 
1.659     raeburn  7681:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7682:     the scan_data hash
                   7683:   
                   7684:   Arguments:
                   7685:     None
                   7686: 
                   7687:   Returns:
                   7688:     2 hash references
                   7689: 
                   7690:      - first one has 
                   7691:          orig      -
                   7692:          corrected -
                   7693:          skipped   -  each of which points to an array ref of the specified
                   7694:                       file broken up into individual lines
                   7695:          count     - number of scanlines
                   7696:  
                   7697:      - second is the scan_data hash possible keys are
1.425     albertel 7698:        ($number refers to scanline numbered $number and thus the key affects
                   7699:         only that scanline
                   7700:         $bubline refers to the specific bubble line element and the aspects
                   7701:         refers to that specific bubble line element)
                   7702: 
                   7703:        $number.user - username:domain to use
                   7704:        $number.CODE_ignore_dup 
                   7705:                     - ignore the duplicate CODE error 
                   7706:        $number.useCODE
                   7707:                     - use the CODE in the scanline as is
                   7708:        $number.no_bubble.$bubline
                   7709:                     - it is valid that there is no bubbled in bubble
                   7710:                       at $number $bubline
                   7711:        remember_skipping
                   7712:                     - a frozen hash containing keys of $number and values
                   7713:                       of either 
                   7714:                         1 - we are on a 'do skipped records pass' and plan
                   7715:                             on processing this line
                   7716:                         2 - we are on a 'do skipped records pass' and this
                   7717:                             scanline has been marked to skip yet again
1.424     albertel 7718: 
1.423     albertel 7719: =cut
                   7720: 
1.157     albertel 7721: sub scantron_getfile {
1.200     albertel 7722:     #FIXME really would prefer a scantron directory
1.257     albertel 7723:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7724:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7725:     my $lines;
                   7726:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7727: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7728:     my %scanlines;
                   7729:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7730:     my $temp=$scanlines{'orig'};
                   7731:     $scanlines{'count'}=$#$temp;
                   7732: 
                   7733:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7734: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7735:     if ($lines eq '-1') {
                   7736: 	$scanlines{'corrected'}=[];
                   7737:     } else {
                   7738: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7739:     }
                   7740:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7741: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7742:     if ($lines eq '-1') {
                   7743: 	$scanlines{'skipped'}=[];
                   7744:     } else {
                   7745: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7746:     }
1.175     albertel 7747:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7748:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7749:     my %scan_data = @tmp;
                   7750:     return (\%scanlines,\%scan_data);
                   7751: }
                   7752: 
1.423     albertel 7753: =pod
                   7754: 
                   7755: =item lonnet_putfile
                   7756: 
1.424     albertel 7757:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7758: 
                   7759:  Arguments:
                   7760:    $contents - data to store
                   7761:    $filename - filename to store $contents into
                   7762: 
                   7763:  Returns:
                   7764:    result value from &Apache::lonnet::finishuserfileupload
                   7765: 
1.423     albertel 7766: =cut
                   7767: 
1.157     albertel 7768: sub lonnet_putfile {
                   7769:     my ($contents,$filename)=@_;
1.257     albertel 7770:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7771:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7772:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7773:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7774: 
                   7775: }
                   7776: 
1.423     albertel 7777: =pod
                   7778: 
                   7779: =item scantron_putfile
                   7780: 
1.659     raeburn  7781:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7782:     scan_data hash. (Does not modify the original version only the
                   7783:     corrected and skipped versions.
                   7784: 
                   7785:  Arguments:
                   7786:     $scanlines - hash ref that looks like the first return value from
                   7787:                  &scantron_getfile()
                   7788:     $scan_data - hash ref that looks like the second return value from
                   7789:                  &scantron_getfile()
                   7790: 
1.423     albertel 7791: =cut
                   7792: 
1.157     albertel 7793: sub scantron_putfile {
                   7794:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7795:     #FIXME really would prefer a scantron directory
1.257     albertel 7796:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7797:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7798:     if ($scanlines) {
                   7799: 	my $prefix='scantron_';
1.157     albertel 7800: # no need to update orig, shouldn't change
                   7801: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7802: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7803: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7804: 			$prefix.'corrected_'.
1.257     albertel 7805: 			$env{'form.scantron_selectfile'});
1.200     albertel 7806: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7807: 			$prefix.'skipped_'.
1.257     albertel 7808: 			$env{'form.scantron_selectfile'});
1.200     albertel 7809:     }
1.175     albertel 7810:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7811: }
                   7812: 
1.423     albertel 7813: =pod
                   7814: 
                   7815: =item scantron_get_line
                   7816: 
1.424     albertel 7817:    Returns the correct version of the scanline
                   7818: 
                   7819:  Arguments:
                   7820:     $scanlines - hash ref that looks like the first return value from
                   7821:                  &scantron_getfile()
                   7822:     $scan_data - hash ref that looks like the second return value from
                   7823:                  &scantron_getfile()
                   7824:     $i         - number of the requested line (starts at 0)
                   7825: 
                   7826:  Returns:
                   7827:    A scanline, (either the original or the corrected one if it
                   7828:    exists), or undef if the requested scanline should be
                   7829:    skipped. (Either because it's an skipped scanline, or it's an
                   7830:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7831:    pass.
                   7832: 
1.423     albertel 7833: =cut
                   7834: 
1.157     albertel 7835: sub scantron_get_line {
1.200     albertel 7836:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7837:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7838:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7839:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7840:     return $scanlines->{'orig'}[$i]; 
                   7841: }
                   7842: 
1.423     albertel 7843: =pod
                   7844: 
                   7845: =item scantron_todo_count
                   7846: 
1.424     albertel 7847:     Counts the number of scanlines that need processing.
                   7848: 
                   7849:  Arguments:
                   7850:     $scanlines - hash ref that looks like the first return value from
                   7851:                  &scantron_getfile()
                   7852:     $scan_data - hash ref that looks like the second return value from
                   7853:                  &scantron_getfile()
                   7854: 
                   7855:  Returns:
                   7856:     $count - number of scanlines to process
                   7857: 
1.423     albertel 7858: =cut
                   7859: 
1.200     albertel 7860: sub get_todo_count {
                   7861:     my ($scanlines,$scan_data)=@_;
                   7862:     my $count=0;
                   7863:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7864: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7865: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7866: 	$count++;
                   7867:     }
                   7868:     return $count;
                   7869: }
                   7870: 
1.423     albertel 7871: =pod
                   7872: 
                   7873: =item scantron_put_line
                   7874: 
1.659     raeburn  7875:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7876:     data file.
                   7877: 
                   7878:  Arguments:
                   7879:     $scanlines - hash ref that looks like the first return value from
                   7880:                  &scantron_getfile()
                   7881:     $scan_data - hash ref that looks like the second return value from
                   7882:                  &scantron_getfile()
                   7883:     $i         - line number to update
                   7884:     $newline   - contents of the updated scanline
                   7885:     $skip      - if true make the line for skipping and update the
                   7886:                  'skipped' file
                   7887: 
1.423     albertel 7888: =cut
                   7889: 
1.157     albertel 7890: sub scantron_put_line {
1.200     albertel 7891:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7892:     if ($skip) {
                   7893: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7894: 	&start_skipping($scan_data,$i);
1.157     albertel 7895: 	return;
                   7896:     }
                   7897:     $scanlines->{'corrected'}[$i]=$newline;
                   7898: }
                   7899: 
1.423     albertel 7900: =pod
                   7901: 
                   7902: =item scantron_clear_skip
                   7903: 
1.424     albertel 7904:    Remove a line from the 'skipped' file
                   7905: 
                   7906:  Arguments:
                   7907:     $scanlines - hash ref that looks like the first return value from
                   7908:                  &scantron_getfile()
                   7909:     $scan_data - hash ref that looks like the second return value from
                   7910:                  &scantron_getfile()
                   7911:     $i         - line number to update
                   7912: 
1.423     albertel 7913: =cut
                   7914: 
1.376     albertel 7915: sub scantron_clear_skip {
                   7916:     my ($scanlines,$scan_data,$i)=@_;
                   7917:     if (exists($scanlines->{'skipped'}[$i])) {
                   7918: 	undef($scanlines->{'skipped'}[$i]);
                   7919: 	return 1;
                   7920:     }
                   7921:     return 0;
                   7922: }
                   7923: 
1.423     albertel 7924: =pod
                   7925: 
                   7926: =item scantron_filter_not_exam
                   7927: 
1.424     albertel 7928:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7929:    filter out resources that are not marked as 'exam' mode
                   7930: 
1.423     albertel 7931: =cut
                   7932: 
1.334     albertel 7933: sub scantron_filter_not_exam {
                   7934:     my ($curres)=@_;
                   7935:     
                   7936:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7937: 	# if the user has asked to not have either hidden
                   7938: 	# or 'randomout' controlled resources to be graded
                   7939: 	# don't include them
                   7940: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7941: 	    && $curres->randomout) {
                   7942: 	    return 0;
                   7943: 	}
                   7944: 	return 1;
                   7945:     }
                   7946:     return 0;
                   7947: }
                   7948: 
1.423     albertel 7949: =pod
                   7950: 
                   7951: =item scantron_validate_sequence
                   7952: 
1.424     albertel 7953:     Validates the selected sequence, checking for resource that are
                   7954:     not set to exam mode.
                   7955: 
1.423     albertel 7956: =cut
                   7957: 
1.334     albertel 7958: sub scantron_validate_sequence {
                   7959:     my ($r,$currentphase) = @_;
                   7960: 
                   7961:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7962:     unless (ref($navmap)) {
                   7963:         $r->print(&navmap_errormsg());
                   7964:         return (1,$currentphase);
                   7965:     }
1.334     albertel 7966:     my (undef,undef,$sequence)=
                   7967: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7968: 
                   7969:     my $map=$navmap->getResourceByUrl($sequence);
                   7970: 
                   7971:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7972:                                     value="ignore" />');
                   7973:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7974: 	my @resources=
                   7975: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7976: 	if (@resources) {
1.675     bisitz   7977: 	    $r->print(
                   7978:                 '<p class="LC_warning">'
                   7979:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7980:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7981:                    .' work correctly.')
                   7982:                .'</p>'
                   7983:             );
1.334     albertel 7984: 	    return (1,$currentphase);
                   7985: 	}
                   7986:     }
                   7987: 
                   7988:     return (0,$currentphase+1);
                   7989: }
                   7990: 
1.423     albertel 7991: 
                   7992: 
1.157     albertel 7993: sub scantron_validate_ID {
1.770     raeburn  7994:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 7995:     
                   7996:     #get student info
                   7997:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7998:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  7999:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 8000: 
                   8001:     #get scantron line setup
1.754     raeburn  8002:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8003:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  8004: 
                   8005:     my $nav_error;
1.649     raeburn  8006:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  8007:     if ($nav_error) {
                   8008:         $r->print(&navmap_errormsg());
                   8009:         return(1,$currentphase);
                   8010:     }
1.157     albertel 8011: 
                   8012:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  8013:     my $unsavedskips = 0;
1.157     albertel 8014:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8015: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8016: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8017: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8018: 						 $scan_data);
                   8019: 	my $id=$$scan_record{'scantron.ID'};
                   8020: 	my $found;
                   8021: 	foreach my $checkid (keys(%idmap)) {
                   8022: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   8023: 	}
                   8024: 	if ($found) {
                   8025: 	    my $username=$idmap{$found};
1.770     raeburn  8026:             if ($checksec) {
                   8027:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   8028:                     my $stusec = $classlist->{$username}->[$secidx];
                   8029:                     if ($stusec ne $checksec) {
                   8030:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   8031:                             my $skip=1;
                   8032:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   8033:                             if (ref($skipbysec) eq 'HASH') {
                   8034:                                 if ($stusec eq '') {
                   8035:                                     $skipbysec->{'none'} ++;
                   8036:                                 } else {
                   8037:                                     $skipbysec->{$stusec} ++;
                   8038:                                 }
                   8039:                             }
                   8040:                             $unsavedskips ++;
                   8041:                             next;
                   8042:                         }
                   8043:                     }
                   8044:                 }
                   8045:             }
1.157     albertel 8046: 	    if ($found{'ids'}{$found}) {
                   8047: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   8048: 					 $line,'duplicateID',$found);
1.770     raeburn  8049:                 if ($unsavedskips) {
                   8050:                     &scantron_putfile($scanlines,$scan_data);
                   8051:                     $unsavedskips = 0;
                   8052:                 }
1.194     albertel 8053: 		return(1,$currentphase);
1.157     albertel 8054: 	    } elsif ($found{'usernames'}{$username}) {
                   8055: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   8056: 					 $line,'duplicateID',$username);
1.770     raeburn  8057:                 if ($unsavedskips) {
                   8058:                     &scantron_putfile($scanlines,$scan_data);
                   8059:                     $unsavedskips = 0;
                   8060:                 }
1.194     albertel 8061: 		return(1,$currentphase);
1.157     albertel 8062: 	    }
1.186     albertel 8063: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 8064: 	    $found{'ids'}{$found}++;
                   8065: 	    $found{'usernames'}{$username}++;
                   8066: 	} else {
                   8067: 	    if ($id =~ /^\s*$/) {
1.158     albertel 8068: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  8069:                 if (($checksec && $username ne '')) {
                   8070:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   8071:                         my $stusec = $classlist->{$username}->[$secidx];
                   8072:                         if ($stusec ne $checksec) {
                   8073:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   8074:                                 my $skip=1;
                   8075:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   8076:                                 if (ref($skipbysec) eq 'HASH') {
                   8077:                                     if ($stusec eq '') {
                   8078:                                         $skipbysec->{'none'} ++;
                   8079:                                     } else {
                   8080:                                         $skipbysec->{$stusec} ++;
                   8081:                                     }
                   8082:                                 }
                   8083:                                 $unsavedskips ++;
                   8084:                                 next;
                   8085:                             }
                   8086:                         }
                   8087:                     }
                   8088: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 8089: 		    &scantron_get_correction($r,$i,$scan_record,
                   8090: 					     \%scantron_config,
                   8091: 					     $line,'duplicateID',$username);
1.770     raeburn  8092:                     if ($unsavedskips) {
                   8093:                         &scantron_putfile($scanlines,$scan_data);
                   8094:                         $unsavedskips = 0;
                   8095:                     }
1.194     albertel 8096: 		    return(1,$currentphase);
1.157     albertel 8097: 		} elsif (!defined($username)) {
                   8098: 		    &scantron_get_correction($r,$i,$scan_record,
                   8099: 					     \%scantron_config,
                   8100: 					     $line,'incorrectID');
1.770     raeburn  8101:                     if ($unsavedskips) {
                   8102:                         &scantron_putfile($scanlines,$scan_data);
                   8103:                         $unsavedskips = 0;
                   8104:                     }
1.194     albertel 8105: 		    return(1,$currentphase);
1.157     albertel 8106: 		}
                   8107: 		$found{'usernames'}{$username}++;
                   8108: 	    } else {
                   8109: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   8110: 					 $line,'incorrectID');
1.770     raeburn  8111:                 if ($unsavedskips) {
                   8112:                     &scantron_putfile($scanlines,$scan_data);
                   8113:                     $unsavedskips = 0;
                   8114:                 }
1.194     albertel 8115: 		return(1,$currentphase);
1.157     albertel 8116: 	    }
                   8117: 	}
                   8118:     }
1.770     raeburn  8119:     if ($unsavedskips) {
                   8120:         &scantron_putfile($scanlines,$scan_data);
                   8121:         $unsavedskips = 0;
                   8122:     }
1.157     albertel 8123:     return (0,$currentphase+1);
                   8124: }
                   8125: 
1.770     raeburn  8126: sub scantron_get_sections {
                   8127:     my %bysec;
                   8128:     if ($env{'form.scantron_format'} ne '') {
                   8129:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   8130:         my ($scanlines,$scan_data)=&scantron_getfile();
                   8131:         my $classlist=&Apache::loncoursedata::get_classlist();
                   8132:         my %idmap=&username_to_idmap($classlist);
                   8133:         foreach my $key (keys(%idmap)) {
                   8134:             my $lckey = lc($key);
                   8135:             $idmap{$lckey} = $idmap{$key};
                   8136:         }
                   8137:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   8138:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8139:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   8140:             if ($line=~/^[\s\cz]*$/) { next; }
                   8141:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8142:                                                      $scan_data);
                   8143:             my $id=lc($$scan_record{'scantron.ID'});
                   8144:             if (exists($idmap{$id})) {
                   8145:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   8146:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   8147:                     if ($stusec eq '') {
                   8148:                         $bysec{'none'} ++;
                   8149:                     } else {
                   8150:                         $bysec{$stusec} ++;
                   8151:                     }
                   8152:                 }
                   8153:             }
                   8154:         }
                   8155:     }
                   8156:     return %bysec;
                   8157: }
1.423     albertel 8158: 
1.157     albertel 8159: sub scantron_get_correction {
1.691     raeburn  8160:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   8161:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 8162: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 8163: #to show both the current line and the previous one and allow skipping
                   8164: #the previous one or the current one
                   8165: 
1.333     albertel 8166:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   8167:         $r->print(
                   8168:             '<p class="LC_warning">'
                   8169:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   8170:                 "<b>$error</b>",
                   8171:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   8172:            ."</p> \n");
1.157     albertel 8173:     } else {
1.658     bisitz   8174:         $r->print(
                   8175:             '<p class="LC_warning">'
                   8176:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8177:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8178:            ."</p> \n");
                   8179:     }
                   8180:     my $message =
                   8181:         '<p>'
                   8182:        .&mt('The ID on the form is [_1]',
                   8183:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8184:        .'<br />'
1.665     raeburn  8185:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   8186:             $$scan_record{'scantron.LastName'},
                   8187:             $$scan_record{'scantron.FirstName'})
                   8188:        .'</p>';
1.242     albertel 8189: 
1.157     albertel 8190:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8191:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8192:                            # Array populated for doublebubble or
                   8193:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8194:                            # to validate radio button checking   
                   8195: 
1.157     albertel 8196:     if ($error =~ /ID$/) {
1.186     albertel 8197: 	if ($error eq 'incorrectID') {
1.658     bisitz   8198:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8199: 		      "</p>\n");
1.157     albertel 8200: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   8201:             $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 8202: 	}
1.242     albertel 8203: 	$r->print($message);
1.492     albertel 8204: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8205: 	$r->print("\n<ul><li> ");
                   8206: 	#FIXME it would be nice if this sent back the user ID and
                   8207: 	#could do partial userID matches
                   8208: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8209: 				       'scantron_username','scantron_domain'));
                   8210: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   8211: 	$r->print("\n:\n".
1.257     albertel 8212: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8213: 
                   8214: 	$r->print('</li>');
1.186     albertel 8215:     } elsif ($error =~ /CODE$/) {
                   8216: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   8217: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8218: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   8219: 	    $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 8220: 	}
1.658     bisitz   8221: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   8222: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8223:                  ."</p>\n");
1.242     albertel 8224: 	$r->print($message);
1.658     bisitz   8225: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8226: 	$r->print("\n<br /> ");
1.194     albertel 8227: 	my $i=0;
1.273     albertel 8228: 	if ($error eq 'incorrectCODE' 
                   8229: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8230: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8231: 	    if ($closest > 0) {
                   8232: 		foreach my $testcode (@{$closest}) {
                   8233: 		    my $checked='';
1.569     bisitz   8234: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8235: 		    $r->print("
                   8236:    <label>
1.569     bisitz   8237:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8238:        ".&mt("Use the similar CODE [_1] instead.",
                   8239: 	    "<b><tt>".$testcode."</tt></b>")."
                   8240:     </label>
                   8241:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8242: 		    $r->print("\n<br />");
                   8243: 		    $i++;
                   8244: 		}
1.194     albertel 8245: 	    }
                   8246: 	}
1.273     albertel 8247: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8248: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8249: 	    $r->print("
                   8250:     <label>
1.569     bisitz   8251:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  8252:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8253: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8254:     </label>");
1.273     albertel 8255: 	    $r->print("\n<br />");
                   8256: 	}
1.194     albertel 8257: 
1.597     wenzelju 8258: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8259: function change_radio(field) {
1.190     albertel 8260:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8261:     var i;
                   8262:     for (i=0;i<slct.length;i++) {
                   8263:         if (slct[i].value==field) { slct[i].checked=true; }
                   8264:     }
                   8265: }
                   8266: ENDSCRIPT
1.187     albertel 8267: 	my $href="/adm/pickcode?".
1.359     www      8268: 	   "form=".&escape("scantronupload").
                   8269: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8270: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8271: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8272: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8273: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8274: 	    $r->print("
                   8275:     <label>
                   8276:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8277:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8278: 	     "<a target='_blank' href='$href'>","</a>")."
                   8279:     </label> 
1.558     bisitz   8280:     ".&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 8281: 	    $r->print("\n<br />");
                   8282: 	}
1.492     albertel 8283: 	$r->print("
                   8284:     <label>
                   8285:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8286:        ".&mt("Use [_1] as the CODE.",
                   8287: 	     "</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 8288: 	$r->print("\n<br /><br />");
1.157     albertel 8289:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   8290: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8291: 
                   8292: 	# The form field scantron_questions is acutally a list of line numbers.
                   8293: 	# represented by this form so:
                   8294: 
1.691     raeburn  8295: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8296:                                                 $respnumlookup,$startline);
1.497     foxr     8297: 
1.157     albertel 8298: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8299: 		  $line_list.'" />');
1.242     albertel 8300: 	$r->print($message);
1.492     albertel 8301: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8302: 	foreach my $question (@{$arg}) {
1.503     raeburn  8303: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8304:                                                    $scan_record, $error,
                   8305:                                                    $randomorder,$randompick,
                   8306:                                                    $respnumlookup,$startline);
1.524     raeburn  8307:             push(@lines_to_correct,@linenums);
1.157     albertel 8308: 	}
1.503     raeburn  8309:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8310:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   8311: 	$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 8312: 	$r->print($message);
1.492     albertel 8313: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8314: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8315: 
1.503     raeburn  8316: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8317: 	# a list of question numbers. Therefore:
                   8318: 	#
1.691     raeburn  8319: 
                   8320: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8321:                                                 $respnumlookup,$startline);
1.497     foxr     8322: 
1.157     albertel 8323: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8324: 		  $line_list.'" />');
1.157     albertel 8325: 	foreach my $question (@{$arg}) {
1.503     raeburn  8326: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8327:                                                    $scan_record, $error,
                   8328:                                                    $randomorder,$randompick,
                   8329:                                                    $respnumlookup,$startline);
1.524     raeburn  8330:             push(@lines_to_correct,@linenums);
1.157     albertel 8331: 	}
1.503     raeburn  8332:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8333:     } else {
                   8334: 	$r->print("\n<ul>");
                   8335:     }
                   8336:     $r->print("\n</li></ul>");
1.497     foxr     8337: }
                   8338: 
1.503     raeburn  8339: sub verify_bubbles_checked {
                   8340:     my (@ansnums) = @_;
                   8341:     my $ansnumstr = join('","',@ansnums);
                   8342:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  8343:     &js_escape(\$warning);
1.767     raeburn  8344:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8345: function verify_bubble_radio(form) {
                   8346:     var ansnumArray = new Array ("$ansnumstr");
                   8347:     var need_bubble_count = 0;
                   8348:     for (var i=0; i<ansnumArray.length; i++) {
                   8349:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8350:             var bubble_picked = 0; 
                   8351:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8352:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8353:                     bubble_picked = 1;
                   8354:                 }
                   8355:             }
                   8356:             if (bubble_picked == 0) {
                   8357:                 need_bubble_count ++;
                   8358:             }
                   8359:         }
                   8360:     }
                   8361:     if (need_bubble_count) {
                   8362:         alert("$warning");
                   8363:         return;
                   8364:     }
                   8365:     form.submit(); 
                   8366: }
                   8367: ENDSCRIPT
                   8368:     return $output;
                   8369: }
                   8370: 
1.497     foxr     8371: =pod
                   8372: 
                   8373: =item  questions_to_line_list
1.157     albertel 8374: 
1.497     foxr     8375: Converts a list of questions into a string of comma separated
                   8376: line numbers in the answer sheet used by the questions.  This is
                   8377: used to fill in the scantron_questions form field.
                   8378: 
                   8379:   Arguments:
                   8380:      questions    - Reference to an array of questions.
1.691     raeburn  8381:      randomorder  - True if randomorder in use.
                   8382:      randompick   - True if randompick in use.
                   8383:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8384:                      for current line to question number used for same question
                   8385:                      in "Master Seqence" (as seen by Course Coordinator).
                   8386:      startline    - Reference to hash where key is question number (0 is first)
                   8387:                     and key is number of first bubble line for current student
                   8388:                     or code-based randompick and/or randomorder.
1.693     raeburn  8389: 
1.497     foxr     8390: =cut
                   8391: 
                   8392: 
                   8393: sub questions_to_line_list {
1.691     raeburn  8394:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8395:     my @lines;
                   8396: 
1.503     raeburn  8397:     foreach my $item (@{$questions}) {
                   8398:         my $question = $item;
                   8399:         my ($first,$count,$last);
                   8400:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8401:             $question = $1;
                   8402:             my $subquestion = $2;
1.691     raeburn  8403:             my $responsenum = $question-1;
                   8404:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8405:                 $responsenum = $respnumlookup->{$question-1};
                   8406:                 if (ref($startline) eq 'HASH') {
                   8407:                     $first = $startline->{$question-1} + 1;
                   8408:                 }
                   8409:             } else {
                   8410:                 $first = $first_bubble_line{$responsenum} + 1;
                   8411:             }
                   8412:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8413:             my $subcount = 1;
                   8414:             while ($subcount<$subquestion) {
                   8415:                 $first += $subans[$subcount-1];
                   8416:                 $subcount ++;
                   8417:             }
                   8418:             $count = $subans[$subquestion-1];
                   8419:         } else {
1.691     raeburn  8420:             my $responsenum = $question-1;
                   8421:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8422:                 $responsenum = $respnumlookup->{$question-1};
                   8423:                 if (ref($startline) eq 'HASH') {
                   8424:                     $first = $startline->{$question-1} + 1;
                   8425:                 }
                   8426:             } else {
                   8427:                 $first = $first_bubble_line{$responsenum} + 1;
                   8428:             }
                   8429: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8430:         }
1.506     raeburn  8431:         $last = $first+$count-1;
1.503     raeburn  8432:         push(@lines, ($first..$last));
1.497     foxr     8433:     }
                   8434:     return join(',', @lines);
                   8435: }
                   8436: 
                   8437: =pod 
                   8438: 
                   8439: =item prompt_for_corrections
                   8440: 
                   8441: Prompts for a potentially multiline correction to the
                   8442: user's bubbling (factors out common code from scantron_get_correction
                   8443: for multi and missing bubble cases).
                   8444: 
                   8445:  Arguments:
                   8446:    $r           - Apache request object.
                   8447:    $question    - The question number to prompt for.
                   8448:    $scan_config - The scantron file configuration hash.
                   8449:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8450:    $error       - Type of error
1.691     raeburn  8451:    $randomorder - True if randomorder in use.
                   8452:    $randompick  - True if randompick in use.
                   8453:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8454:                     for current line to question number used for same question
                   8455:                     in "Master Seqence" (as seen by Course Coordinator).
                   8456:    $startline   - Reference to hash where key is question number (0 is first)
                   8457:                   and value is number of first bubble line for current student
                   8458:                   or code-based randompick and/or randomorder.
                   8459: 
1.497     foxr     8460: 
                   8461:  Implicit inputs:
                   8462:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8463:                                   Numbered from 0 (but question numbers are from
                   8464:                                   1.
                   8465:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8466:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8467:                                   type problems render as separate sub-questions, 
1.503     raeburn  8468:                                   in exam mode. This hash contains a 
                   8469:                                   comma-separated list of the lines per 
                   8470:                                   sub-question.
1.510     raeburn  8471:    %responsetype_per_response   - essayresponse, formularesponse,
                   8472:                                   stringresponse, imageresponse, reactionresponse,
                   8473:                                   and organicresponse type problem parts can have
1.503     raeburn  8474:                                   multiple lines per response if the weight
                   8475:                                   assigned exceeds 10.  In this case, only
                   8476:                                   one bubble per line is permitted, but more 
                   8477:                                   than one line might contain bubbles, e.g.
                   8478:                                   bubbling of: line 1 - J, line 2 - J, 
                   8479:                                   line 3 - B would assign 22 points.  
1.497     foxr     8480: 
                   8481: =cut
                   8482: 
                   8483: sub prompt_for_corrections {
1.691     raeburn  8484:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8485:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8486:     my ($current_line,$lines);
                   8487:     my @linenums;
                   8488:     my $questionnum = $question;
1.691     raeburn  8489:     my ($first,$responsenum);
1.503     raeburn  8490:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8491:         $question = $1;
                   8492:         my $subquestion = $2;
1.691     raeburn  8493:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8494:             $responsenum = $respnumlookup->{$question-1};
                   8495:             if (ref($startline) eq 'HASH') {
                   8496:                 $first = $startline->{$question-1};
                   8497:             }
                   8498:         } else {
                   8499:             $responsenum = $question-1;
1.714     raeburn  8500:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8501:         }
                   8502:         $current_line = $first + 1 ;
                   8503:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8504:         my $subcount = 1;
                   8505:         while ($subcount<$subquestion) {
                   8506:             $current_line += $subans[$subcount-1];
                   8507:             $subcount ++;
                   8508:         }
                   8509:         $lines = $subans[$subquestion-1];
                   8510:     } else {
1.691     raeburn  8511:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8512:             $responsenum = $respnumlookup->{$question-1};
                   8513:             if (ref($startline) eq 'HASH') { 
                   8514:                 $first = $startline->{$question-1};
                   8515:             }
                   8516:         } else {
                   8517:             $responsenum = $question-1;
                   8518:             $first = $first_bubble_line{$responsenum};
                   8519:         }
                   8520:         $current_line = $first + 1;
                   8521:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8522:     }
1.497     foxr     8523:     if ($lines > 1) {
1.503     raeburn  8524:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8525:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8526:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8527:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8528:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8529:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8530:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8531:             $r->print(
                   8532:                 &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)
                   8533:                .'<br /><br />'
                   8534:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8535:                .'<br />'
                   8536:                .&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.')
                   8537:                .'<br />'
                   8538:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8539:                .'<br /><br />'
                   8540:             );
1.503     raeburn  8541:         } else {
                   8542:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8543:         }
1.497     foxr     8544:     }
                   8545:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8546:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8547: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8548: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8549:         push(@linenums,$current_line);
1.497     foxr     8550: 	$current_line++;
                   8551:     }
                   8552:     if ($lines > 1) {
                   8553: 	$r->print("<hr /><br />");
                   8554:     }
1.503     raeburn  8555:     return @linenums;
1.157     albertel 8556: }
1.423     albertel 8557: 
                   8558: =pod
                   8559: 
                   8560: =item scantron_bubble_selector
                   8561:   
                   8562:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8563:    possibly showing the existing the selected bubbles if known
1.423     albertel 8564: 
                   8565:  Arguments:
                   8566:     $r           - Apache request object
1.754     raeburn  8567:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8568:     $line        - Number of the line being displayed.
1.503     raeburn  8569:     $questionnum - Question number (may include subquestion)
                   8570:     $error       - Type of error.
1.497     foxr     8571:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8572: 
                   8573: =cut
                   8574: 
1.157     albertel 8575: sub scantron_bubble_selector {
1.503     raeburn  8576:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8577:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8578: 
                   8579:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8580:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8581:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8582:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8583:             $max=$$scan_config{'BubblesPerRow'};
                   8584:             if (($scmode eq 'number') && ($max > 10)) {
                   8585:                 $max = 10;
                   8586:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8587:                 $max = 26;
                   8588:             }
                   8589:         } else {
                   8590:             $max = 10;
                   8591:         }
                   8592:     }
1.274     albertel 8593: 
1.157     albertel 8594:     my @alphabet=('A'..'Z');
1.503     raeburn  8595:     $r->print(&Apache::loncommon::start_data_table().
                   8596:               &Apache::loncommon::start_data_table_row());
                   8597:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8598:     for (my $i=0;$i<$max+1;$i++) {
                   8599: 	$r->print("\n".'<td align="center">');
                   8600: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8601: 	else { $r->print('&nbsp;'); }
                   8602: 	$r->print('</td>');
                   8603:     }
1.503     raeburn  8604:     $r->print(&Apache::loncommon::end_data_table_row().
                   8605:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8606:     for (my $i=0;$i<$max;$i++) {
                   8607: 	$r->print("\n".
                   8608: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8609: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8610:     }
1.503     raeburn  8611:     my $nobub_checked = ' ';
                   8612:     if ($error eq 'missingbubble') {
                   8613:         $nobub_checked = ' checked = "checked" ';
                   8614:     }
                   8615:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8616: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8617:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8618:               $line.'" value="'.$questionnum.'" /></td>');
                   8619:     $r->print(&Apache::loncommon::end_data_table_row().
                   8620:               &Apache::loncommon::end_data_table());
1.157     albertel 8621: }
                   8622: 
1.423     albertel 8623: =pod
                   8624: 
                   8625: =item num_matches
                   8626: 
1.424     albertel 8627:    Counts the number of characters that are the same between the two arguments.
                   8628: 
                   8629:  Arguments:
                   8630:    $orig - CODE from the scanline
                   8631:    $code - CODE to match against
                   8632: 
                   8633:  Returns:
                   8634:    $count - integer count of the number of same characters between the
                   8635:             two arguments
                   8636: 
1.423     albertel 8637: =cut
                   8638: 
1.194     albertel 8639: sub num_matches {
                   8640:     my ($orig,$code) = @_;
                   8641:     my @code=split(//,$code);
                   8642:     my @orig=split(//,$orig);
                   8643:     my $same=0;
                   8644:     for (my $i=0;$i<scalar(@code);$i++) {
                   8645: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8646:     }
                   8647:     return $same;
                   8648: }
                   8649: 
1.423     albertel 8650: =pod
                   8651: 
                   8652: =item scantron_get_closely_matching_CODEs
                   8653: 
1.424     albertel 8654:    Cycles through all CODEs and finds the set that has the greatest
                   8655:    number of same characters as the provided CODE
                   8656: 
                   8657:  Arguments:
                   8658:    $allcodes - hash ref returned by &get_codes()
                   8659:    $CODE     - CODE from the current scanline
                   8660: 
                   8661:  Returns:
                   8662:    2 element list
                   8663:     - first elements is number of how closely matching the best fit is 
                   8664:       (5 means best set has 5 matching characters)
                   8665:     - second element is an arrary ref containing the set of valid CODEs
                   8666:       that best fit the passed in CODE
                   8667: 
1.423     albertel 8668: =cut
                   8669: 
1.194     albertel 8670: sub scantron_get_closely_matching_CODEs {
                   8671:     my ($allcodes,$CODE)=@_;
                   8672:     my @CODEs;
                   8673:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8674: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8675:     }
                   8676: 
                   8677:     return ($#CODEs,$CODEs[-1]);
                   8678: }
                   8679: 
1.423     albertel 8680: =pod
                   8681: 
                   8682: =item get_codes
                   8683: 
1.424     albertel 8684:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8685:    set of remembered CODEs.
                   8686: 
                   8687:  Arguments:
                   8688:   $old_name - name of the set of remembered CODEs
                   8689:   $cdom     - domain of the course
                   8690:   $cnum     - internal course name
                   8691: 
                   8692:  Returns:
                   8693:   %allcodes - keys are the valid CODEs, values are all 1
                   8694: 
1.423     albertel 8695: =cut
                   8696: 
1.194     albertel 8697: sub get_codes {
1.280     foxr     8698:     my ($old_name, $cdom, $cnum) = @_;
                   8699:     if (!$old_name) {
                   8700: 	$old_name=$env{'form.scantron_CODElist'};
                   8701:     }
                   8702:     if (!$cdom) {
                   8703: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8704:     }
                   8705:     if (!$cnum) {
                   8706: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8707:     }
1.278     albertel 8708:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8709: 				    $cdom,$cnum);
                   8710:     my %allcodes;
                   8711:     if ($result{"type\0$old_name"} eq 'number') {
                   8712: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8713:     } else {
                   8714: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8715:     }
1.194     albertel 8716:     return %allcodes;
                   8717: }
                   8718: 
1.423     albertel 8719: =pod
                   8720: 
                   8721: =item scantron_validate_CODE
                   8722: 
1.424     albertel 8723:    Validates all scanlines in the selected file to not have any
                   8724:    invalid or underspecified CODEs and that none of the codes are
                   8725:    duplicated if this was requested.
                   8726: 
1.423     albertel 8727: =cut
                   8728: 
1.157     albertel 8729: sub scantron_validate_CODE {
                   8730:     my ($r,$currentphase) = @_;
1.754     raeburn  8731:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8732:     if ($scantron_config{'CODElocation'} &&
                   8733: 	$scantron_config{'CODEstart'} &&
                   8734: 	$scantron_config{'CODElength'}) {
1.257     albertel 8735: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8736: 	    &FIXME_blow_up()
                   8737: 	}
                   8738:     } else {
                   8739: 	return (0,$currentphase+1);
                   8740:     }
                   8741:     
                   8742:     my %usedCODEs;
                   8743: 
1.194     albertel 8744:     my %allcodes=&get_codes();
1.186     albertel 8745: 
1.582     raeburn  8746:     my $nav_error;
1.649     raeburn  8747:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8748:     if ($nav_error) {
                   8749:         $r->print(&navmap_errormsg());
                   8750:         return(1,$currentphase);
                   8751:     }
1.447     foxr     8752: 
1.186     albertel 8753:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8754:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8755: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8756: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8757: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8758: 						 $scan_data);
                   8759: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8760: 	my $error=0;
1.224     albertel 8761: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8762: 	    &scantron_get_correction($r,$i,$scan_record,
                   8763: 				     \%scantron_config,
                   8764: 				     $line,'incorrectCODE',\%allcodes);
                   8765: 	    return(1,$currentphase);
                   8766: 	}
1.221     albertel 8767: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8768: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8769: 	    &scantron_get_correction($r,$i,$scan_record,
                   8770: 				     \%scantron_config,
1.194     albertel 8771: 				     $line,'incorrectCODE',\%allcodes);
                   8772: 	    return(1,$currentphase);
1.186     albertel 8773: 	}
1.214     albertel 8774: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8775: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8776: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8777: 	    &scantron_get_correction($r,$i,$scan_record,
                   8778: 				     \%scantron_config,
1.194     albertel 8779: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8780: 	    return(1,$currentphase);
1.186     albertel 8781: 	}
1.524     raeburn  8782: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8783:     }
1.157     albertel 8784:     return (0,$currentphase+1);
                   8785: }
                   8786: 
1.423     albertel 8787: =pod
                   8788: 
                   8789: =item scantron_validate_doublebubble
                   8790: 
1.424     albertel 8791:    Validates all scanlines in the selected file to not have any
                   8792:    bubble lines with multiple bubbles marked.
                   8793: 
1.423     albertel 8794: =cut
                   8795: 
1.157     albertel 8796: sub scantron_validate_doublebubble {
                   8797:     my ($r,$currentphase) = @_;
                   8798:     #get student info
                   8799:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8800:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8801:     my (undef,undef,$sequence)=
                   8802:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8803: 
                   8804:     #get scantron line setup
1.754     raeburn  8805:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8806:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8807: 
                   8808:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8809:     unless (ref($navmap)) {
                   8810:         $r->print(&navmap_errormsg());
                   8811:         return(1,$currentphase);
                   8812:     }
                   8813:     my $map=$navmap->getResourceByUrl($sequence);
                   8814:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8815:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8816:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8817:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8818: 
1.583     raeburn  8819:     my $nav_error;
1.691     raeburn  8820:     if (ref($map)) {
                   8821:         $randomorder = $map->randomorder();
                   8822:         $randompick = $map->randompick();
1.788     raeburn  8823:         unless ($randomorder || $randompick) {
                   8824:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8825:                 if ($res->randomorder()) {
                   8826:                     $randomorder = 1;
                   8827:                 }
                   8828:                 if ($res->randompick()) {
                   8829:                     $randompick = 1;
                   8830:                 }
                   8831:                 last if ($randomorder || $randompick);
                   8832:             }
                   8833:         }
1.691     raeburn  8834:         if ($randomorder || $randompick) {
                   8835:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8836:             if ($nav_error) {
                   8837:                 $r->print(&navmap_errormsg());
                   8838:                 return(1,$currentphase);
                   8839:             }
                   8840:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8841:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8842:         }
                   8843:     } else {
                   8844:         $r->print(&navmap_errormsg());
                   8845:         return(1,$currentphase);
                   8846:     }
                   8847: 
1.649     raeburn  8848:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8849:     if ($nav_error) {
                   8850:         $r->print(&navmap_errormsg());
                   8851:         return(1,$currentphase);
                   8852:     }
1.447     foxr     8853: 
1.157     albertel 8854:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8855: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8856: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8857: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8858: 						 $scan_data,undef,\%idmap,$randomorder,
                   8859:                                                  $randompick,$sequence,\@master_seq,
                   8860:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8861:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8862: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8863: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8864: 				 'doublebubble',
1.691     raeburn  8865: 				 $$scan_record{'scantron.doubleerror'},
                   8866:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8867:     	return (1,$currentphase);
                   8868:     }
                   8869:     return (0,$currentphase+1);
                   8870: }
                   8871: 
1.423     albertel 8872: 
1.503     raeburn  8873: sub scantron_get_maxbubble {
1.649     raeburn  8874:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8875:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8876: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8877: 	&restore_bubble_lines();
1.257     albertel 8878: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8879:     }
1.330     albertel 8880: 
1.447     foxr     8881:     my (undef, undef, $sequence) =
1.257     albertel 8882: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8883: 
1.447     foxr     8884:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8885:     unless (ref($navmap)) {
                   8886:         if (ref($nav_error)) {
                   8887:             $$nav_error = 1;
                   8888:         }
1.591     raeburn  8889:         return;
1.582     raeburn  8890:     }
1.191     albertel 8891:     my $map=$navmap->getResourceByUrl($sequence);
                   8892:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8893:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8894: 
                   8895:     &Apache::lonxml::clear_problem_counter();
                   8896: 
1.557     raeburn  8897:     my $uname       = $env{'user.name'};
                   8898:     my $udom        = $env{'user.domain'};
1.435     foxr     8899:     my $cid         = $env{'request.course.id'};
                   8900:     my $total_lines = 0;
                   8901:     %bubble_lines_per_response = ();
1.447     foxr     8902:     %first_bubble_line         = ();
1.503     raeburn  8903:     %subdivided_bubble_lines   = ();
                   8904:     %responsetype_per_response = ();
1.691     raeburn  8905:     %masterseq_id_responsenum  = ();
1.554     raeburn  8906: 
1.447     foxr     8907:     my $response_number = 0;
                   8908:     my $bubble_line     = 0;
1.191     albertel 8909:     foreach my $resource (@resources) {
1.691     raeburn  8910:         my $resid = $resource->id(); 
1.672     raeburn  8911:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8912:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8913:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8914: 	    foreach my $part_id (@{$parts}) {
                   8915:                 my $lines;
                   8916: 
                   8917: 	        # TODO - make this a persistent hash not an array.
                   8918: 
                   8919:                 # optionresponse, matchresponse and rankresponse type items 
                   8920:                 # render as separate sub-questions in exam mode.
                   8921:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8922:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8923:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8924:                     my ($numbub,$numshown);
                   8925:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8926:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8927:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8928:                         }
                   8929:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8930:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8931:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8932:                         }
                   8933:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8934:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8935:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8936:                         }
                   8937:                     }
                   8938:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8939:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8940:                     }
1.649     raeburn  8941:                     my $bubbles_per_row =
                   8942:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8943:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8944:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8945:                         $inner_bubble_lines++;
                   8946:                     }
                   8947:                     for (my $i=0; $i<$numshown; $i++) {
                   8948:                         $subdivided_bubble_lines{$response_number} .= 
                   8949:                             $inner_bubble_lines.',';
                   8950:                     }
                   8951:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8952:                     $lines = $numshown * $inner_bubble_lines;
                   8953:                 } else {
                   8954:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8955:                 }
1.542     raeburn  8956: 
                   8957:                 $first_bubble_line{$response_number} = $bubble_line;
                   8958: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8959:                 $responsetype_per_response{$response_number} = 
                   8960:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8961:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8962: 	        $response_number++;
                   8963: 
                   8964: 	        $bubble_line +=  $lines;
                   8965: 	        $total_lines +=  $lines;
                   8966: 	    }
                   8967:         }
                   8968:     }
1.552     raeburn  8969:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8970: 
                   8971:     &save_bubble_lines();
                   8972:     $env{'form.scantron_maxbubble'} =
                   8973: 	$total_lines;
                   8974:     return $env{'form.scantron_maxbubble'};
                   8975: }
1.523     raeburn  8976: 
1.649     raeburn  8977: sub bubblesheet_bubbles_per_row {
                   8978:     my ($scantron_config) = @_;
                   8979:     my $bubbles_per_row;
                   8980:     if (ref($scantron_config) eq 'HASH') {
                   8981:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8982:     }
                   8983:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8984:         $bubbles_per_row = 10;
                   8985:     }
                   8986:     return $bubbles_per_row;
                   8987: }
                   8988: 
1.157     albertel 8989: sub scantron_validate_missingbubbles {
                   8990:     my ($r,$currentphase) = @_;
                   8991:     #get student info
                   8992:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8993:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8994:     my (undef,undef,$sequence)=
                   8995:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8996: 
                   8997:     #get scantron line setup
1.754     raeburn  8998:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8999:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  9000: 
                   9001:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9002:     unless (ref($navmap)) {
                   9003:         $r->print(&navmap_errormsg());
                   9004:         return(1,$currentphase);
                   9005:     }
                   9006: 
                   9007:     my $map=$navmap->getResourceByUrl($sequence);
                   9008:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9009:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9010:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   9011:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9012: 
1.582     raeburn  9013:     my $nav_error;
1.691     raeburn  9014:     if (ref($map)) {
                   9015:         $randomorder = $map->randomorder();
                   9016:         $randompick = $map->randompick();
1.788     raeburn  9017:         unless ($randomorder || $randompick) {
                   9018:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9019:                 if ($res->randomorder()) {
                   9020:                     $randomorder = 1;
                   9021:                 }
                   9022:                 if ($res->randompick()) {
                   9023:                     $randompick = 1;
                   9024:                 }
                   9025:                 last if ($randomorder || $randompick);
                   9026:             }
                   9027:         }
1.691     raeburn  9028:         if ($randomorder || $randompick) {
                   9029:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9030:             if ($nav_error) {
                   9031:                 $r->print(&navmap_errormsg());
                   9032:                 return(1,$currentphase);
                   9033:             }
                   9034:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9035:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   9036:         }
                   9037:     } else {
                   9038:         $r->print(&navmap_errormsg());
                   9039:         return(1,$currentphase);
                   9040:     }
                   9041: 
                   9042: 
1.649     raeburn  9043:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  9044:     if ($nav_error) {
1.691     raeburn  9045:         $r->print(&navmap_errormsg());
1.693     raeburn  9046:         return(1,$currentphase);
1.582     raeburn  9047:     }
1.691     raeburn  9048: 
1.157     albertel 9049:     if (!$max_bubble) { $max_bubble=2**31; }
                   9050:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 9051: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9052: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  9053: 	my $scan_record =
                   9054:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   9055: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   9056:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   9057:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 9058: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   9059: 	my @to_correct;
1.470     foxr     9060: 	
                   9061: 	# Probably here's where the error is...
                   9062: 
1.157     albertel 9063: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  9064:             my $lastbubble;
                   9065:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   9066:                my $question = $1;
                   9067:                my $subquestion = $2;
1.691     raeburn  9068:                my ($first,$responsenum);
                   9069:                if ($randomorder || $randompick) {
                   9070:                    $responsenum = $respnumlookup{$question-1};
                   9071:                    $first = $startline{$question-1};
                   9072:                } else {
                   9073:                    $responsenum = $question-1; 
                   9074:                    $first = $first_bubble_line{$responsenum};
                   9075:                }
                   9076:                if (!defined($first)) { next; }
                   9077:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  9078:                my $subcount = 1;
                   9079:                while ($subcount<$subquestion) {
                   9080:                    $first += $subans[$subcount-1];
                   9081:                    $subcount ++;
                   9082:                }
                   9083:                my $count = $subans[$subquestion-1];
                   9084:                $lastbubble = $first + $count;
                   9085:             } else {
1.691     raeburn  9086:                my ($first,$responsenum);
                   9087:                if ($randomorder || $randompick) {
                   9088:                    $responsenum = $respnumlookup{$missing-1};
                   9089:                    $first = $startline{$missing-1};
                   9090:                } else {
                   9091:                    $responsenum = $missing-1;
                   9092:                    $first = $first_bubble_line{$responsenum};
                   9093:                }
                   9094:                if (!defined($first)) { next; }
                   9095:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  9096:             }
                   9097:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 9098: 	    push(@to_correct,$missing);
                   9099: 	}
                   9100: 	if (@to_correct) {
                   9101: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  9102: 				     $line,'missingbubble',\@to_correct,
                   9103:                                      $randomorder,$randompick,\%respnumlookup,
                   9104:                                      \%startline);
1.157     albertel 9105: 	    return (1,$currentphase);
                   9106: 	}
                   9107: 
                   9108:     }
                   9109:     return (0,$currentphase+1);
                   9110: }
                   9111: 
1.663     raeburn  9112: sub hand_bubble_option {
                   9113:     my (undef, undef, $sequence) =
                   9114:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9115:     return if ($sequence eq '');
                   9116:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9117:     unless (ref($navmap)) {
                   9118:         return;
                   9119:     }
                   9120:     my $needs_hand_bubbles;
                   9121:     my $map=$navmap->getResourceByUrl($sequence);
                   9122:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9123:     foreach my $res (@resources) {
                   9124:         if (ref($res)) {
                   9125:             if ($res->is_problem()) {
                   9126:                 my $partlist = $res->parts();
                   9127:                 foreach my $part (@{ $partlist }) {
                   9128:                     my @types = $res->responseType($part);
                   9129:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   9130:                         $needs_hand_bubbles = 1;
                   9131:                         last;
                   9132:                     }
                   9133:                 }
                   9134:             }
                   9135:         }
                   9136:     }
                   9137:     if ($needs_hand_bubbles) {
1.754     raeburn  9138:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  9139:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9140:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   9141:                &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 />').
                   9142:                '<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  9143:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  9144:     }
                   9145:     return;
                   9146: }
1.423     albertel 9147: 
1.82      albertel 9148: sub scantron_process_students {
1.608     www      9149:     my ($r,$symb) = @_;
1.513     foxr     9150: 
1.257     albertel 9151:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     9152:     if (!$symb) {
                   9153: 	return '';
                   9154:     }
1.324     albertel 9155:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 9156: 
1.754     raeburn  9157:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  9158:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 9159:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 9160:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9161:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 9162:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9163:     unless (ref($navmap)) {
                   9164:         $r->print(&navmap_errormsg());
                   9165:         return '';
1.691     raeburn  9166:     }
1.83      albertel 9167:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9168:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.788     raeburn  9169:         %grader_randomlists_by_symb,%symb_for_examcode);
1.677     raeburn  9170:     if (ref($map)) {
                   9171:         $randomorder = $map->randomorder();
1.689     raeburn  9172:         $randompick = $map->randompick();
1.788     raeburn  9173:         unless ($randomorder || $randompick) {
                   9174:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9175:                 if ($res->randomorder()) {
                   9176:                     $randomorder = 1;
                   9177:                 }
                   9178:                 if ($res->randompick()) {
                   9179:                     $randompick = 1;
                   9180:                 }
                   9181:                 last if ($randomorder || $randompick);
                   9182:             }
                   9183:         }
1.691     raeburn  9184:     } else {
                   9185:         $r->print(&navmap_errormsg());
                   9186:         return '';
1.677     raeburn  9187:     }
1.691     raeburn  9188:     my $nav_error;
1.83      albertel 9189:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9190:     if ($randomorder || $randompick) {
1.788     raeburn  9191:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
1.691     raeburn  9192:         if ($nav_error) {
                   9193:             $r->print(&navmap_errormsg());
                   9194:             return '';
                   9195:         }
                   9196:     }
1.557     raeburn  9197:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  9198:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  9199: 
1.554     raeburn  9200:     my ($uname,$udom);
1.82      albertel 9201:     my $result= <<SCANTRONFORM;
1.81      albertel 9202: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   9203:   <input type="hidden" name="command" value="scantron_configphase" />
                   9204:   $default_form_data
                   9205: SCANTRONFORM
1.82      albertel 9206:     $r->print($result);
                   9207: 
1.770     raeburn  9208:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 9209:     my @delayqueue;
1.542     raeburn  9210:     my (%completedstudents,%scandata);
1.770     raeburn  9211: 
1.520     www      9212:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9213:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9214:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   9215:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9216:     $r->print('<br />');
1.140     albertel 9217:     my $start=&Time::HiRes::time();
1.158     albertel 9218:     my $i=-1;
1.542     raeburn  9219:     my $started;
1.447     foxr     9220: 
1.649     raeburn  9221:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9222:     if ($nav_error) {
                   9223:         $r->print(&navmap_errormsg());
                   9224:         return '';
                   9225:     }
                   9226: 
1.513     foxr     9227:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9228:     # the user and return.
                   9229: 
                   9230:     if ($ssi_error) {
                   9231: 	$r->print("</form>");
                   9232: 	&ssi_print_error($r);
1.520     www      9233:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9234: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9235:     }
1.447     foxr     9236: 
1.755     raeburn  9237:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9238:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  9239:     my %orderedforcode;
1.542     raeburn  9240: 
1.157     albertel 9241:     while ($i<$scanlines->{'count'}) {
                   9242:  	($uname,$udom)=('','');
                   9243:  	$i++;
1.200     albertel 9244:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9245:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9246: 	if ($started) {
1.667     www      9247: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9248: 	}
                   9249: 	$started=1;
1.691     raeburn  9250:         my %respnumlookup = ();
                   9251:         my %startline = ();
                   9252:         my $total;
1.157     albertel 9253:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9254:                                                  $scan_data,undef,\%idmap,$randomorder,
                   9255:                                                  $randompick,$sequence,\@master_seq,
                   9256:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9257:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9258:                                                  \$total);
1.157     albertel 9259:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9260:  					      \%idmap,$i)) {
                   9261:   	    &scantron_add_delay(\@delayqueue,$line,
                   9262:  				'Unable to find a student that matches',1);
                   9263:  	    next;
                   9264:   	}
                   9265:  	if (exists $completedstudents{$uname}) {
                   9266:  	    &scantron_add_delay(\@delayqueue,$line,
                   9267:  				'Student '.$uname.' has multiple sheets',2);
                   9268:  	    next;
                   9269:  	}
1.677     raeburn  9270:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  9271:         if (($checksec ne '') && ($checksec ne $usec)) {
                   9272:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   9273:                 &scantron_add_delay(\@delayqueue,$line,
                   9274:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   9275:                 next;
                   9276:             }
                   9277:         }
1.677     raeburn  9278:         my $user = $uname.':'.$usec;
1.157     albertel 9279:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9280: 
1.677     raeburn  9281:         my $scancode;
                   9282:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9283:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9284:             $scancode = $scan_record->{'scantron.CODE'};
                   9285:         } else {
                   9286:             $scancode = '';
                   9287:         }
                   9288: 
                   9289:         my @mapresources = @resources;
1.689     raeburn  9290:         if ($randomorder || $randompick) {
1.678     raeburn  9291:             @mapresources = 
1.691     raeburn  9292:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9293:                              \%orderedforcode);
1.677     raeburn  9294:         }
1.586     raeburn  9295:         my (%partids_by_symb,$res_error);
1.677     raeburn  9296:         foreach my $resource (@mapresources) {
1.586     raeburn  9297:             my $ressymb;
                   9298:             if (ref($resource)) {
                   9299:                 $ressymb = $resource->symb();
                   9300:             } else {
                   9301:                 $res_error = 1;
                   9302:                 last;
                   9303:             }
1.557     raeburn  9304:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9305:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9306:                 my $currcode;
                   9307:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9308:                     $currcode = $scancode;
                   9309:                 }
1.557     raeburn  9310:                 my ($analysis,$parts) =
1.672     raeburn  9311:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  9312:                                               $uname,$udom,undef,$bubbles_per_row,
                   9313:                                               $currcode);
1.557     raeburn  9314:                 $partids_by_symb{$ressymb} = $parts;
                   9315:             } else {
                   9316:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9317:             }
1.554     raeburn  9318:         }
                   9319: 
1.586     raeburn  9320:         if ($res_error) {
                   9321:             &scantron_add_delay(\@delayqueue,$line,
                   9322:                                 'An error occurred while grading student '.$uname,2);
                   9323:             next;
                   9324:         }
                   9325: 
1.330     albertel 9326: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9327:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9328: 
                   9329: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9330: 	    &scantron_putfile($scanlines,$scan_data);
                   9331: 	}
1.161     albertel 9332: 	
1.542     raeburn  9333:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9334:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  9335:                                    $bubbles_per_row,$randomorder,$randompick,
                   9336:                                    \%respnumlookup,\%startline) 
                   9337:             eq 'ssi_error') {
1.542     raeburn  9338:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9339:             $r->print("</form>");
                   9340:             &ssi_print_error($r);
                   9341:             &Apache::lonnet::remove_lock($lock);
                   9342:             return '';      # Why return ''?  Beats me.
                   9343:         }
1.513     foxr     9344: 
1.692     raeburn  9345:         if (($scancode) && ($randomorder || $randompick)) {
1.788     raeburn  9346:             foreach my $key (keys(%symb_for_examcode)) {
                   9347:                 my $symb_in_map = $symb_for_examcode{$key};
                   9348:                 if ($symb_in_map ne '') {
                   9349:                     my $parmresult =
                   9350:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   9351:                                                                '0_examcode',2,$scancode,
                   9352:                                                                'string_examcode',$uname,
                   9353:                                                                $udom);
                   9354:                 }
                   9355:             }
1.692     raeburn  9356:         }
1.140     albertel 9357: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9358:         if ($env{'form.verifyrecord'}) {
                   9359:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  9360:             if ($randompick) {
                   9361:                 if ($total) {
                   9362:                     $lastpos = $total*$scantron_config{'Qlength'};
                   9363:                 }
                   9364:             }
                   9365: 
1.542     raeburn  9366:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9367:             chomp($studentdata);
                   9368:             $studentdata =~ s/\r$//;
                   9369:             my $studentrecord = '';
                   9370:             my $counter = -1;
1.677     raeburn  9371:             foreach my $resource (@mapresources) {
1.554     raeburn  9372:                 my $ressymb = $resource->symb();
1.542     raeburn  9373:                 ($counter,my $recording) =
                   9374:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9375:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9376:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9377:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9378:                 $studentrecord .= $recording;
                   9379:             }
                   9380:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9381:                 &Apache::lonxml::clear_problem_counter();
                   9382:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9383:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  9384:                                            $bubbles_per_row,$randomorder,$randompick,
                   9385:                                            \%respnumlookup,\%startline) 
                   9386:                     eq 'ssi_error') {
1.554     raeburn  9387:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9388:                     $r->print("</form>");
                   9389:                     &ssi_print_error($r);
                   9390:                     &Apache::lonnet::remove_lock($lock);
                   9391:                     delete($completedstudents{$uname});
                   9392:                     return '';
                   9393:                 }
1.542     raeburn  9394:                 $counter = -1;
                   9395:                 $studentrecord = '';
1.677     raeburn  9396:                 foreach my $resource (@mapresources) {
1.554     raeburn  9397:                     my $ressymb = $resource->symb();
1.542     raeburn  9398:                     ($counter,my $recording) =
                   9399:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9400:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9401:                                                  \%scantron_config,\%lettdig,$numletts,
                   9402:                                                  $randomorder,$randompick,\%respnumlookup,
                   9403:                                                  \%startline);
1.542     raeburn  9404:                     $studentrecord .= $recording;
                   9405:                 }
                   9406:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   9407:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9408:                     if ($scancode eq '') {
1.658     bisitz   9409:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9410:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9411:                     } else {
1.658     bisitz   9412:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9413:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9414:                     }
                   9415:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9416:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9417:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9418:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9419:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9420:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   9421:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9422:                               &Apache::loncommon::end_data_table_row().
                   9423:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9424:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   9425:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9426:                               &Apache::loncommon::end_data_table_row().
                   9427:                               &Apache::loncommon::end_data_table().'</p>');
                   9428:                 } else {
                   9429:                     $r->print('<br /><span class="LC_warning">'.
                   9430:                              &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 />'.
                   9431:                              &mt("As a consequence, this user's submission history records two tries.").
                   9432:                                  '</span><br />');
                   9433:                 }
                   9434:             }
                   9435:         }
1.543     raeburn  9436:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9437:     } continue {
1.330     albertel 9438: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9439: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9440:     }
1.140     albertel 9441:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9442:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9443: #    my $lasttime = &Time::HiRes::time()-$start;
                   9444: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9445: 
1.200     albertel 9446:     $r->print("</form>");
1.157     albertel 9447:     return '';
1.75      albertel 9448: }
1.157     albertel 9449: 
1.557     raeburn  9450: sub graders_resources_pass {
1.649     raeburn  9451:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9452:         $bubbles_per_row) = @_;
1.557     raeburn  9453:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9454:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9455:         foreach my $resource (@{$resources}) {
                   9456:             my $ressymb = $resource->symb();
                   9457:             my ($analysis,$parts) =
                   9458:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  9459:                                           $env{'user.name'},$env{'user.domain'},
                   9460:                                           1,$bubbles_per_row);
1.557     raeburn  9461:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9462:             if (ref($analysis) eq 'HASH') {
                   9463:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9464:                     $grader_randomlists_by_symb->{$ressymb} =
                   9465:                         $analysis->{'parts_withrandomlist'};
                   9466:                 }
                   9467:             }
                   9468:         }
                   9469:     }
                   9470:     return;
                   9471: }
                   9472: 
1.678     raeburn  9473: =pod
                   9474: 
                   9475: =item users_order
                   9476: 
                   9477:   Returns array of resources in current map, ordered based on either CODE,
                   9478:   if this is a CODEd exam, or based on student's identity if this is a 
                   9479:   "NAMEd" exam.
                   9480: 
1.691     raeburn  9481:   Should be used when randomorder and/or randompick applied when the 
                   9482:   corresponding exam was printed, prior to students completing bubblesheets 
                   9483:   for the version of the exam the student received.
1.678     raeburn  9484: 
                   9485: =cut
                   9486: 
                   9487: sub users_order  {
1.691     raeburn  9488:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9489:     my @mapresources;
1.691     raeburn  9490:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9491:         return @mapresources;
1.691     raeburn  9492:     }
                   9493:     if ($scancode) {
                   9494:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9495:             @mapresources = @{$orderedforcode->{$scancode}};
                   9496:         } else {
                   9497:             $env{'form.CODE'} = $scancode;
                   9498:             my $actual_seq =
                   9499:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9500:                                                                $master_seq,
                   9501:                                                                $user,$scancode,1);
                   9502:             if (ref($actual_seq) eq 'ARRAY') {
                   9503:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9504:                 if (ref($orderedforcode) eq 'HASH') {
                   9505:                     if (@mapresources > 0) { 
                   9506:                         $orderedforcode->{$scancode} = \@mapresources;
                   9507:                     }
                   9508:                 }
                   9509:             }
                   9510:             delete($env{'form.CODE'});
1.678     raeburn  9511:         }
                   9512:     } else {
                   9513:         my $actual_seq =
                   9514:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9515:                                                            $master_seq,
1.688     raeburn  9516:                                                            $user,undef,1);
1.678     raeburn  9517:         if (ref($actual_seq) eq 'ARRAY') {
                   9518:             @mapresources = 
                   9519:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9520:         }
1.691     raeburn  9521:     }
                   9522:     return @mapresources;
1.678     raeburn  9523: }
                   9524: 
1.542     raeburn  9525: sub grade_student_bubbles {
1.691     raeburn  9526:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9527:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9528:     my $uselookup = 0;
                   9529:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9530:         (ref($startline) eq 'HASH')) {
                   9531:         $uselookup = 1;
                   9532:     }
                   9533: 
1.554     raeburn  9534:     if (ref($resources) eq 'ARRAY') {
                   9535:         my $count = 0;
                   9536:         foreach my $resource (@{$resources}) {
                   9537:             my $ressymb = $resource->symb();
                   9538:             my %form = ('submitted'      => 'scantron',
                   9539:                         'grade_target'   => 'grade',
                   9540:                         'grade_username' => $uname,
                   9541:                         'grade_domain'   => $udom,
                   9542:                         'grade_courseid' => $env{'request.course.id'},
                   9543:                         'grade_symb'     => $ressymb,
                   9544:                         'CODE'           => $scancode
                   9545:                        );
1.649     raeburn  9546:             if ($bubbles_per_row ne '') {
                   9547:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9548:             }
1.663     raeburn  9549:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9550:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9551:             }
1.554     raeburn  9552:             if (ref($parts) eq 'HASH') {
                   9553:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9554:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9555:                         if ($uselookup) {
                   9556:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9557:                         } else {
                   9558:                             $form{'scantron_questnum_start.'.$part} =
                   9559:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9560:                         }
1.554     raeburn  9561:                         $count++;
                   9562:                     }
                   9563:                 }
                   9564:             }
                   9565:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9566:             return 'ssi_error' if ($ssi_error);
                   9567:             last if (&Apache::loncommon::connection_aborted($r));
                   9568:         }
1.542     raeburn  9569:     }
                   9570:     return;
                   9571: }
                   9572: 
1.157     albertel 9573: sub scantron_upload_scantron_data {
1.767     raeburn  9574:     my ($r,$symb) = @_;
1.565     raeburn  9575:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9576:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9577:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9578:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9579:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9580: 							  'domainid',
1.565     raeburn  9581: 							  'coursename',$dom);
                   9582:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9583:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9584:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9585:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9586:     &js_escape(\$nofile_alert);
1.579     raeburn  9587:     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  9588:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9589:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9590:     function checkUpload(formname) {
                   9591: 	if (formname.upfile.value == "") {
1.579     raeburn  9592: 	    alert("'.$nofile_alert.'");
1.157     albertel 9593: 	    return false;
                   9594: 	}
1.565     raeburn  9595:         if (formname.courseid.value == "") {
1.579     raeburn  9596:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9597:             return false;
                   9598:         }
1.157     albertel 9599: 	formname.submit();
                   9600:     }
1.565     raeburn  9601: 
                   9602:     function ToSyllabus() {
                   9603:         var cdom = '."'$dom'".';
                   9604:         var cnum = document.rules.courseid.value;
                   9605:         if (cdom == "" || cdom == null) {
                   9606:             return;
                   9607:         }
                   9608:         if (cnum == "" || cnum == null) {
                   9609:            return;
                   9610:         }
                   9611:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9612:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9613:         return;
                   9614:     }
                   9615: 
1.754     raeburn  9616:     '.$formatjs.'
1.597     wenzelju 9617: '));
                   9618:     $r->print('
1.648     bisitz   9619: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9620: 
1.492     albertel 9621: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9622: '.$default_form_data.
                   9623:   &Apache::lonhtmlcommon::start_pick_box().
                   9624:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9625:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9626:   &Apache::lonhtmlcommon::row_closure().
                   9627:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9628:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9629:   &Apache::lonhtmlcommon::row_closure().
                   9630:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9631:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9632:   &Apache::lonhtmlcommon::row_closure());
                   9633:     if ($formatoptions) {
                   9634:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9635:                   &Apache::lonhtmlcommon::row_closure());
                   9636:     }
                   9637:     $r->print(
1.565     raeburn  9638:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9639:   '<input type="file" name="upfile" size="50" />'.
                   9640:   &Apache::lonhtmlcommon::row_closure(1).
                   9641:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9642: 
1.492     albertel 9643: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9644: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9645: </form>
1.492     albertel 9646: ');
1.157     albertel 9647:     return '';
                   9648: }
                   9649: 
1.754     raeburn  9650: sub scantron_upload_dataformat {
                   9651:     my ($dom) = @_;
                   9652:     my ($formatoptions,$formattitle,$formatjs);
                   9653:     $formatjs = <<'END';
                   9654: function toggleScantab(form) {
                   9655:    return;
                   9656: }
                   9657: END
                   9658:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9659:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9660:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9661:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9662:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9663:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  9664:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   9665:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9666:                             my ($onclick,$formatextra,$singleline);
                   9667:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9668:                             my $count = 0;
                   9669:                             foreach my $line (@lines) {
1.790     raeburn  9670:                                 next if (($line =~ /^\#/) || ($line eq ''));
1.756     raeburn  9671:                                 $singleline = $line;
                   9672:                                 $count ++;
                   9673:                             }
                   9674:                             if ($count > 1) {
                   9675:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  9676:                                                '<span class="LC_nobreak">'.
1.776     raeburn  9677:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  9678:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  9679:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9680:                                 $formatjs = <<"END";
1.754     raeburn  9681: function toggleScantab(form) {
                   9682:     var divid = 'bubbletype';
                   9683:     if (document.getElementById(divid)) {
                   9684:         var radioname = 'fileformat';
                   9685:         var num = form.elements[radioname].length;
                   9686:         if (num) {
                   9687:             for (var i=0; i<num; i++) {
                   9688:                 if (form.elements[radioname][i].checked) {
                   9689:                     var chosen = form.elements[radioname][i].value;
                   9690:                     if (chosen == 'dat') {
                   9691:                         document.getElementById(divid).style.display = 'none';
                   9692:                     } else if (chosen == 'csv') {
1.757     raeburn  9693:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  9694:                     }
                   9695:                 }
                   9696:             }
                   9697:         }
                   9698:     }
                   9699:     return;
                   9700: }
                   9701: 
                   9702: END
1.756     raeburn  9703:                             } elsif ($count == 1) {
                   9704:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9705:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9706:                             }
                   9707:                             $formattitle = &mt('File format');
                   9708:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9709:                                              &mt('Plain Text (no delimiters)').
                   9710:                                              '</label>'.('&nbsp;'x2).
                   9711:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9712:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9713:                         }
                   9714:                     }
                   9715:                 }
                   9716:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  9717:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9718:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  9719:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  9720:                         $formatoptions = &scantron_scantab();
                   9721:                     }
1.754     raeburn  9722:                 }
                   9723:             }
                   9724:         }
                   9725:     }
                   9726:     return ($formatoptions,$formattitle,$formatjs);
                   9727: }
1.423     albertel 9728: 
1.157     albertel 9729: sub scantron_upload_scantron_data_save {
1.767     raeburn  9730:     my ($r,$symb) = @_;
1.182     albertel 9731:     my $doanotherupload=
                   9732: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9733: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9734: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9735: 	'</form>'."\n";
1.257     albertel 9736:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9737: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  9738: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   9739:         !&Apache::lonnet::allowed('usc',
                   9740:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      9741: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9742: 	unless ($symb) {
1.182     albertel 9743: 	    $r->print($doanotherupload);
                   9744: 	}
1.162     albertel 9745: 	return '';
                   9746:     }
1.257     albertel 9747:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9748:     my $uploadedfile;
1.710     bisitz   9749:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9750:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9751:         $r->print(
                   9752:             &Apache::lonhtmlcommon::confirm_success(
                   9753:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9754:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9755:     } else {
1.754     raeburn  9756:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9757:         my $parser;
                   9758:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9759:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9760:                 my $is_csv;
                   9761:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9762:                 if (@possibles > 1) {
                   9763:                     if ($env{'form.fileformat'} eq 'csv') {
                   9764:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9765:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9766:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9767:                                     $is_csv = 1;
                   9768:                                 }
1.754     raeburn  9769:                             }
                   9770:                         }
                   9771:                     }
                   9772:                 } elsif (@possibles == 1) {
                   9773:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9774:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9775:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9776:                                 $is_csv = 1;
                   9777:                             }
1.754     raeburn  9778:                         }
                   9779:                     }
                   9780:                 }
                   9781:                 if ($is_csv) {
                   9782:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9783:                 }
                   9784:             }
                   9785:         }
                   9786:         my $result =
                   9787:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9788:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9789:         if ($result =~ m{^/uploaded/}) {
                   9790:             $r->print(
                   9791:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9792:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9793:                         (length($env{'form.upfile'})-1),
                   9794:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9795:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  9796:             if ($uploadedfile =~ /^scantron_orig_/) {
                   9797:                 my $logname = $uploadedfile;
                   9798:                 $logname =~ s/^scantron_orig_//;
                   9799:                 if ($logname ne '') {
                   9800:                     my $now = time;
                   9801:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   9802:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9803:                 }
                   9804:             }
1.567     raeburn  9805:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  9806:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   9807:         } else {
                   9808:             $r->print(
                   9809:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9810:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9811:                           $result,
1.568     raeburn  9812: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9813: 	}
                   9814:     }
1.174     albertel 9815:     if ($symb) {
1.612     www      9816: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9817:     } else {
1.182     albertel 9818: 	$r->print($doanotherupload);
1.174     albertel 9819:     }
1.157     albertel 9820:     return '';
                   9821: }
                   9822: 
1.567     raeburn  9823: sub validate_uploaded_scantron_file {
1.770     raeburn  9824:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   9825: 
1.567     raeburn  9826:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9827:     my @lines;
                   9828:     if ($scanlines ne '-1') {
                   9829:         @lines=split("\n",$scanlines,-1);
                   9830:     }
1.770     raeburn  9831:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   9832:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   9833:     if ($context eq 'download') {
                   9834:         $priv = 'mgr';
                   9835:     } else {
                   9836:         $priv = 'usc';
                   9837:     }
                   9838:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   9839:             (($env{'request.course.id'}) &&
                   9840:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   9841:         if ($env{'request.course.sec'} ne '') {
                   9842:             unless (&Apache::lonnet::allowed($priv,
                   9843:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   9844:                 unless ($context eq 'download') {
                   9845:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   9846:                 }
                   9847:                 return $output;
                   9848:             }
                   9849:             ($checksec,@possibles)=&gradable_sections();
                   9850:         }
                   9851:     }
1.567     raeburn  9852:     if (@lines) {
                   9853:         my (%counts,$max_match_format);
1.710     bisitz   9854:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9855:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9856:         my %idmap = &username_to_idmap($classlist);
                   9857:         foreach my $key (keys(%idmap)) {
                   9858:             my $lckey = lc($key);
                   9859:             $idmap{$lckey} = $idmap{$key};
                   9860:         }
                   9861:         my %unique_formats;
1.754     raeburn  9862:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9863:         foreach my $line (@formatlines) {
1.790     raeburn  9864:             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  9865:             my @config = split(/:/,$line);
                   9866:             my $idstart = $config[5];
                   9867:             my $idlength = $config[6];
                   9868:             if (($idstart ne '') && ($idlength > 0)) {
                   9869:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9870:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9871:                 } else {
                   9872:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9873:                 }
                   9874:             }
                   9875:         }
                   9876:         foreach my $key (keys(%unique_formats)) {
                   9877:             my ($idstart,$idlength) = split(':',$key);
                   9878:             %{$counts{$key}} = (
                   9879:                                'found'   => 0,
                   9880:                                'total'   => 0,
1.770     raeburn  9881:                                'totalanysec' => 0,
                   9882:                                'othersec' => 0,
1.567     raeburn  9883:                               );
                   9884:             foreach my $line (@lines) {
                   9885:                 next if ($line =~ /^#/);
                   9886:                 next if ($line =~ /^[\s\cz]*$/);
                   9887:                 my $id = substr($line,$idstart-1,$idlength);
                   9888:                 $id = lc($id);
                   9889:                 if (exists($idmap{$id})) {
1.770     raeburn  9890:                     if ($checksec ne '') {
                   9891:                         $counts{$key}{'totalanysec'} ++;
                   9892:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9893:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9894:                             if ($stusec ne $checksec) {
                   9895:                                 if (@possibles) {
                   9896:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   9897:                                         $counts{$key}{'othersec'} ++;
                   9898:                                         next;
                   9899:                                     }
                   9900:                                 } else {
                   9901:                                     $counts{$key}{'othersec'} ++;
                   9902:                                     next;
                   9903:                                 }
                   9904:                             }
                   9905:                         }
                   9906:                     }
1.567     raeburn  9907:                     $counts{$key}{'found'} ++;
                   9908:                 }
                   9909:                 $counts{$key}{'total'} ++;
                   9910:             }
                   9911:             if ($counts{$key}{'total'}) {
                   9912:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9913:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9914:                     $max_match_pct = $percent_match;
                   9915:                     $max_match_format = $key;
1.710     bisitz   9916:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9917:                     $max_match_count = $counts{$key}{'total'};
                   9918:                 }
                   9919:             }
                   9920:         }
1.770     raeburn  9921:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  9922:             my $format_descs;
                   9923:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9924:             for (my $i=0; $i<$numwithformat; $i++) {
                   9925:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9926:                 if ($i<$numwithformat-2) {
                   9927:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9928:                 } elsif ($i==$numwithformat-2) {
                   9929:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9930:                 } elsif ($i==$numwithformat-1) {
                   9931:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9932:                 }
                   9933:             }
                   9934:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9935:             $output .= '<br />';
                   9936:             if ($found_match_count == $max_match_count) {
                   9937:                 # 100% matching entries
                   9938:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9939:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9940:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9941:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9942:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9943:                     ' in the file (for the format defined for [_3]).',
                   9944:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9945:             } else {
                   9946:                 # Not all entries matching? -> Show warning and additional info
                   9947:                 $output .=
                   9948:                     &Apache::lonhtmlcommon::confirm_success(
                   9949:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9950:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9951:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9952:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9953:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9954:                         ' in the file (for the format defined for [_3]).',
                   9955:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9956:                     '<p class="LC_info">'.
                   9957:                     &mt('A low percentage of matches results from one of the following:').
                   9958:                     '</p><ul>'.
                   9959:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9960:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9961:                                '<i>'.$cdom.'</i>').'</li>'.
                   9962:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9963:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9964:                     '</ul>';
                   9965:             }
1.770     raeburn  9966:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9967:                 if ($counts{$max_match_format}{'othersec'}) {
                   9968:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   9969:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   9970:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   9971:                     &js_escape(\$confirmdel);
                   9972:                     $output .= '<p class="LC_warning">'.
                   9973:                                &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',
                   9974:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   9975:                                '<br />'.
                   9976:                                &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>').
                   9977:                                '</p><p>'.
                   9978:                                &mt('If you prefer to delete the file now, use: [_1]').
                   9979:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   9980:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   9981:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   9982:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   9983:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   9984:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   9985:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   9986:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   9987:                                '</form></p>';
                   9988:                 }
                   9989:             }
1.567     raeburn  9990:         }
1.770     raeburn  9991:         if (($context eq 'download') && ($checksec ne '')) {
                   9992:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9993:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   9994:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   9995:             }
                   9996:         } 
                   9997:     } elsif ($context ne 'download') {
1.710     bisitz   9998:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9999:     }
                   10000:     return $output;
                   10001: }
                   10002: 
1.770     raeburn  10003: sub gradable_sections {
                   10004:     my $checksec = $env{'request.course.sec'};
                   10005:     my @oksecs;
                   10006:     if ($checksec) {
                   10007:         my %availablesecs = &sections_grade_privs();
                   10008:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   10009:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   10010:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   10011:                     push(@oksecs,$sec);
                   10012:                 }
                   10013:             }
                   10014:             if (grep(/^all$/,@oksecs)) {
                   10015:                 undef($checksec);
                   10016:             }
                   10017:         }
                   10018:     }
                   10019:     return($checksec,@oksecs);
                   10020: }
                   10021: 
                   10022: sub sections_grade_privs {
                   10023:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10024:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10025:     my %availablesecs = (
                   10026:                           mgr => [],
                   10027:                           vgr => [],
                   10028:                           usc => [],
                   10029:                         );
                   10030:     my $ccrole = 'cc';
                   10031:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   10032:         $ccrole = 'co';
                   10033:     }
                   10034:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   10035:                                                      'userroles',['active'],
                   10036:                                                      [$ccrole,'in','cr'],$cdom,1);
                   10037:     my $crsid = $cnum.':'.$cdom;
                   10038:     foreach my $item (keys(%crsroleshash)) {
                   10039:         next unless ($item =~ /^$crsid\:/);
                   10040:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   10041:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   10042:         if ($sec ne '') {
                   10043:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   10044:         }
                   10045:         if (($role eq $ccrole) || ($role eq 'in')) {
                   10046:             foreach my $priv ('mgr','vgr','usc') { 
                   10047:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   10048:                     if ($sec eq '') {
                   10049:                         $availablesecs{$priv} = ['all'];
                   10050:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   10051:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   10052:                             push(@{$availablesecs{$priv}},$sec);
                   10053:                         }
                   10054:                     }
                   10055:                 }
                   10056:             }
                   10057:         } elsif ($role =~ m{^cr/}) {
                   10058:             foreach my $priv ('mgr','vgr','usc') {
                   10059:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   10060:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   10061:                         if ($sec eq '') {
                   10062:                             $availablesecs{$priv} = ['all'];
                   10063:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   10064:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   10065:                                 push(@{$availablesecs{$priv}},$sec);
                   10066:                             }
                   10067:                         }
                   10068:                     }
                   10069:                 }
                   10070:             }
                   10071:         }
                   10072:     }
                   10073:     return %availablesecs;
                   10074: }
                   10075: 
                   10076: sub scantron_upload_delete {
                   10077:     my ($r,$symb) = @_;
                   10078:     my $filename = $env{'form.uploadedfile'};
                   10079:     if ($filename =~ /^scantron_orig_/) {
                   10080:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   10081:             &Apache::lonnet::allowed('usc',
                   10082:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   10083:             &Apache::lonnet::allowed('usc',
                   10084:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   10085:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   10086:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   10087:             if ($retrieval eq '-1') {
                   10088:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10089:                           &mt('File requested for deletion not found.'));
                   10090:             } else {
                   10091:                 $filename =~ s/^scantron_orig_//;
                   10092:                 if ($filename ne '') {
                   10093:                     my ($is_valid,$numleft);
                   10094:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   10095:                     if (keys(%info)) {
                   10096:                         if (ref($info{$filename}) eq 'HASH') {
                   10097:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   10098:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   10099:                                     $is_valid = 1;
                   10100:                                     delete($info{$filename}{$timestamp}); 
                   10101:                                 }
                   10102:                             }
                   10103:                             $numleft = scalar(keys(%{$info{$filename}}));
                   10104:                         }
                   10105:                     }
                   10106:                     if ($is_valid) {
                   10107:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   10108:                         if ($result eq 'ok') {
                   10109:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   10110:                             if ($numleft) {
                   10111:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   10112:                             } else {
                   10113:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   10114:                             }
                   10115:                         } else {
                   10116:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10117:                                       &mt('Result was [_1]',$result));
                   10118:                         }
                   10119:                     } else {
                   10120:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10121:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   10122:                     }
                   10123:                 } else {
                   10124:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10125:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   10126:                 }
                   10127:             }
                   10128:         } else {
                   10129:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   10130:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   10131:         }
                   10132:     } else {
                   10133:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10134:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   10135:     }
                   10136:     return;
                   10137: }
                   10138: 
1.202     albertel 10139: sub valid_file {
                   10140:     my ($requested_file)=@_;
                   10141:     foreach my $filename (sort(&scantron_filenames())) {
                   10142: 	if ($requested_file eq $filename) { return 1; }
                   10143:     }
                   10144:     return 0;
                   10145: }
                   10146: 
                   10147: sub scantron_download_scantron_data {
1.767     raeburn  10148:     my ($r,$symb) = @_;
1.608     www      10149:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 10150:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10151:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10152:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 10153:     if (! &valid_file($file)) {
1.492     albertel 10154: 	$r->print('
1.202     albertel 10155: 	<p>
1.686     bisitz   10156: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 10157:         </p>
1.492     albertel 10158: ');
1.202     albertel 10159: 	return;
                   10160:     }
1.770     raeburn  10161:     my (%uploader,$is_owner,%counts,$percent);
                   10162:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   10163:     if (ref($uploader{$file}) eq 'HASH') {
                   10164:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   10165:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   10166:                 $is_owner = 1;
                   10167:                 last;
                   10168:             }
                   10169:         }
                   10170:     }
                   10171:     unless ($is_owner) {
                   10172:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   10173:         if ($counts{'totalanysec'}) {
                   10174:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   10175:             if ($percent_othersec >= 10) {
                   10176:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   10177:                 $r->print('<p class="LC_warning">'.
                   10178:                           &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).
                   10179:                           '</p>');
                   10180:                 return;
                   10181:             }
                   10182:         }
                   10183:     }
1.202     albertel 10184:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   10185:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   10186:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   10187:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   10188:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   10189:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 10190:     $r->print('
1.202     albertel 10191:     <p>
1.723     raeburn  10192: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 10193: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 10194:     </p>
                   10195:     <p>
1.492     albertel 10196: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   10197: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 10198:     </p>
                   10199:     <p>
1.492     albertel 10200: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   10201: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 10202:     </p>
1.492     albertel 10203: ');
1.202     albertel 10204:     return '';
                   10205: }
1.157     albertel 10206: 
1.523     raeburn  10207: sub checkscantron_results {
1.608     www      10208:     my ($r,$symb) = @_;
1.523     raeburn  10209:     if (!$symb) {return '';}
                   10210:     my $cid = $env{'request.course.id'};
1.755     raeburn  10211:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  10212:     my $numletts = scalar(keys(%lettdig));
                   10213:     my $cnum = $env{'course.'.$cid.'.num'};
                   10214:     my $cdom = $env{'course.'.$cid.'.domain'};
                   10215:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10216:     my %record;
                   10217:     my %scantron_config =
1.754     raeburn  10218:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  10219:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  10220:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  10221:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10222:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   10223:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10224:     unless (ref($navmap)) {
                   10225:         $r->print(&navmap_errormsg());
                   10226:         return '';
                   10227:     }
1.523     raeburn  10228:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10229:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10230:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  10231:     if (ref($map)) { 
                   10232:         $randomorder=$map->randomorder();
1.689     raeburn  10233:         $randompick=$map->randompick();
1.788     raeburn  10234:         unless ($randomorder || $randompick) {
                   10235:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10236:                 if ($res->randomorder()) {
                   10237:                     $randomorder = 1;
                   10238:                 }
                   10239:                 if ($res->randompick()) {
                   10240:                     $randompick = 1;
                   10241:                 }
                   10242:                 last if ($randomorder || $randompick);
                   10243:             }
                   10244:         }
1.677     raeburn  10245:     }
1.557     raeburn  10246:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10247:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10248:     if ($nav_error) {
                   10249:         $r->print(&navmap_errormsg());
                   10250:         return '';
1.678     raeburn  10251:     }
1.673     raeburn  10252:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10253:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  10254:     my ($uname,$udom);
1.523     raeburn  10255:     my (%scandata,%lastname,%bylast);
                   10256:     $r->print('
                   10257: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   10258: 
                   10259:     my @delayqueue;
                   10260:     my %completedstudents;
                   10261: 
1.691     raeburn  10262:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10263:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  10264:     my ($username,$domain,$started);
1.649     raeburn  10265:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10266:     if ($nav_error) {
                   10267:         $r->print(&navmap_errormsg());
                   10268:         return '';
                   10269:     }
1.523     raeburn  10270: 
1.667     www      10271:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  10272:     my $start=&Time::HiRes::time();
                   10273:     my $i=-1;
                   10274: 
                   10275:     while ($i<$scanlines->{'count'}) {
                   10276:         ($username,$domain,$uname)=('','','');
                   10277:         $i++;
                   10278:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   10279:         if ($line=~/^[\s\cz]*$/) { next; }
                   10280:         if ($started) {
1.667     www      10281:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  10282:         }
                   10283:         $started=1;
                   10284:         my $scan_record=
                   10285:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   10286:                                                      $scan_data);
1.693     raeburn  10287:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10288:                                               \%idmap,$i)) {
1.523     raeburn  10289:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10290:                                 'Unable to find a student that matches',1);
                   10291:             next;
                   10292:         }
                   10293:         if (exists $completedstudents{$uname}) {
                   10294:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10295:                                 'Student '.$uname.' has multiple sheets',2);
                   10296:             next;
                   10297:         }
                   10298:         my $pid = $scan_record->{'scantron.ID'};
                   10299:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   10300:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  10301:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   10302:         my $user = $uname.':'.$usec;
1.523     raeburn  10303:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  10304: 
1.678     raeburn  10305:         my $scancode;
1.677     raeburn  10306:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10307:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10308:             $scancode = $scan_record->{'scantron.CODE'};
                   10309:         } else {
                   10310:             $scancode = '';
                   10311:         }
                   10312: 
                   10313:         my @mapresources = @resources;
1.691     raeburn  10314:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   10315:         my %respnumlookup=();
                   10316:         my %startline=();
1.689     raeburn  10317:         if ($randomorder || $randompick) {
1.678     raeburn  10318:             @mapresources =
1.691     raeburn  10319:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10320:                              \%orderedforcode);
                   10321:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   10322:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   10323:                                              \%grader_partids_by_symb,\%orderedforcode,
                   10324:                                              \%respnumlookup,\%startline);
                   10325:             if ($randompick && $total) {
                   10326:                 $lastpos = $total*$scantron_config{'Qlength'};
                   10327:             }
1.677     raeburn  10328:         }
1.691     raeburn  10329:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10330:         chomp($scandata{$pid});
                   10331:         $scandata{$pid} =~ s/\r$//;
                   10332: 
1.523     raeburn  10333:         my $counter = -1;
1.677     raeburn  10334:         foreach my $resource (@mapresources) {
1.557     raeburn  10335:             my $parts;
1.554     raeburn  10336:             my $ressymb = $resource->symb();
1.557     raeburn  10337:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10338:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10339:                 my $currcode;
                   10340:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10341:                     $currcode = $scancode;
                   10342:                 }
1.557     raeburn  10343:                 (my $analysis,$parts) =
1.672     raeburn  10344:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   10345:                                               $username,$domain,undef,
1.741     raeburn  10346:                                               $bubbles_per_row,$currcode);
1.557     raeburn  10347:             } else {
                   10348:                 $parts = $grader_partids_by_symb{$ressymb};
                   10349:             }
1.542     raeburn  10350:             ($counter,my $recording) =
                   10351:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  10352:                                          $scandata{$pid},$parts,
1.691     raeburn  10353:                                          \%scantron_config,\%lettdig,$numletts,
                   10354:                                          $randomorder,$randompick,
                   10355:                                          \%respnumlookup,\%startline);
1.542     raeburn  10356:             $record{$pid} .= $recording;
1.523     raeburn  10357:         }
                   10358:     }
                   10359:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   10360:     $r->print('<br />');
                   10361:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   10362:     $passed = 0;
                   10363:     $failed = 0;
                   10364:     $numstudents = 0;
                   10365:     foreach my $last (sort(keys(%bylast))) {
                   10366:         if (ref($bylast{$last}) eq 'ARRAY') {
                   10367:             foreach my $pid (sort(@{$bylast{$last}})) {
                   10368:                 my $showscandata = $scandata{$pid};
                   10369:                 my $showrecord = $record{$pid};
                   10370:                 $showscandata =~ s/\s/&nbsp;/g;
                   10371:                 $showrecord =~ s/\s/&nbsp;/g;
                   10372:                 if ($scandata{$pid} eq $record{$pid}) {
                   10373:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   10374:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      10375: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  10376: '</tr>'."\n".
                   10377: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10378: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  10379:                     $passed ++;
                   10380:                 } else {
                   10381:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      10382:                     $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  10383: '</tr>'."\n".
                   10384: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10385: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  10386: '</tr>'."\n";
                   10387:                     $failed ++;
                   10388:                 }
                   10389:                 $numstudents ++;
                   10390:             }
                   10391:         }
                   10392:     }
1.648     bisitz   10393:     $r->print(
                   10394:         '<p>'
                   10395:        .&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).',
                   10396:             '<b>',
                   10397:             $numstudents,
                   10398:             '</b>',
                   10399:             $env{'form.scantron_maxbubble'})
                   10400:        .'</p>'
                   10401:     );
1.682     raeburn  10402:     $r->print('<p>'
1.683     raeburn  10403:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  10404:              .'<br />'
                   10405:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10406:              .'</p>'
                   10407:     );
1.523     raeburn  10408:     if ($passed) {
1.572     www      10409:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10410:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10411:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10412:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10413:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10414:                  $okstudents."\n".
                   10415:                  &Apache::loncommon::end_data_table().'<br />');
                   10416:     }
                   10417:     if ($failed) {
1.572     www      10418:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10419:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10420:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10421:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10422:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10423:                  $badstudents."\n".
                   10424:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10425:                  &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  10426:     }
1.614     www      10427:     $r->print('</form><br />');
1.523     raeburn  10428:     return;
                   10429: }
                   10430: 
1.542     raeburn  10431: sub verify_scantron_grading {
1.554     raeburn  10432:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  10433:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10434:         $respnumlookup,$startline) = @_;
1.542     raeburn  10435:     my ($record,%expected,%startpos);
                   10436:     return ($counter,$record) if (!ref($resource));
                   10437:     return ($counter,$record) if (!$resource->is_problem());
                   10438:     my $symb = $resource->symb();
1.554     raeburn  10439:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10440:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10441:         $counter ++;
                   10442:         $expected{$part_id} = 0;
1.691     raeburn  10443:         my $respnum = $counter;
                   10444:         if ($randomorder || $randompick) {
                   10445:             $respnum = $respnumlookup->{$counter};
                   10446:             $startpos{$part_id} = $startline->{$counter} + 1;
                   10447:         } else {
                   10448:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10449:         }
                   10450:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10451:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10452:             foreach my $item (@sub_lines) {
                   10453:                 $expected{$part_id} += $item;
                   10454:             }
                   10455:         } else {
1.691     raeburn  10456:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10457:         }
                   10458:     }
                   10459:     if ($symb) {
                   10460:         my %recorded;
                   10461:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10462:         if ($returnhash{'version'}) {
                   10463:             my %lasthash=();
                   10464:             my $version;
                   10465:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10466:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10467:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10468:                 }
                   10469:             }
                   10470:             foreach my $key (keys(%lasthash)) {
                   10471:                 if ($key =~ /\.scantron$/) {
                   10472:                     my $value = &unescape($lasthash{$key});
                   10473:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10474:                     if ($value eq '') {
                   10475:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10476:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10477:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10478:                             }
                   10479:                         }
                   10480:                     } else {
                   10481:                         my @tocheck;
                   10482:                         my @items = split(//,$value);
                   10483:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10484:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10485:                             if (@items < $expected{$part_id}) {
                   10486:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10487:                                 my @singles = split(//,$fragment);
                   10488:                                 foreach my $pos (@singles) {
                   10489:                                     if ($pos eq ' ') {
                   10490:                                         push(@tocheck,$pos);
                   10491:                                     } else {
                   10492:                                         my $next = shift(@items);
                   10493:                                         push(@tocheck,$next);
                   10494:                                     }
                   10495:                                 }
                   10496:                             } else {
                   10497:                                 @tocheck = @items;
                   10498:                             }
                   10499:                             foreach my $letter (@tocheck) {
                   10500:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10501:                                     if ($letter !~ /^[A-J]$/) {
                   10502:                                         $letter = $scantron_config->{'Qoff'};
                   10503:                                     }
                   10504:                                     $recorded{$part_id} .= $letter;
                   10505:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10506:                                     my $digit;
                   10507:                                     if ($letter !~ /^[A-J]$/) {
                   10508:                                         $digit = $scantron_config->{'Qoff'};
                   10509:                                     } else {
                   10510:                                         $digit = $lettdig->{$letter};
                   10511:                                     }
                   10512:                                     $recorded{$part_id} .= $digit;
                   10513:                                 }
                   10514:                             }
                   10515:                         } else {
                   10516:                             @tocheck = @items;
                   10517:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10518:                                 my $curr_sub = shift(@tocheck);
                   10519:                                 my $digit;
                   10520:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10521:                                     $digit = $lettdig->{$curr_sub}-1;
                   10522:                                 }
                   10523:                                 if ($curr_sub eq 'J') {
                   10524:                                     $digit += scalar($numletts);
                   10525:                                 }
                   10526:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10527:                                     if ($j == $digit) {
                   10528:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10529:                                     } else {
                   10530:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10531:                                     }
                   10532:                                 }
                   10533:                             }
                   10534:                         }
                   10535:                     }
                   10536:                 }
                   10537:             }
                   10538:         }
1.554     raeburn  10539:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10540:             if ($recorded{$part_id} eq '') {
                   10541:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10542:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10543:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10544:                     }
                   10545:                 }
                   10546:             }
                   10547:             $record .= $recorded{$part_id};
                   10548:         }
                   10549:     }
                   10550:     return ($counter,$record);
                   10551: }
                   10552: 
1.75      albertel 10553: #-------- end of section for handling grading scantron forms -------
                   10554: #
                   10555: #-------------------------------------------------------------------
                   10556: 
1.72      ng       10557: #-------------------------- Menu interface -------------------------
                   10558: #
1.614     www      10559: #--- Href with symb and command ---
                   10560: 
                   10561: sub href_symb_cmd {
                   10562:     my ($symb,$cmd)=@_;
1.669     raeburn  10563:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       10564: }
                   10565: 
1.443     banghart 10566: sub grading_menu {
1.608     www      10567:     my ($request,$symb) = @_;
1.443     banghart 10568:     if (!$symb) {return '';}
                   10569: 
                   10570:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      10571:                   'command'=>'individual');
1.538     schulted 10572:     
1.598     www      10573:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10574: 
                   10575:     $fields{'command'}='ungraded';
                   10576:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10577: 
                   10578:     $fields{'command'}='table';
                   10579:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10580: 
                   10581:     $fields{'command'}='all_for_one';
                   10582:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10583: 
1.621     www      10584:     $fields{'command'}='downloadfilesselect';
                   10585:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10586: 
1.443     banghart 10587:     $fields{'command'} = 'csvform';
1.538     schulted 10588:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10589:     
1.443     banghart 10590:     $fields{'command'} = 'processclicker';
1.538     schulted 10591:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10592:     
1.443     banghart 10593:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10594:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      10595: 
                   10596:     $fields{'command'} = 'initialverifyreceipt';
                   10597:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  10598: 
                   10599:     my %permissions;
                   10600:     if ($perm{'mgr'}) {
                   10601:         $permissions{'either'} = 'F';
                   10602:         $permissions{'mgr'} = 'F';
                   10603:     }
                   10604:     if ($perm{'vgr'}) {
                   10605:         $permissions{'either'} = 'F';
                   10606:         $permissions{'vgr'} = 'F';
                   10607:     }
                   10608: 
1.598     www      10609:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10610:             items =>[
1.598     www      10611:                         {	linktext => 'Select individual students to grade',
                   10612:                     		url => $url1a,
1.781     raeburn  10613:                     		permission => $permissions{'either'},
1.636     wenzelju 10614:                     		icon => 'grade_students.png',
1.598     www      10615:                     		linktitle => 'Grade current resource for a selection of students.'
                   10616:                         }, 
1.764     raeburn  10617:                         {       linktext => 'Grade ungraded submissions',
1.598     www      10618:                                 url => $url1b,
1.781     raeburn  10619:                                 permission => $permissions{'either'},
1.636     wenzelju 10620:                                 icon => 'ungrade_sub.png',
1.598     www      10621:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 10622:                         },
1.598     www      10623: 
                   10624:                         {       linktext => 'Grading table',
                   10625:                                 url => $url1c,
1.781     raeburn  10626:                                 permission => $permissions{'either'},
1.636     wenzelju 10627:                                 icon => 'grading_table.png',
1.598     www      10628:                                 linktitle => 'Grade current resource for all students.'
                   10629:                         },
1.615     www      10630:                         {       linktext => 'Grade page/folder for one student',
1.598     www      10631:                                 url => $url1d,
1.781     raeburn  10632:                                 permission => $permissions{'either'},
1.636     wenzelju 10633:                                 icon => 'grade_PageFolder.png',
1.598     www      10634:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      10635:                         },
                   10636:                         {       linktext => 'Download submissions',
                   10637:                                 url => $url1e,
1.781     raeburn  10638:                                 permission => $permissions{'either'},
1.636     wenzelju 10639:                                 icon => 'download_sub.png',
1.621     www      10640:                                 linktitle => 'Download all students submissions.'
1.598     www      10641:                         }]},
                   10642:                          { categorytitle=>'Automated Grading',
                   10643:                items =>[
                   10644: 
1.538     schulted 10645:                 	    {	linktext => 'Upload Scores',
                   10646:                     		url => $url2,
1.780     raeburn  10647:                     		permission => $permissions{'mgr'},
1.538     schulted 10648:                     		icon => 'uploadscores.png',
                   10649:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10650:                 	    },
                   10651:                 	    {	linktext => 'Process Clicker',
                   10652:                     		url => $url3,
1.780     raeburn  10653:                     		permission => $permissions{'mgr'},
1.538     schulted 10654:                     		icon => 'addClickerInfoFile.png',
                   10655:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10656:                 	    },
1.587     raeburn  10657:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10658:                     		url => $url4,
1.780     raeburn  10659:                     		permission => $permissions{'mgr'},
1.636     wenzelju 10660:                     		icon => 'bubblesheet.png',
1.648     bisitz   10661:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      10662:                 	    },
1.616     www      10663:                             {   linktext => 'Verify Receipt Number',
1.602     www      10664:                                 url => $url5,
1.780     raeburn  10665:                                 permission => $permissions{'either'},
1.636     wenzelju 10666:                                 icon => 'receipt_number.png',
1.602     www      10667:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10668:                             }
                   10669: 
1.538     schulted 10670:                     ]
                   10671:             });
                   10672: 
1.443     banghart 10673:     # Create the menu
                   10674:     my $Str;
1.445     banghart 10675:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10676:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      10677:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 10678: 
1.602     www      10679:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10680:     return $Str;    
                   10681: }
                   10682: 
1.598     www      10683: sub ungraded {
                   10684:     my ($request)=@_;
                   10685:     &submit_options($request);
                   10686: }
                   10687: 
1.599     www      10688: sub submit_options_sequence {
1.608     www      10689:     my ($request,$symb) = @_;
1.599     www      10690:     if (!$symb) {return '';}
1.600     www      10691:     &commonJSfunctions($request);
                   10692:     my $result;
1.599     www      10693: 
1.600     www      10694:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10695:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      10696:     $result.=&selectfield(0).
1.601     www      10697:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      10698:             <div>
                   10699:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10700:             </div>
                   10701:         </div>
                   10702:   </form>';
                   10703:     return $result;
                   10704: }
                   10705: 
                   10706: sub submit_options_table {
1.608     www      10707:     my ($request,$symb) = @_;
1.600     www      10708:     if (!$symb) {return '';}
1.599     www      10709:     &commonJSfunctions($request);
1.746     raeburn  10710:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      10711:     my $result;
                   10712: 
                   10713:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10714:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      10715: 
1.745     raeburn  10716:     $result.=&selectfield(1,$is_tool).
1.601     www      10717:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      10718:             <div>
                   10719:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10720:             </div>
                   10721:         </div>
                   10722:   </form>';
                   10723:     return $result;
                   10724: }
1.443     banghart 10725: 
1.621     www      10726: sub submit_options_download {
                   10727:     my ($request,$symb) = @_;
                   10728:     if (!$symb) {return '';}
                   10729: 
1.773     raeburn  10730:     my $res_error;
                   10731:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10732:         &response_type($symb,\$res_error);
                   10733:     if ($res_error) {
                   10734:         $request->print(&mt('An error occurred retrieving response types'));
                   10735:         return;
                   10736:     }
                   10737:     unless ($numessay) {
                   10738:         $request->print(&mt('No essayresponse items found'));
                   10739:         return;
                   10740:     }
                   10741:     my $table;
                   10742:     if (ref($partlist) eq 'ARRAY') {
                   10743:         if (scalar(@$partlist) > 1 ) {
                   10744:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   10745:         }
                   10746:     }
                   10747: 
1.746     raeburn  10748:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      10749:     &commonJSfunctions($request);
                   10750: 
                   10751:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  10752:                $table."\n".
                   10753:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      10754:     $result.='
                   10755: <h2>
1.750     raeburn  10756:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  10757: </h2>'.&selectfield(1,$is_tool).'
1.621     www      10758:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   10759:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10760:             </div>
                   10761:           </div>
1.600     www      10762: 
                   10763: 
1.621     www      10764:   </form>';
                   10765:     return $result;
                   10766: }
                   10767: 
1.443     banghart 10768: #--- Displays the submissions first page -------
                   10769: sub submit_options {
1.608     www      10770:     my ($request,$symb) = @_;
1.72      ng       10771:     if (!$symb) {return '';}
                   10772: 
1.746     raeburn  10773:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       10774:     &commonJSfunctions($request);
1.473     albertel 10775:     my $result;
1.533     bisitz   10776: 
1.72      ng       10777:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10778: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  10779:     $result.=&selectfield(1,$is_tool).'
1.601     www      10780:                 <input type="hidden" name="command" value="submission" /> 
                   10781: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10782:             </div>
                   10783:           </div>
                   10784:   </form>';
                   10785:     return $result;
                   10786: }
1.533     bisitz   10787: 
1.601     www      10788: sub selectfield {
1.745     raeburn  10789:    my ($full,$is_tool)=@_;
                   10790:    my %options;
                   10791:    if ($is_tool) {
                   10792:        %options =
                   10793:            (&transtatus_options,
                   10794:             'select_form_order' => ['yes','incorrect','all']);
                   10795:    } else {
                   10796:        %options = 
                   10797:            (&substatus_options,
                   10798:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10799:    }
1.782     raeburn  10800: 
                   10801:   #
                   10802:   # PrepareClasslist() needs to be called to avoid getting a sections list
                   10803:   # for a different course from the @Sections global in lonstatistics.pm, 
                   10804:   # populated by an earlier request.
                   10805:   #
                   10806:    &Apache::lonstatistics::PrepareClasslist();
                   10807: 
1.601     www      10808:    my $result='<div class="LC_columnSection">
1.537     harmsja  10809:   
1.533     bisitz   10810:     <fieldset>
                   10811:       <legend>
                   10812:        '.&mt('Sections').'
                   10813:       </legend>
1.601     www      10814:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10815:     </fieldset>
1.537     harmsja  10816:   
1.533     bisitz   10817:     <fieldset>
                   10818:       <legend>
                   10819:         '.&mt('Groups').'
                   10820:       </legend>
                   10821:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10822:     </fieldset>
1.537     harmsja  10823:   
1.533     bisitz   10824:     <fieldset>
                   10825:       <legend>
                   10826:         '.&mt('Access Status').'
                   10827:       </legend>
1.601     www      10828:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10829:     </fieldset>';
                   10830:     if ($full) {
1.745     raeburn  10831:         my $heading = &mt('Submission Status');
                   10832:         if ($is_tool) {
                   10833:             $heading = &mt('Transaction Status');
                   10834:         }
                   10835:         $result.='
1.533     bisitz   10836:     <fieldset>
                   10837:       <legend>
1.745     raeburn  10838:         '.$heading.'
1.601     www      10839:       </legend>'.
1.635     raeburn  10840:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      10841:    '</fieldset>';
                   10842:     }
                   10843:     $result.='</div><br />';
1.44      ng       10844:     return $result;
1.2       albertel 10845: }
                   10846: 
1.738     raeburn  10847: sub substatus_options {
                   10848:     return &Apache::lonlocal::texthash(
                   10849:                                       'yes'       => 'with submissions',
                   10850:                                       'queued'    => 'in grading queue',
                   10851:                                       'graded'    => 'with ungraded submissions',
                   10852:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10853:                                       'all'       => 'with any status',
                   10854:                                       );
1.738     raeburn  10855: }
                   10856: 
1.745     raeburn  10857: sub transtatus_options {
                   10858:     return &Apache::lonlocal::texthash(
                   10859:                                        'yes'       => 'with score transactions',
                   10860:                                        'incorrect' => 'with less than full credit',
                   10861:                                        'all'       => 'with any status',
                   10862:                                       );
                   10863: }
                   10864: 
1.285     albertel 10865: sub reset_perm {
                   10866:     undef(%perm);
                   10867: }
                   10868: 
                   10869: sub init_perm {
                   10870:     &reset_perm();
1.770     raeburn  10871:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 10872: 
                   10873: 	my $scope = $env{'request.course.id'};
                   10874: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10875: 
                   10876: 	    $scope .= '/'.$env{'request.course.sec'};
                   10877: 	    if ( $perm{$test_perm}=
                   10878: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10879: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10880: 	    } else {
                   10881: 		delete($perm{$test_perm});
                   10882: 	    }
1.285     albertel 10883: 	}
                   10884:     }
                   10885: }
                   10886: 
1.674     raeburn  10887: sub init_old_essays {
                   10888:     my ($symb,$apath,$adom,$aname) = @_;
                   10889:     if ($symb ne '') {
                   10890:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10891:         if (keys(%essays) > 0) {
                   10892:             $old_essays{$symb} = \%essays;
                   10893:         }
                   10894:     }
                   10895:     return;
                   10896: }
                   10897: 
                   10898: sub reset_old_essays {
                   10899:     undef(%old_essays);
                   10900: }
                   10901: 
1.400     www      10902: sub gather_clicker_ids {
1.408     albertel 10903:     my %clicker_ids;
1.400     www      10904: 
                   10905:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10906: 
                   10907:     # Set up a couple variables.
1.407     albertel 10908:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10909:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10910:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10911: 
1.407     albertel 10912:     foreach my $student (keys(%$classlist)) {
1.438     www      10913:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10914:         my $username = $classlist->{$student}->[$username_idx];
                   10915:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10916:         my $clickers =
1.408     albertel 10917: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10918:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10919:             $id=~s/^[\#0]+//;
1.421     www      10920:             $id=~s/[\-\:]//g;
1.407     albertel 10921:             if (exists($clicker_ids{$id})) {
1.408     albertel 10922: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10923:             } else {
1.408     albertel 10924: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10925:             }
                   10926:         }
                   10927:     }
1.407     albertel 10928:     return %clicker_ids;
1.400     www      10929: }
                   10930: 
1.402     www      10931: sub gather_adv_clicker_ids {
1.408     albertel 10932:     my %clicker_ids;
1.402     www      10933:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10934:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10935:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10936:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10937:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10938:             my ($puname,$pudom)=split(/\:/,$person);
                   10939:             my $clickers =
1.408     albertel 10940: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10941:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10942: 		$id=~s/^[\#0]+//;
1.421     www      10943:                 $id=~s/[\-\:]//g;
1.408     albertel 10944: 		if (exists($clicker_ids{$id})) {
                   10945: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10946: 		} else {
                   10947: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10948: 		}
1.405     www      10949:             }
1.402     www      10950:         }
                   10951:     }
1.407     albertel 10952:     return %clicker_ids;
1.402     www      10953: }
                   10954: 
1.413     www      10955: sub clicker_grading_parameters {
                   10956:     return ('gradingmechanism' => 'scalar',
                   10957:             'upfiletype' => 'scalar',
                   10958:             'specificid' => 'scalar',
                   10959:             'pcorrect' => 'scalar',
                   10960:             'pincorrect' => 'scalar');
                   10961: }
                   10962: 
1.400     www      10963: sub process_clicker {
1.608     www      10964:     my ($r,$symb)=@_;
1.400     www      10965:     if (!$symb) {return '';}
                   10966:     my $result=&checkforfile_js();
1.632     www      10967:     $result.=&Apache::loncommon::start_data_table().
                   10968:              &Apache::loncommon::start_data_table_header_row().
                   10969:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10970:              &Apache::loncommon::end_data_table_header_row().
                   10971:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10972: # Attempt to restore parameters from last session, set defaults if not present
                   10973:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10974:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10975:                                                  \%Saveable_Parameters);
                   10976:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10977:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10978:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10979:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10980: 
                   10981:     my %checked;
1.521     www      10982:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10983:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10984:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10985:        }
                   10986:     }
                   10987: 
1.632     www      10988:     my $upload=&mt("Evaluate File");
1.400     www      10989:     my $type=&mt("Type");
1.402     www      10990:     my $attendance=&mt("Award points just for participation");
                   10991:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10992:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10993:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10994:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10995:     my $pcorrect=&mt("Percentage points for correct solution");
                   10996:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10997:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10998: 						   {'iclicker' => 'i>clicker',
1.666     www      10999:                                                     'interwrite' => 'interwrite PRS',
                   11000:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 11001:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 11002:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      11003: function sanitycheck() {
                   11004: // Accept only integer percentages
                   11005:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   11006:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   11007: // Find out grading choice
                   11008:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   11009:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   11010:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   11011:       }
                   11012:    }
                   11013: // By default, new choice equals user selection
                   11014:    newgradingchoice=gradingchoice;
                   11015: // Not good to give more points for false answers than correct ones
                   11016:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   11017:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   11018:    }
                   11019: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   11020:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   11021:       document.forms.gradesupload.pcorrect.value=100;
                   11022:       document.forms.gradesupload.pincorrect.value=100;
                   11023:    }
                   11024: // If the values are different, cannot be attendance only
                   11025:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   11026:        (gradingchoice=='attendance')) {
                   11027:        newgradingchoice='personnel';
                   11028:    }
                   11029: // Change grading choice to new one
                   11030:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   11031:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   11032:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   11033:       } else {
                   11034:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   11035:       }
                   11036:    }
                   11037: // Remember the old state
                   11038:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   11039: }
1.597     wenzelju 11040: ENDUPFORM
                   11041:     $result.= <<ENDUPFORM;
1.400     www      11042: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   11043: <input type="hidden" name="symb" value="$symb" />
                   11044: <input type="hidden" name="command" value="processclickerfile" />
                   11045: <input type="file" name="upfile" size="50" />
                   11046: <br /><label>$type: $selectform</label>
1.632     www      11047: ENDUPFORM
                   11048:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   11049:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   11050:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   11051: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   11052: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      11053: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   11054: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      11055: <br />&nbsp;&nbsp;&nbsp;
                   11056: <input type="text" name="givenanswer" size="50" />
1.413     www      11057: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      11058: ENDGRADINGFORM
1.766     raeburn  11059:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      11060:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   11061:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   11062: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   11063: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  11064: </form>
1.632     www      11065: ENDPERCFORM
                   11066:     $result.='</td>'.
                   11067:              &Apache::loncommon::end_data_table_row().
                   11068:              &Apache::loncommon::end_data_table();
1.400     www      11069:     return $result;
                   11070: }
                   11071: 
                   11072: sub process_clicker_file {
1.766     raeburn  11073:     my ($r,$symb) = @_;
1.400     www      11074:     if (!$symb) {return '';}
1.413     www      11075: 
                   11076:     my %Saveable_Parameters=&clicker_grading_parameters();
                   11077:     &Apache::loncommon::store_course_settings('grades_clicker',
                   11078:                                               \%Saveable_Parameters);
1.598     www      11079:     my $result='';
1.404     www      11080:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 11081: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      11082: 	return $result;
1.404     www      11083:     }
1.522     www      11084:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      11085:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      11086:         return $result;
1.521     www      11087:     }
1.522     www      11088:     my $foundgiven=0;
1.521     www      11089:     if ($env{'form.gradingmechanism'} eq 'given') {
                   11090:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   11091:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      11092:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      11093:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      11094:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   11095:         $foundgiven=$#answers+1;
1.521     www      11096:     }
1.407     albertel 11097:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 11098:     my %correct_ids;
1.404     www      11099:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 11100: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      11101:     }
                   11102:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      11103: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   11104: 	   $correct_id=~tr/a-z/A-Z/;
                   11105: 	   $correct_id=~s/\s//gs;
                   11106: 	   $correct_id=~s/^[\#0]+//;
1.421     www      11107:            $correct_id=~s/[\-\:]//g;
1.414     www      11108:            if ($correct_id) {
                   11109: 	      $correct_ids{$correct_id}='specified';
                   11110:            }
                   11111:         }
1.400     www      11112:     }
1.404     www      11113:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 11114: 	$result.=&mt('Score based on attendance only');
1.521     www      11115:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      11116:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      11117:     } else {
1.408     albertel 11118: 	my $number=0;
1.411     www      11119: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 11120: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      11121: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 11122: 	    if ($correct_ids{$id} eq 'specified') {
                   11123: 		$result.=&mt('specified');
                   11124: 	    } else {
                   11125: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   11126: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   11127: 	    }
                   11128: 	    $number++;
                   11129: 	}
1.411     www      11130:         $result.="</p>\n";
1.710     bisitz   11131:         if ($number==0) {
                   11132:             $result .=
                   11133:                  &Apache::lonhtmlcommon::confirm_success(
                   11134:                      &mt('No IDs found to determine correct answer'),1);
                   11135:             return $result;
                   11136:         }
1.404     www      11137:     }
1.405     www      11138:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   11139:         $result .=
                   11140:             &Apache::lonhtmlcommon::confirm_success(
                   11141:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   11142:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      11143:         return $result;
1.405     www      11144:     }
1.760     raeburn  11145:     my $mimetype;
                   11146:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   11147:         my $mm = new File::MMagic;
                   11148:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   11149:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   11150:             $result.= '<p>'.
                   11151:                 &Apache::lonhtmlcommon::confirm_success(
                   11152:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   11153:             return $result;
                   11154:         }
                   11155:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   11156:         $result .= '<p>'.
                   11157:             &Apache::lonhtmlcommon::confirm_success(
                   11158:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   11159:         return $result;
                   11160:     }
1.410     www      11161: 
                   11162: # Were able to get all the info needed, now analyze the file
                   11163: 
1.411     www      11164:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 11165:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      11166:     $result.=&Apache::loncommon::start_data_table().
                   11167:              &Apache::loncommon::start_data_table_header_row().
                   11168:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   11169:              &Apache::loncommon::end_data_table_header_row().
                   11170:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   11171: <td>
1.410     www      11172: <form method="post" action="/adm/grades" name="clickeranalysis">
                   11173: <input type="hidden" name="symb" value="$symb" />
                   11174: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      11175: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   11176: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   11177: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      11178: ENDHEADER
1.522     www      11179:     if ($env{'form.gradingmechanism'} eq 'given') {
                   11180:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   11181:     } 
1.408     albertel 11182:     my %responses;
                   11183:     my @questiontitles;
1.405     www      11184:     my $errormsg='';
                   11185:     my $number=0;
                   11186:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  11187:         if ($mimetype eq 'text/plain') {
                   11188:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   11189:         } elsif ($mimetype eq 'text/html') {
                   11190:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   11191:         }
                   11192:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      11193:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  11194:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      11195:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   11196:     }
1.411     www      11197:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   11198:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   11199:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   11200:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   11201:              '<br />';
1.522     www      11202:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   11203:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      11204:        return $result;
1.522     www      11205:     } 
1.414     www      11206: # Remember Question Titles
                   11207: # FIXME: Possibly need delimiter other than ":"
                   11208:     for (my $i=0;$i<$number;$i++) {
                   11209:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   11210:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   11211:     }
1.411     www      11212:     my $correct_count=0;
                   11213:     my $student_count=0;
                   11214:     my $unknown_count=0;
1.414     www      11215: # Match answers with usernames
                   11216: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 11217:     foreach my $id (keys(%responses)) {
1.410     www      11218:        if ($correct_ids{$id}) {
1.414     www      11219:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      11220:           $correct_count++;
1.410     www      11221:        } elsif ($clicker_ids{$id}) {
1.437     www      11222:           if ($clicker_ids{$id}=~/\,/) {
                   11223: # More than one user with the same clicker!
1.632     www      11224:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11225:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11226:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      11227:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11228:                            "<select name='multi".$id."'>";
                   11229:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   11230:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   11231:              }
                   11232:              $result.='</select>';
                   11233:              $unknown_count++;
                   11234:           } else {
                   11235: # Good: found one and only one user with the right clicker
                   11236:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   11237:              $student_count++;
                   11238:           }
1.410     www      11239:        } else {
1.632     www      11240:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11241:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11242:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      11243:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11244:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   11245:                    "\n".&mt("Domain").": ".
                   11246:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  11247:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      11248:           $unknown_count++;
1.410     www      11249:        }
1.405     www      11250:     }
1.412     www      11251:     $result.='<hr />'.
                   11252:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      11253:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      11254:        if ($correct_count==0) {
1.696     bisitz   11255:           $errormsg.="Found no correct answers for grading!";
1.412     www      11256:        } elsif ($correct_count>1) {
1.414     www      11257:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      11258:        }
                   11259:     }
1.428     www      11260:     if ($number<1) {
                   11261:        $errormsg.="Found no questions.";
                   11262:     }
1.412     www      11263:     if ($errormsg) {
                   11264:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   11265:     } else {
                   11266:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   11267:     }
1.632     www      11268:     $result.='</form></td>'.
                   11269:              &Apache::loncommon::end_data_table_row().
                   11270:              &Apache::loncommon::end_data_table();
1.614     www      11271:     return $result;
1.400     www      11272: }
                   11273: 
1.405     www      11274: sub iclicker_eval {
1.406     www      11275:     my ($questiontitles,$responses)=@_;
1.405     www      11276:     my $number=0;
                   11277:     my $errormsg='';
                   11278:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      11279:         my %components=&Apache::loncommon::record_sep($line);
                   11280:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 11281: 	if ($entries[0] eq 'Question') {
                   11282: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   11283: 		$$questiontitles[$number]=$entries[$i];
                   11284: 		$number++;
                   11285: 	    }
                   11286: 	}
                   11287: 	if ($entries[0]=~/^\#/) {
                   11288: 	    my $id=$entries[0];
                   11289: 	    my @idresponses;
                   11290: 	    $id=~s/^[\#0]+//;
                   11291: 	    for (my $i=0;$i<$number;$i++) {
                   11292: 		my $idx=3+$i*6;
1.644     www      11293:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 11294: 		push(@idresponses,$entries[$idx]);
                   11295: 	    }
                   11296: 	    $$responses{$id}=join(',',@idresponses);
                   11297: 	}
1.405     www      11298:     }
                   11299:     return ($errormsg,$number);
                   11300: }
                   11301: 
1.760     raeburn  11302: sub iclickerxml_eval {
                   11303:     my ($questiontitles,$responses)=@_;
                   11304:     my $number=0;
                   11305:     my $errormsg='';
                   11306:     my @state;
                   11307:     my %respbyid;
                   11308:     my $p = HTML::Parser->new
                   11309:     (
                   11310:         xml_mode => 1,
                   11311:         start_h =>
                   11312:             [sub {
                   11313:                  my ($tagname,$attr) = @_;
                   11314:                  push(@state,$tagname);
                   11315:                  if ("@state" eq "ssn p") {
                   11316:                      my $title = $attr->{qn};
                   11317:                      $title =~ s/(^\s+|\s+$)//g;
                   11318:                      $questiontitles->[$number]=$title;
                   11319:                  } elsif ("@state" eq "ssn p v") {
                   11320:                      my $id = $attr->{id};
                   11321:                      my $entry = $attr->{ans};
                   11322:                      $id=~s/^[\#0]+//;
                   11323:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   11324:                      $respbyid{$id}[$number] = $entry;
                   11325:                  }
                   11326:             }, "tagname, attr"],
                   11327:          end_h =>
                   11328:                [sub {
                   11329:                    my ($tagname) = @_;
                   11330:                    if ("@state" eq "ssn p") {
                   11331:                        $number++;
                   11332:                    }
                   11333:                    pop(@state);
                   11334:                 }, "tagname"],
                   11335:     );
                   11336: 
                   11337:     $p->parse($env{'form.upfile'});
                   11338:     $p->eof;
                   11339:     foreach my $id (keys(%respbyid)) {
                   11340:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   11341:     }
                   11342:     return ($errormsg,$number);
                   11343: }
                   11344: 
1.419     www      11345: sub interwrite_eval {
                   11346:     my ($questiontitles,$responses)=@_;
                   11347:     my $number=0;
                   11348:     my $errormsg='';
1.420     www      11349:     my $skipline=1;
                   11350:     my $questionnumber=0;
                   11351:     my %idresponses=();
1.419     www      11352:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11353:         my %components=&Apache::loncommon::record_sep($line);
                   11354:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      11355:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   11356:         if ($entries[1] eq 'Response') { $skipline=1; }
                   11357:         next if $skipline;
                   11358:         if ($entries[0]!=$questionnumber) {
                   11359:            $questionnumber=$entries[0];
                   11360:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   11361:            $number++;
1.419     www      11362:         }
1.420     www      11363:         my $id=$entries[4];
                   11364:         $id=~s/^[\#0]+//;
1.421     www      11365:         $id=~s/^v\d*\://i;
                   11366:         $id=~s/[\-\:]//g;
1.420     www      11367:         $idresponses{$id}[$number]=$entries[6];
                   11368:     }
1.524     raeburn  11369:     foreach my $id (keys(%idresponses)) {
1.420     www      11370:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   11371:        $$responses{$id}=~s/^\s*\,//;
1.419     www      11372:     }
                   11373:     return ($errormsg,$number);
                   11374: }
                   11375: 
1.666     www      11376: sub turning_eval {
                   11377:     my ($questiontitles,$responses)=@_;
                   11378:     my $number=0;
                   11379:     my $errormsg='';
                   11380:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11381:         my %components=&Apache::loncommon::record_sep($line);
                   11382:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   11383:         if ($#entries>$number) { $number=$#entries; }
                   11384:         my $id=$entries[0];
                   11385:         my @idresponses;
                   11386:         $id=~s/^[\#0]+//;
                   11387:         unless ($id) { next; }
                   11388:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   11389:             $entries[$idx]=~s/\,/\;/g;
                   11390:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   11391:             push(@idresponses,$entries[$idx]);
                   11392:         }
                   11393:         $$responses{$id}=join(',',@idresponses);
                   11394:     }
                   11395:     for (my $i=1; $i<=$number; $i++) {
                   11396:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   11397:     }
                   11398:     return ($errormsg,$number);
                   11399: }
                   11400: 
                   11401: 
1.414     www      11402: sub assign_clicker_grades {
1.766     raeburn  11403:     my ($r,$symb) = @_;
1.414     www      11404:     if (!$symb) {return '';}
1.416     www      11405: # See which part we are saving to
1.582     raeburn  11406:     my $res_error;
                   11407:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   11408:     if ($res_error) {
                   11409:         return &navmap_errormsg();
                   11410:     }
1.416     www      11411: # FIXME: This should probably look for the first handgradeable part
                   11412:     my $part=$$partlist[0];
                   11413: # Start screen output
1.766     raeburn  11414:     my $result = &Apache::loncommon::start_data_table().
                   11415:                  &Apache::loncommon::start_data_table_header_row().
                   11416:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   11417:                  &Apache::loncommon::end_data_table_header_row().
                   11418:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11419: # Get correct result
                   11420: # FIXME: Possibly need delimiter other than ":"
                   11421:     my @correct=();
1.415     www      11422:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11423:     my $number=$env{'form.number'};
                   11424:     if ($gradingmechanism ne 'attendance') {
1.414     www      11425:        foreach my $key (keys(%env)) {
                   11426:           if ($key=~/^form\.correct\:/) {
                   11427:              my @input=split(/\,/,$env{$key});
                   11428:              for (my $i=0;$i<=$#input;$i++) {
                   11429:                  if (($correct[$i]) && ($input[$i]) &&
                   11430:                      ($correct[$i] ne $input[$i])) {
                   11431:                     $result.='<br /><span class="LC_warning">'.
                   11432:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11433:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      11434:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11435:                     $correct[$i]=$input[$i];
                   11436:                  }
                   11437:              }
                   11438:           }
                   11439:        }
1.415     www      11440:        for (my $i=0;$i<$number;$i++) {
1.644     www      11441:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11442:              $result.='<br /><span class="LC_error">'.
                   11443:                       &mt('No correct result given for question "[_1]"!',
                   11444:                           $env{'form.question:'.$i}).'</span>';
                   11445:           }
                   11446:        }
1.644     www      11447:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11448:     }
                   11449: # Start grading
1.415     www      11450:     my $pcorrect=$env{'form.pcorrect'};
                   11451:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11452:     my $storecount=0;
1.632     www      11453:     my %users=();
1.415     www      11454:     foreach my $key (keys(%env)) {
1.420     www      11455:        my $user='';
1.415     www      11456:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11457:           $user=$1;
                   11458:        }
                   11459:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11460:           my $id=$1;
                   11461:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11462:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11463:           } elsif ($env{'form.multi'.$id}) {
                   11464:              $user=$env{'form.multi'.$id};
1.420     www      11465:           }
                   11466:        }
1.632     www      11467:        if ($user) {
                   11468:           if ($users{$user}) {
                   11469:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   11470:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      11471:                       '</span><br />';
                   11472:           }
                   11473:           $users{$user}=1; 
1.415     www      11474:           my @answer=split(/\,/,$env{$key});
                   11475:           my $sum=0;
1.522     www      11476:           my $realnumber=$number;
1.415     www      11477:           for (my $i=0;$i<$number;$i++) {
1.576     www      11478:              if  ($correct[$i] eq '-') {
                   11479:                 $realnumber--;
1.766     raeburn  11480:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11481:                 if ($gradingmechanism eq 'attendance') {
                   11482:                    $sum+=$pcorrect;
1.576     www      11483:                 } elsif ($correct[$i] eq '*') {
1.522     www      11484:                    $sum+=$pcorrect;
1.415     www      11485:                 } else {
1.644     www      11486: # We actually grade if correct or not
                   11487:                    my $increment=$pincorrect;
                   11488: # Special case: numerical answer "0"
                   11489:                    if ($correct[$i] eq '0') {
                   11490:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11491:                          $increment=$pcorrect;
                   11492:                       }
                   11493: # General numerical answer, both evaluate to something non-zero
                   11494:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11495:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11496:                          $increment=$pcorrect;
                   11497:                       }
                   11498: # Must be just alphanumeric
                   11499:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11500:                       $increment=$pcorrect;
1.415     www      11501:                    }
1.644     www      11502:                    $sum+=$increment;
1.415     www      11503:                 }
                   11504:              }
                   11505:           }
1.522     www      11506:           my $ave=$sum/(100*$realnumber);
1.416     www      11507: # Store
                   11508:           my ($username,$domain)=split(/\:/,$user);
                   11509:           my %grades=();
                   11510:           $grades{"resource.$part.solved"}='correct_by_override';
                   11511:           $grades{"resource.$part.awarded"}=$ave;
                   11512:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11513:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11514:                                                  $env{'request.course.id'},
                   11515:                                                  $domain,$username);
                   11516:           if ($returncode ne 'ok') {
                   11517:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11518:           } else {
                   11519:              $storecount++;
                   11520:           }
1.415     www      11521:        }
                   11522:     }
                   11523: # We are done
1.549     hauer    11524:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      11525:              '</td>'.
                   11526:              &Apache::loncommon::end_data_table_row().
                   11527:              &Apache::loncommon::end_data_table();
1.614     www      11528:     return $result;
1.414     www      11529: }
                   11530: 
1.582     raeburn  11531: sub navmap_errormsg {
                   11532:     return '<div class="LC_error">'.
                   11533:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11534:            &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  11535:            '</div>';
                   11536: }
1.607     droeschl 11537: 
1.609     www      11538: sub startpage {
1.777     raeburn  11539:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  11540:     my %args;
                   11541:     if ($onload) {
                   11542:          my %loaditems = (
                   11543:                         'onload' => $onload,
                   11544:                       );
                   11545:          $args{'add_entries'} = \%loaditems;
                   11546:     }
1.671     raeburn  11547:     if ($nomenu) {
1.754     raeburn  11548:         $args{'only_body'} = 1; 
1.777     raeburn  11549:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  11550:     } else {
1.785     raeburn  11551:         if ($env{'request.course.id'}) { 
                   11552:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   11553:         }
1.754     raeburn  11554:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  11555:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  11556:         if ($env{'request.course.id'}) {
                   11557:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   11558:         }
1.671     raeburn  11559:     }
1.613     www      11560:     unless ($nodisplayflag) {
1.773     raeburn  11561:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      11562:     }
1.607     droeschl 11563: }
1.582     raeburn  11564: 
1.622     www      11565: sub select_problem {
                   11566:     my ($r)=@_;
1.632     www      11567:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  11568:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      11569:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11570:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11571: }
                   11572: 
1.793     raeburn  11573: #----- display problem, answer, and submissions for a single student (no grading)
                   11574: 
                   11575: sub view_as_user {
                   11576:     my ($symb,$vuname,$vudom,$hasperm) = @_;
                   11577:     my $plainname = &Apache::loncommon::plainname($vuname,$vudom,'lastname');
                   11578:     my $displayname = &nameUserString('',$plainname,$vuname,$vudom);
                   11579:     my $output = &Apache::loncommon::get_student_view($symb,$vuname,$vudom,
                   11580:                                                       $env{'request.course.id'},
                   11581:                                                       undef,{'disable_submit' => 1}).
                   11582:                  "\n\n".
                   11583:                  '<div class="LC_grade_show_user">'.
                   11584:                  '<h2>'.$displayname.'</h2>'.
                   11585:                  "\n".
                   11586:                  &Apache::loncommon::track_student_link('View recent activity',
                   11587:                                                         $vuname,$vudom,'check').' '.
                   11588:                  "\n";
                   11589:     if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) ||
                   11590:         (($env{'request.course.sec'} ne '') &&
                   11591:          &Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
                   11592:         $output .= &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   11593:                                                $vuname,$vudom,$symb,'check');
                   11594:     }
                   11595:     $output .= "\n";
                   11596:     my $companswer = &Apache::loncommon::get_student_answers($symb,$vuname,$vudom,
                   11597:                                                              $env{'request.course.id'});
                   11598:     $companswer=~s|<form(.*?)>||g;
                   11599:     $companswer=~s|</form>||g;
                   11600:     $companswer=~s|name="submit"|name="would_have_been_submit"|g;
                   11601:     $output .= '<div class="LC_Box">'.
                   11602:                '<h3 class="LC_hcell">'.&mt('Correct answer for[_1]',$displayname).'</h3>'.
                   11603:                $companswer.
                   11604:                '</div>'."\n";
                   11605:     my $is_tool = ($symb =~ /ext\.tool$/);
                   11606:     my ($essayurl,%coursedesc_by_cid);
                   11607:     (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   11608:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$vudom,$vuname);
                   11609:     my $res_error;
                   11610:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   11611:         &response_type($symb,\$res_error);
                   11612:     my $fullname;
                   11613:     my $collabinfo;
                   11614:     if ($numessay) {
                   11615:         unless ($hasperm) {
                   11616:             &init_perm();
                   11617:         }
                   11618:         ($collabinfo,$fullname)=
                   11619:             &check_collaborators($symb,$vuname,$vudom,\%record,$handgrade,0);
                   11620:         unless ($hasperm) {
                   11621:             &reset_perm();
                   11622:         }
                   11623:     }
                   11624:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   11625:                     '" src="'.$Apache::lonnet::perlvar{'lonIconsURL'}.
                   11626:                     '/check.gif" height="16" border="0" />';
                   11627:     my ($lastsubonly,$partinfo) =
                   11628:         &show_last_submission($vuname,$vudom,$symb,$essayurl,$responseType,'datesub',
                   11629:                               '',$fullname,\%record,\%coursedesc_by_cid);
                   11630:     $output .= '<div class="LC_Box">'.
                   11631:                '<h3 class="LC_hcell">'.&mt('Submissions').'</h3>'."\n".$collabinfo."\n";
                   11632:     if (($numresp > $numessay) & !$is_tool) {
                   11633:         $output .='<p class="LC_info">'.
                   11634:                   &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon).
                   11635:                   "</p>\n";
                   11636:     }
                   11637:     $output .= $partinfo;
                   11638:     $output .= $lastsubonly;
                   11639:     $output .= &displaySubByDates($symb,\%record,$partlist,$responseType,$checkIcon,$vuname,$vudom);
                   11640:     $output .= '</div></div>'."\n";
                   11641:     return $output;
                   11642: }
                   11643: 
1.1       albertel 11644: sub handler {
1.41      ng       11645:     my $request=$_[0];
1.434     albertel 11646:     &reset_caches();
1.646     raeburn  11647:     if ($request->header_only) {
                   11648:         &Apache::loncommon::content_type($request,'text/html');
                   11649:         $request->send_http_header;
                   11650:         return OK;
                   11651:     }
                   11652:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   11653: 
1.664     raeburn  11654: # see what command we need to execute
                   11655: 
                   11656:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11657:     my $command=$commands[0];
                   11658: 
1.646     raeburn  11659:     &init_perm();
                   11660:     if (!$env{'request.course.id'}) {
1.664     raeburn  11661:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11662:                 ($command =~ /^scantronupload/)) {
                   11663:             # Not in a course.
                   11664:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11665:             return HTTP_NOT_ACCEPTABLE;
                   11666:         }
1.646     raeburn  11667:     } elsif (!%perm) {
                   11668:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  11669:         return OK;
1.41      ng       11670:     }
1.646     raeburn  11671:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       11672:     $request->send_http_header;
1.646     raeburn  11673: 
1.160     albertel 11674:     if ($#commands > 0) {
                   11675: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11676:     }
1.608     www      11677: 
                   11678: # see what the symb is
                   11679: 
                   11680:     my $symb=$env{'form.symb'};
                   11681:     unless ($symb) {
                   11682:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11683:        $symb=&Apache::lonnet::symbread($url);
                   11684:     }
1.646     raeburn  11685:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      11686: 
1.513     foxr     11687:     $ssi_error = 0;
1.637     www      11688:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      11689: #
1.637     www      11690: # Not called from a resource, but inside a course
1.601     www      11691: #    
1.622     www      11692:         &startpage($request,undef,[],1,1);
                   11693:         &select_problem($request);
1.41      ng       11694:     } else {
1.104     albertel 11695: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  11696:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  11697:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11698:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11699:                     &choose_task_version_form($symb,$env{'form.student'},
                   11700:                                               $env{'form.userdom'});
                   11701:             }
1.773     raeburn  11702:             my $divforres;
                   11703:             if ($env{'form.student'} eq '') {
                   11704:                 $js .= &part_selector_js();
                   11705:                 $onload = "toggleParts('gradesub');";
                   11706:             } else {
                   11707:                 $divforres = 1;
                   11708:             }
1.778     raeburn  11709:             my $head_extra = $js;
                   11710:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11711:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11712:                 if ($csslinks) {
                   11713:                     $head_extra .= "\n$csslinks";
                   11714:                 }
                   11715:             }
1.777     raeburn  11716:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   11717:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  11718:             if ($versionform) {
1.775     raeburn  11719:                 if ($divforres) {
                   11720:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   11721:                 }
1.671     raeburn  11722:                 $request->print($versionform);
                   11723:             }
1.773     raeburn  11724: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  11725:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11726:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11727:                 &choose_task_version_form($symb,$env{'form.student'},
                   11728:                                           $env{'form.userdom'},
                   11729:                                           $env{'form.inhibitmenu'});
1.778     raeburn  11730:             my $head_extra = $js;
                   11731:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11732:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11733:                 if ($csslinks) {
                   11734:                     $head_extra .= "\n$csslinks";
                   11735:                 }
                   11736:             }
1.777     raeburn  11737:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   11738:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  11739:             if ($versionform) {
                   11740:                 $request->print($versionform);
                   11741:             }
                   11742:             $request->print('<br clear="all" />');
                   11743:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 11744: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      11745:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11746:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      11747: 	    &pickStudentPage($request,$symb);
1.103     albertel 11748: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  11749:             my $csslinks;
                   11750:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11751:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  11752:             }
1.615     www      11753:             &startpage($request,$symb,
                   11754:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11755:                                        {href=>'',text=>'Select student'},
1.777     raeburn  11756:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      11757: 	    &displayPage($request,$symb);
1.104     albertel 11758: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      11759:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11760:                                        {href=>'',text=>'Select student'},
                   11761:                                        {href=>'',text=>'Grade student'},
                   11762:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      11763: 	    &updateGradeByPage($request,$symb);
1.104     albertel 11764: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  11765:             my $csslinks;
                   11766:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11767:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11768:             }
1.619     www      11769:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  11770:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      11771: 	    &processGroup($request,$symb);
1.104     albertel 11772: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      11773:             &startpage($request,$symb);
                   11774: 	    $request->print(&grading_menu($request,$symb));
1.598     www      11775: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      11776:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      11777: 	    $request->print(&submit_options($request,$symb));
1.598     www      11778:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  11779:             my $js = &part_selector_js();
                   11780:             my $onload = "toggleParts('gradesub');";
                   11781:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11782:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      11783:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      11784:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      11785:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      11786:             $request->print(&submit_options_table($request,$symb));
1.598     www      11787:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      11788:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      11789:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 11790: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      11791:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      11792: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 11793: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      11794:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11795:                                        {href=>'',text=>'Store grades'}]);
1.608     www      11796: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 11797: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      11798:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11799:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11800:                                                                              text=>"Modify grades"},
                   11801:                                        {href=>'', text=>"Store grades"}]);
1.608     www      11802: 	    $request->print(&editgrades($request,$symb));
1.602     www      11803:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      11804:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      11805:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 11806: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      11807:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11808:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      11809: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      11810:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      11811:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      11812:             $request->print(&process_clicker($request,$symb));
1.400     www      11813:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      11814:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11815:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      11816:             $request->print(&process_clicker_file($request,$symb));
1.414     www      11817:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      11818:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11819:                                        {href=>'', text=>'Process clicker file'},
                   11820:                                        {href=>'', text=>'Store grades'}]);
1.608     www      11821:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 11822: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      11823:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11824: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 11825: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      11826:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11827: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 11828: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      11829:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11830: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 11831: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 11832: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      11833:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11834: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       11835: 	    } else {
1.257     albertel 11836: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11837: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       11838: 		} else {
1.257     albertel 11839: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       11840: 		}
1.627     www      11841:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11842: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       11843: 	    }
1.246     albertel 11844: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      11845:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11846: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 11847: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  11848:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11849:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      11850: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 11851:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      11852:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11853:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 11854: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      11855:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11856: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 11857: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      11858:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11859: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 11860:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  11861:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  11862:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11863:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      11864:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 11865:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  11866:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      11867:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11868:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  11869:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      11870:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11871:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  11872:         } elsif ($command eq 'scantronupload_delete' &&
                   11873:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   11874:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11875:             &scantron_upload_delete($request,$symb);
1.523     raeburn  11876:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      11877:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      11878:             $request->print(&checkscantron_results($request,$symb));
                   11879:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  11880:             my $js = &part_selector_js();
                   11881:             my $onload = "toggleParts('gradingMenu');";
                   11882:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11883:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      11884:             $request->print(&submit_options_download($request,$symb));
                   11885:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11886:             &startpage($request,$symb,
                   11887:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  11888:     {href=>'', text=>'Download submitted files'}],
                   11889:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  11890:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      11891:             &submit_download_link($request,$symb);
1.106     albertel 11892: 	} elsif ($command) {
1.620     www      11893:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   11894: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 11895: 	}
1.2       albertel 11896:     }
1.513     foxr     11897:     if ($ssi_error) {
                   11898: 	&ssi_print_error($request);
                   11899:     }
1.671     raeburn  11900:     if ($env{'form.inhibitmenu'}) {
                   11901:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  11902:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  11903:         &Apache::lonquickgrades::endGradeScreen($request);
                   11904:     }
1.434     albertel 11905:     &reset_caches();
1.646     raeburn  11906:     return OK;
1.44      ng       11907: }
                   11908: 
1.1       albertel 11909: 1;
                   11910: 
1.13      albertel 11911: __END__;
1.531     jms      11912: 
                   11913: 
                   11914: =head1 NAME
                   11915: 
                   11916: Apache::grades
                   11917: 
                   11918: =head1 SYNOPSIS
                   11919: 
                   11920: Handles the viewing of grades.
                   11921: 
                   11922: This is part of the LearningOnline Network with CAPA project
                   11923: described at http://www.lon-capa.org.
                   11924: 
                   11925: =head1 OVERVIEW
                   11926: 
                   11927: Do an ssi with retries:
1.715     bisitz   11928: While I'd love to factor out this with the version in lonprintout,
1.531     jms      11929: 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
                   11930: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11931: 
                   11932: At least the logic that drives this has been pulled out into loncommon.
                   11933: 
                   11934: 
                   11935: 
                   11936: ssi_with_retries - Does the server side include of a resource.
                   11937:                      if the ssi call returns an error we'll retry it up to
                   11938:                      the number of times requested by the caller.
1.715     bisitz   11939:                      If we still have a problem, no text is appended to the
1.531     jms      11940:                      output and we set some global variables.
                   11941:                      to indicate to the caller an SSI error occurred.  
                   11942:                      All of this is supposed to deal with the issues described
1.715     bisitz   11943:                      in LON-CAPA BZ 5631 see:
1.531     jms      11944:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11945:                      by informing the user that this happened.
                   11946: 
                   11947: Parameters:
                   11948:   resource   - The resource to include.  This is passed directly, without
                   11949:                interpretation to lonnet::ssi.
                   11950:   form       - The form hash parameters that guide the interpretation of the resource
                   11951:                
                   11952:   retries    - Number of retries allowed before giving up completely.
                   11953: Returns:
                   11954:   On success, returns the rendered resource identified by the resource parameter.
                   11955: Side Effects:
                   11956:   The following global variables can be set:
                   11957:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11958:                               It is up to the caller to initialize this to false
                   11959:                               if desired.
                   11960:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11961:                               of the resource that could not be rendered by the ssi
                   11962:                               call.
                   11963:    ssi_error_message   - The error string fetched from the ssi response
                   11964:                               in the event of an error.
                   11965: 
                   11966: 
                   11967: =head1 HANDLER SUBROUTINE
                   11968: 
                   11969: ssi_with_retries()
                   11970: 
                   11971: =head1 SUBROUTINES
                   11972: 
                   11973: =over
                   11974: 
1.671     raeburn  11975: =head1 Routines to display previous version of a Task for a specific student
                   11976: 
                   11977: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   11978: can receive another opportunity. Access to tasks is slot-based. If a slot
                   11979: requires a proctor to check-in the student, a new version of the Task will
                   11980: be created when the student is checked in to the new opportunity.
                   11981: 
                   11982: If a particular student has tried two or more versions of a particular task,
                   11983: the submission screen provides a user with vgr privileges (e.g., a Course
                   11984: Coordinator) the ability to display a previous version worked on by the
                   11985: student.  By default, the current version is displayed. If a previous version
                   11986: has been selected for display, submission data are only shown that pertain
                   11987: to that particular version, and the interface to submit grades is not shown.
                   11988: 
                   11989: =over 4
                   11990: 
                   11991: =item show_previous_task_version()
                   11992: 
                   11993: Displays a specified version of a student's Task, as the student sees it.
                   11994: 
                   11995: Inputs: 2
                   11996:         request - request object
                   11997:         symb    - unique symb for current instance of resource
                   11998: 
                   11999: Output: None.
                   12000: 
                   12001: Side Effects: calls &show_problem() to print version of Task, with
                   12002:               version contained in form item: $env{'form.previousversion'}
                   12003: 
                   12004: =item choose_task_version_form()
                   12005: 
                   12006: Displays a web form used to select which version of a student's view of a
                   12007: Task should be displayed.  Either launches a pop-up window, or replaces
                   12008: content in existing pop-up, or replaces page in main window.
                   12009: 
                   12010: Inputs: 4
                   12011:         symb    - unique symb for current instance of resource
                   12012:         uname   - username of student
                   12013:         udom    - domain of student
                   12014:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   12015:                   breadcrumbs etc., are displayed
                   12016: 
                   12017: Output: 4
                   12018:         current   - student's current version
                   12019:         displayed - student's version being displayed
                   12020:         result    - scalar containing HTML for web form used to switch to
                   12021:                     a different version (or a link to close window, if pop-up).
                   12022:         js        - javascript for processing selection in versions web form
                   12023: 
                   12024: Side Effects: None.
                   12025: 
                   12026: =item previous_display_javascript()
                   12027: 
                   12028: Inputs: 2
                   12029:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   12030:                   breadcrumbs etc., are displayed.
                   12031:         current - student's current version number.
                   12032: 
                   12033: Output: 1
                   12034:         js      - javascript for processing selection in versions web form.
                   12035: 
                   12036: Side Effects: None.
                   12037: 
                   12038: =back
                   12039: 
                   12040: =head1 Routines to process bubblesheet data.
                   12041: 
                   12042: =over 4
                   12043: 
1.531     jms      12044: =item scantron_get_correction() : 
                   12045: 
                   12046:    Builds the interface screen to interact with the operator to fix a
                   12047:    specific error condition in a specific scanline
                   12048: 
                   12049:  Arguments:
                   12050:     $r           - Apache request object
                   12051:     $i           - number of the current scanline
                   12052:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  12053:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      12054:     $line        - full contents of the current scanline
                   12055:     $error       - error condition, valid values are
                   12056:                    'incorrectCODE', 'duplicateCODE',
                   12057:                    'doublebubble', 'missingbubble',
                   12058:                    'duplicateID', 'incorrectID'
                   12059:     $arg         - extra information needed
                   12060:        For errors:
                   12061:          - duplicateID   - paper number that this studentID was seen before on
                   12062:          - duplicateCODE - array ref of the paper numbers this CODE was
                   12063:                            seen on before
                   12064:          - incorrectCODE - current incorrect CODE 
                   12065:          - doublebubble  - array ref of the bubble lines that have double
                   12066:                            bubble errors
                   12067:          - missingbubble - array ref of the bubble lines that have missing
                   12068:                            bubble errors
                   12069: 
1.788     raeburn  12070:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   12071:    $randompick  - True if exam folder (or a sub-folder) has randompick set
1.691     raeburn  12072:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   12073:                      for current line to question number used for same question
                   12074:                      in "Master Seqence" (as seen by Course Coordinator).
                   12075:    $startline   - Reference to hash where key is question number (0 is first)
                   12076:                   and value is number of first bubble line for current student
                   12077:                   or code-based randompick and/or randomorder.
                   12078: 
                   12079: 
                   12080: 
1.531     jms      12081: =item  scantron_get_maxbubble() : 
                   12082: 
1.582     raeburn  12083:    Arguments:
                   12084:        $nav_error  - Reference to scalar which is a flag to indicate a
                   12085:                       failure to retrieve a navmap object.
                   12086:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   12087:        calling routine should trap the error condition and display the warning
                   12088:        found in &navmap_errormsg().
                   12089: 
1.649     raeburn  12090:        $scantron_config - Reference to bubblesheet format configuration hash.
                   12091: 
1.531     jms      12092:    Returns the maximum number of bubble lines that are expected to
                   12093:    occur. Does this by walking the selected sequence rendering the
                   12094:    resource and then checking &Apache::lonxml::get_problem_counter()
                   12095:    for what the current value of the problem counter is.
                   12096: 
                   12097:    Caches the results to $env{'form.scantron_maxbubble'},
                   12098:    $env{'form.scantron.bubble_lines.n'}, 
                   12099:    $env{'form.scantron.first_bubble_line.n'} and
                   12100:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  12101:    which are the total number of bubble lines, the number of bubble
1.531     jms      12102:    lines for response n and number of the first bubble line for response n,
                   12103:    and a comma separated list of numbers of bubble lines for sub-questions
                   12104:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   12105: 
                   12106: 
                   12107: =item  scantron_validate_missingbubbles() : 
                   12108: 
                   12109:    Validates all scanlines in the selected file to not have any
                   12110:     answers that don't have bubbles that have not been verified
                   12111:     to be bubble free.
                   12112: 
                   12113: =item  scantron_process_students() : 
                   12114: 
1.659     raeburn  12115:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      12116: 
                   12117:    The parsed scanline hash is added to %env 
                   12118: 
                   12119:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   12120:    foreach resource , with the form data of
                   12121: 
                   12122: 	'submitted'     =>'scantron' 
                   12123: 	'grade_target'  =>'grade',
                   12124: 	'grade_username'=> username of student
                   12125: 	'grade_domain'  => domain of student
                   12126: 	'grade_courseid'=> of course
                   12127: 	'grade_symb'    => symb of resource to grade
                   12128: 
                   12129:     This triggers a grading pass. The problem grading code takes care
                   12130:     of converting the bubbled letter information (now in %env) into a
                   12131:     valid submission.
                   12132: 
                   12133: =item  scantron_upload_scantron_data() :
                   12134: 
1.659     raeburn  12135:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      12136: 
                   12137: =item  scantron_upload_scantron_data_save() : 
                   12138: 
                   12139:    Adds a provided bubble information data file to the course if user
1.770     raeburn  12140:    has the correct privileges to do so.
                   12141: 
                   12142: = item scantron_upload_delete() :
                   12143: 
                   12144:    Deletes a previously uploaded bubble information data file, if user
                   12145:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      12146: 
                   12147: =item  valid_file() :
                   12148: 
                   12149:    Validates that the requested bubble data file exists in the course.
                   12150: 
                   12151: =item  scantron_download_scantron_data() : 
                   12152: 
                   12153:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  12154:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      12155:    course.
                   12156: 
                   12157: =item  scantron_validate_ID() : 
                   12158: 
                   12159:    Validates all scanlines in the selected file to not have any
1.556     weissno  12160:    invalid or underspecified student/employee IDs
1.531     jms      12161: 
1.582     raeburn  12162: =item navmap_errormsg() :
                   12163: 
                   12164:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  12165:    Should be called whenever the request to instantiate a navmap object fails.
                   12166: 
                   12167: =back
1.582     raeburn  12168: 
1.531     jms      12169: =back
                   12170: 
                   12171: =cut

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