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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.784   ! raeburn     4: # $Id: grades.pm,v 1.783 2021/01/23 20:32:17 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.396     banghart 2209:         my ($string,$timestamp)= &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.745     raeburn  2561:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.773     raeburn  2562: 
1.702     kruse    2563:     my $lastsubonly;
1.468     albertel 2564: 
1.702     kruse    2565:     if ($$timestamp eq '') {
                   2566:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2567:     } elsif ($is_tool) {
                   2568:         $lastsubonly =
                   2569:             '<div class="LC_grade_submissions_body">'
                   2570:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2571:     } else {
                   2572:         $lastsubonly =
                   2573:             '<div class="LC_grade_submissions_body">'
                   2574:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2575: 
                   2576: 	my %seenparts;
                   2577: 	my @part_response_id = &flatten_responseType($responseType);
                   2578: 	foreach my $part (@part_response_id) {
                   2579: 	    my ($partid,$respid) = @{ $part };
                   2580: 	    my $display_part=&get_display_part($partid,$symb);
                   2581: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2582: 		if (exists($seenparts{$partid})) { next; }
                   2583: 		$seenparts{$partid}=1;
                   2584:                 $request->print(
                   2585:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2586:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2587:                                '<a href="javascript:viewSubmitter(\''.
                   2588:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2589:                                '\');" target="_self">'.
                   2590:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2591:                     '<br />');
                   2592: 		next;
1.773     raeburn  2593: 	    }
1.702     kruse    2594: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2595: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2596:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2597:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2598:                     ' <span class="LC_internal_info">'.
                   2599:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2600:                     '</span>&nbsp; &nbsp;'.
                   2601: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2602: 		next;
                   2603: 	    }
                   2604: 	    foreach my $submission (@$string) {
                   2605: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2606: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2607: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2608: 		# Similarity check
                   2609:                 my $similar='';
                   2610:                 my ($type,$trial,$rndseed);
                   2611:                 if ($hide eq 'rand') {
                   2612:                     $type = 'randomizetry';
                   2613:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2614:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2615:                 }
                   2616: 	        if ($env{'form.checkPlag'}) {
1.774     raeburn  2617: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2618: 		    &most_similar($uname,$udom,$symb,$subval);
1.702     kruse    2619: 		    if ($osim) {
                   2620: 			$osim=int($osim*100.0);
                   2621:                         if ($hide eq 'anon') {
                   2622:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2623:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2624:                         } else {
1.753     raeburn  2625: 			    $similar='<hr />';
                   2626:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2627:                                 $similar .= '<h3><span class="LC_warning">'.
                   2628:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2629:                                                 $osim,
                   2630:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2631:                                             '</span></h3>';
                   2632:                             } else {
                   2633:                                 my %old_course_desc;
                   2634:                                 if ($ocrsid ne '') {
                   2635:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2636:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
                   2637:                                     } else {
                   2638:                                         my $args;
                   2639:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   2640:                                             $args = {'one_time' => 1};
                   2641:                                         }
                   2642:                                         %old_course_desc =
                   2643:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
                   2644:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
                   2645:                                     }
                   2646:                                     $similar .=
                   2647:                                         '<h3><span class="LC_warning">'.
                   2648:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2649:                                             $osim,
                   2650:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2651:                                             $old_course_desc{'description'},
                   2652:                                             $old_course_desc{'num'},
                   2653:                                             $old_course_desc{'domain'}).
                   2654:                                         '</span></h3>';
                   2655:                                 } else {
                   2656:                                     $similar .=
                   2657:                                         '<h3><span class="LC_warning">'.
                   2658:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2659:                                             $osim,
                   2660:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2661:                                         '</span></h3>';
                   2662:                                 }
                   2663:                             }
                   2664:                             $similar .= '<blockquote><i>'.
                   2665:                                         &keywords_highlight($oessay).
                   2666:                                         '</i></blockquote><hr />';
1.702     kruse    2667:                         }
                   2668: 	            }
                   2669: 		}
                   2670: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2671:                                      undef,$type,$trial,$rndseed);
1.773     raeburn  2672:                 if (($env{'form.lastSub'} eq 'lastonly') ||
                   2673:                     ($env{'form.lastSub'} eq 'datesub')  ||
                   2674:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
1.702     kruse    2675: 		    my $display_part=&get_display_part($partid,$symb);
                   2676:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2677:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2678:                         ' <span class="LC_internal_info">'.
                   2679:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2680:                         '</span>&nbsp; &nbsp;';
                   2681: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2682: 		    if (@$files) {
                   2683:                         if ($hide eq 'anon') {
                   2684:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2685:                         } else {
                   2686:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2687:                                         .'<br /><span class="LC_warning">';
                   2688:                             if(@$files == 1) {
                   2689:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2690:                             } else {
1.702     kruse    2691:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2692:                             }
1.774     raeburn  2693:                             $lastsubonly .= '</span>';
1.702     kruse    2694:                             foreach my $file (@$files) {
                   2695:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2696:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2697:                             }
                   2698:                         }
1.702     kruse    2699: 			$lastsubonly.='<br />';
                   2700:                     }
                   2701:                     if ($hide eq 'anon') {
                   2702:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2703:                     } else {
1.774     raeburn  2704:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  2705:                         if ($draft) {
                   2706:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2707:                         }
                   2708:                         $subval =
1.702     kruse    2709: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2710: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2711:                         if ($responsetype eq 'essay') {
                   2712:                             $subval =~ s{\n}{<br />}g;
                   2713:                         }
                   2714:                         $lastsubonly.=$subval."\n";
1.702     kruse    2715:                     }
1.774     raeburn  2716:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.702     kruse    2717: 		    $lastsubonly.='</div>';
1.41      ng       2718: 		}
1.702     kruse    2719:             }
1.151     albertel 2720: 	}
1.702     kruse    2721: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2722:     }
                   2723:     $request->print($lastsubonly);
                   2724:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2725:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2726: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.773     raeburn  2727:     }
1.702     kruse    2728:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2729:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2730:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2731: 								 $env{'request.course.id'},
1.44      ng       2732: 								 $last,'.submission',
1.726     raeburn  2733: 								 'Apache::grades::keywords_highlight',
                   2734:                                                                  $usec,$identifier));
1.41      ng       2735:     }
1.121     ng       2736:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2737: 	.$udom.'" />'."\n");
1.44      ng       2738:     # return if view submission with no grading option
1.618     www      2739:     if (!&canmodify($usec)) {
1.633     www      2740: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2741: 	return;
1.180     albertel 2742:     } else {
1.468     albertel 2743: 	$request->print('</div>'."\n");
1.41      ng       2744:     }
1.33      ng       2745: 
1.773     raeburn  2746:     # grading message center
                   2747: 
                   2748:     if ($env{'form.compmsg'}) {
                   2749:         my $result='<div class="LC_Box">'.
                   2750:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2751:                    '<div class="LC_grade_message_center_body">';
                   2752:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2753:         my $msgfor = $givenn.' '.$lastname;
                   2754:         if (scalar(@$col_fullnames) > 0) {
                   2755:             my $lastone = pop(@$col_fullnames);
                   2756:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2757:         }
                   2758:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2759:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2760:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2761:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2762:                  ',\''.$msgfor.'\');" target="_self">'.
                   2763:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2764:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2765:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2766:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2767:                  '<br />&nbsp;('.
                   2768:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2769:                  '</div></div>';
                   2770:         $request->print($result);
1.118     ng       2771:     }
1.41      ng       2772: 
                   2773:     my %seen = ();
                   2774:     my @partlist;
1.129     ng       2775:     my @gradePartRespid;
1.745     raeburn  2776:     my @part_response_id;
                   2777:     if ($is_tool) {
                   2778:         @part_response_id = ([0,'']);
                   2779:     } else {
                   2780:         @part_response_id = &flatten_responseType($responseType);
                   2781:     }
1.585     bisitz   2782:     $request->print(
1.588     bisitz   2783:         '<div class="LC_Box">'
                   2784:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2785:     );
1.592     bisitz   2786:     $request->print(&gradeBox_start());
1.375     albertel 2787:     foreach my $part_response_id (@part_response_id) {
                   2788:     	my ($partid,$respid) = @{ $part_response_id };
                   2789: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2790: 	next if ($seen{$partid} > 0);
1.41      ng       2791: 	$seen{$partid}++;
1.524     raeburn  2792: 	push(@partlist,$partid);
                   2793: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2794: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2795:     }
1.585     bisitz   2796:     $request->print(&gradeBox_end()); # </div>
                   2797:     $request->print('</div>');
1.468     albertel 2798: 
                   2799:     $request->print('<div class="LC_grade_info_links">');
                   2800:     $request->print('</div>');
                   2801: 
1.45      ng       2802:     $result='<input type="hidden" name="partlist'.$counter.
                   2803: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2804:     $result.='<input type="hidden" name="gradePartRespid'.
                   2805: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2806:     my $ctr = 0;
                   2807:     while ($ctr < scalar(@partlist)) {
                   2808: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2809: 	    $partlist[$ctr].'" />'."\n";
                   2810: 	$ctr++;
                   2811:     }
1.468     albertel 2812:     $request->print($result.''."\n");
1.41      ng       2813: 
1.441     www      2814: # Done with printing info for one student
                   2815: 
1.468     albertel 2816:     $request->print('</div>');#LC_grade_show_user
1.441     www      2817: 
                   2818: 
1.41      ng       2819:     # print end of form
                   2820:     if ($counter == $total) {
1.592     bisitz   2821:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2822: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2823: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2824: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2825: 	my $ntstu ='<select name="NTSTU">'.
                   2826: 	    '<option>1</option><option>2</option>'.
                   2827: 	    '<option>3</option><option>5</option>'.
                   2828: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2829: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2830: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2831:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2832: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2833: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2834: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2835: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2836:         $endform.='<span class="LC_warning">'.
                   2837:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2838:                   '</span>'."\n" ;
1.349     albertel 2839:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2840:             "' name='increment' />";
1.485     albertel 2841: 	$endform.='</td></tr></table></form>';
1.41      ng       2842: 	$request->print($endform);
                   2843:     }
                   2844:     return '';
1.38      ng       2845: }
                   2846: 
1.464     albertel 2847: sub check_collaborators {
                   2848:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2849:     my ($result,@col_fullnames);
                   2850:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2851:     foreach my $part (keys(%$handgrade)) {
                   2852: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2853: 					'.maxcollaborators',
                   2854: 					$symb,$udom,$uname);
                   2855: 	next if ($ncol <= 0);
                   2856: 	$part =~ s/\_/\./g;
                   2857: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2858: 	my (@good_collaborators, @bad_collaborators);
                   2859: 	foreach my $possible_collaborator
1.630     www      2860: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2861: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2862: 	    next if ($possible_collaborator eq '');
1.631     www      2863: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2864: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2865: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2866: 	    # Doing this grep allows 'fuzzy' specification
                   2867: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2868: 			       keys(%$classlist));
                   2869: 	    if (! scalar(@matches)) {
                   2870: 		push(@bad_collaborators, $possible_collaborator);
                   2871: 	    } else {
                   2872: 		push(@good_collaborators, @matches);
                   2873: 	    }
                   2874: 	}
                   2875: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2876: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2877: 	    foreach my $name (@good_collaborators) {
                   2878: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2879: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2880: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2881: 	    }
1.630     www      2882: 	    $result.='</ol><br />'."\n";
1.466     albertel 2883: 	    my ($part)=split(/\./,$part);
1.464     albertel 2884: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2885: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2886: 		"\n";
                   2887: 	}
                   2888: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2889: 	    $result.='<div class="LC_warning">';
1.464     albertel 2890: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2891: 	    $result .= '</div>';
                   2892: 	}         
                   2893: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2894: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2895: 	    $result .= &mt('This student has submitted too many '.
                   2896: 		'collaborators.  Maximum is [_1].',$ncol);
                   2897: 	    $result .= '</div>';
                   2898: 	}
                   2899:     }
                   2900:     return ($result,$fullname,\@col_fullnames);
                   2901: }
                   2902: 
1.44      ng       2903: #--- Retrieve the last submission for all the parts
1.38      ng       2904: sub get_last_submission {
1.745     raeburn  2905:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2906:     my (@string,$timestamp,%lasthidden);
1.119     ng       2907:     if ($$returnhash{'version'}) {
1.46      ng       2908: 	my %lasthash=();
                   2909: 	my ($version);
1.119     ng       2910: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2911: 	    foreach my $key (sort(split(/\:/,
                   2912: 					$$returnhash{$version.':keys'}))) {
                   2913: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2914: 		$timestamp = 
1.545     raeburn  2915: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2916: 	    }
                   2917: 	}
1.640     raeburn  2918:         my (%typeparts,%randombytry);
1.596     raeburn  2919:         my $showsurv = 
                   2920:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2921:         foreach my $key (sort(keys(%lasthash))) {
                   2922:             if ($key =~ /\.type$/) {
                   2923:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2924:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2925:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2926:                     my ($ign,@parts) = split(/\./,$key);
                   2927:                     pop(@parts);
1.641     raeburn  2928:                     my $id = join('.',@parts);
1.640     raeburn  2929:                     if ($lasthash{$key} eq 'randomizetry') {
                   2930:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2931:                     } else {
                   2932:                         unless ($showsurv) {
                   2933:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2934:                         }
1.596     raeburn  2935:                     }
                   2936:                     delete($lasthash{$key});
                   2937:                 }
                   2938:             }
                   2939:         }
                   2940:         my @hidden = keys(%typeparts);
1.640     raeburn  2941:         my @randomize = keys(%randombytry);
1.397     albertel 2942: 	foreach my $key (keys(%lasthash)) {
                   2943: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2944:             my $hide;
                   2945:             if (@hidden) {
                   2946:                 foreach my $id (@hidden) {
                   2947:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2948:                         $hide = 'anon';
1.596     raeburn  2949:                         last;
                   2950:                     }
                   2951:                 }
                   2952:             }
1.640     raeburn  2953:             unless ($hide) {
                   2954:                 if (@randomize) {
1.732     raeburn  2955:                     foreach my $id (@randomize) {
1.640     raeburn  2956:                         if ($key =~ /^\Q$id\E/) {
                   2957:                             $hide = 'rand';
                   2958:                             last;
                   2959:                         }
                   2960:                     }
                   2961:                 }
                   2962:             }
1.397     albertel 2963: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2964: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2965:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2966:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2967:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2968: 	}
                   2969:     }
1.397     albertel 2970:     if (!@string) {
1.745     raeburn  2971:         my $msg;
                   2972:         if ($is_tool) {
1.747     raeburn  2973:             $msg = &mt('No grade passed back.');
1.745     raeburn  2974:         } else {
                   2975:             $msg = &mt('Nothing submitted - no attempts.');
                   2976:         }
1.397     albertel 2977: 	$string[0] =
1.745     raeburn  2978: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2979:     }
                   2980:     return (\@string,\$timestamp);
1.38      ng       2981: }
1.35      ng       2982: 
1.44      ng       2983: #--- High light keywords, with style choosen by user.
1.38      ng       2984: sub keywords_highlight {
1.44      ng       2985:     my $string    = shift;
1.257     albertel 2986:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2987:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2988:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2989:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2990:     foreach my $keyword (@keylist) {
                   2991: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2992:     }
                   2993:     return $string;
1.38      ng       2994: }
1.36      ng       2995: 
1.671     raeburn  2996: # For Tasks provide a mechanism to display previous version for one specific student
                   2997: 
                   2998: sub show_previous_task_version {
                   2999:     my ($request,$symb) = @_;
                   3000:     if ($symb eq '') {
1.717     bisitz   3001:         $request->print(
                   3002:             '<span class="LC_error">'.
                   3003:             &mt('Unable to handle ambiguous references.').
                   3004:             '</span>');
1.671     raeburn  3005:         return '';
                   3006:     }
                   3007:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3008:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3009:     if (!&canview($usec)) {
1.712     bisitz   3010:         $request->print(
                   3011:             '<span class="LC_warning">'.
1.713     bisitz   3012:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   3013:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3014:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3015:             '</span>');
1.671     raeburn  3016:         return;
                   3017:     }
                   3018:     my $mode = 'both';
                   3019:     my $isTask = ($symb =~/\.task$/);
                   3020:     if ($isTask) {
                   3021:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   3022:             if ($env{'form.fullname'} eq '') {
                   3023:                 $env{'form.fullname'} =
                   3024:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3025:             }
                   3026:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   3027:             $request->print("\n\n".
                   3028:                             '<div class="LC_grade_show_user">'.
                   3029:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   3030:                             '</h2>'."\n");
                   3031:             &Apache::lonxml::clear_problem_counter();
                   3032:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   3033:                             {'previousversion' => $env{'form.previousversion'} }));
                   3034:             $request->print("\n</div>");
                   3035:         }
                   3036:     }
                   3037:     return;
                   3038: }
                   3039: 
                   3040: sub choose_task_version_form {
                   3041:     my ($symb,$uname,$udom,$nomenu) = @_;
                   3042:     my $isTask = ($symb =~/\.task$/);
                   3043:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   3044:     if ($isTask) {
                   3045:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3046:                                               $udom,$uname);
                   3047:         if (($record{'resource.0.version'} eq '') ||
                   3048:             ($record{'resource.0.version'} < 2)) {
                   3049:             return ($record{'resource.0.version'},
                   3050:                     $record{'resource.0.version'},$result,$js);
                   3051:         } else {
                   3052:             $current = $record{'resource.0.version'};
                   3053:         }
                   3054:         if ($env{'form.previousversion'}) {
                   3055:             $displayed = $env{'form.previousversion'};
                   3056:             $rowtitle = &mt('Choose another version:')
                   3057:         } else {
                   3058:             $displayed = $current;
                   3059:             $rowtitle = &mt('Show earlier version:');
                   3060:         }
                   3061:         $result = '<div class="LC_left_float">';
                   3062:         my $list;
                   3063:         my $numversions = 0;
                   3064:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3065:             if ($i == $current) {
                   3066:                 if (!$env{'form.previousversion'} || $nomenu) {
                   3067:                     next;
                   3068:                 } else {
                   3069:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3070:                     $numversions ++;
                   3071:                 }
                   3072:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3073:                 unless ($i == $env{'form.previousversion'}) {
                   3074:                     $numversions ++;
                   3075:                 }
                   3076:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3077:             }
                   3078:         }
                   3079:         if ($numversions) {
                   3080:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3081:             $result .=
                   3082:                 '<form name="getprev" method="post" action=""'.
                   3083:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3084:                 &Apache::loncommon::start_data_table().
                   3085:                 &Apache::loncommon::start_data_table_row().
                   3086:                 '<th align="left">'.$rowtitle.'</th>'.
                   3087:                 '<td><select name="version">'.
                   3088:                 '<option>'.&mt('Select').'</option>'.
                   3089:                 $list.
                   3090:                 '</select></td>'.
                   3091:                 &Apache::loncommon::end_data_table_row();
                   3092:             unless ($nomenu) {
                   3093:                 $result .= &Apache::loncommon::start_data_table_row().
                   3094:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3095:                 '<td><span class="LC_nobreak">'.
                   3096:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3097:                 &mt('Yes').'</label>'.
                   3098:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3099:                 '</span></td>'.
                   3100:                 &Apache::loncommon::end_data_table_row();
                   3101:             }
                   3102:             $result .=
                   3103:                 &Apache::loncommon::start_data_table_row().
                   3104:                 '<th align="left">&nbsp;</th>'.
                   3105:                 '<td>'.
                   3106:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3107:                 '</td>'.
                   3108:                 &Apache::loncommon::end_data_table_row().
                   3109:                 &Apache::loncommon::end_data_table().
                   3110:                 '</form>';
                   3111:             $js = &previous_display_javascript($nomenu,$current);
                   3112:         } elsif ($displayed && $nomenu) {
                   3113:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3114:         } else {
                   3115:             $result .= &mt('No previous versions to show for this student');
                   3116:         }
                   3117:         $result .= '</div>';
                   3118:     }
                   3119:     return ($current,$displayed,$result,$js);
                   3120: }
                   3121: 
                   3122: sub previous_display_javascript {
                   3123:     my ($nomenu,$current) = @_;
                   3124:     my $js = <<"JSONE";
                   3125: <script type="text/javascript">
                   3126: // <![CDATA[
                   3127: function previousVersion(uname,udom,symb) {
                   3128:     var current = '$current';
                   3129:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3130:     var prevstr = new RegExp("^\\\\d+\$");
                   3131:     if (!prevstr.test(version)) {
                   3132:         return false;
                   3133:     }
                   3134:     var url = '';
                   3135:     if (version == current) {
                   3136:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3137:     } else {
                   3138:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3139:     }
                   3140: JSONE
                   3141:     if ($nomenu) {
                   3142:         $js .= <<"JSTWO";
                   3143:     document.location.href = url;
                   3144: JSTWO
                   3145:     } else {
                   3146:         $js .= <<"JSTHREE";
                   3147:     var newwin = 0;
                   3148:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3149:         if (document.getprev.prevwin[i].checked == true) {
                   3150:             newwin = document.getprev.prevwin[i].value;
                   3151:         }
                   3152:     }
                   3153:     if (newwin == 1) {
                   3154:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3155:         url = url+'&inhibitmenu=yes';
                   3156:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3157:             previousWin = window.open(url,'',options,1);
                   3158:         } else {
                   3159:             previousWin.location.href = url;
                   3160:         }
                   3161:         previousWin.focus();
                   3162:         return false;
                   3163:     } else {
                   3164:         document.location.href = url;
                   3165:         return false;
                   3166:     }
                   3167: JSTHREE
                   3168:     }
                   3169:     $js .= <<"ENDJS";
                   3170:     return false;
                   3171: }
                   3172: // ]]>
                   3173: </script>
                   3174: ENDJS
                   3175: 
                   3176: }
                   3177: 
1.44      ng       3178: #--- Called from submission routine
1.38      ng       3179: sub processHandGrade {
1.608     www      3180:     my ($request,$symb) = @_;
1.324     albertel 3181:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3182:     my $button = $env{'form.gradeOpt'};
                   3183:     my $ngrade = $env{'form.NCT'};
                   3184:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3185:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3186:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3187: 
1.44      ng       3188:     if ($button eq 'Save & Next') {
                   3189: 	my $ctr = 0;
                   3190: 	while ($ctr < $ngrade) {
1.257     albertel 3191: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  3192: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   3193:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3194: 	    if ($errorflag eq 'no_score') {
                   3195: 		$ctr++;
                   3196: 		next;
                   3197: 	    }
1.104     albertel 3198: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3199: 		$request->print(
                   3200:                     '<span class="LC_error">'
                   3201:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3202:                    .'</span>');
1.104     albertel 3203: 		$ctr++;
                   3204: 		next;
                   3205: 	    }
1.726     raeburn  3206:             if ($numhidden) {
                   3207:                 $request->print(
                   3208:                     '<span class="LC_info">'
                   3209:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3210:                    .'</span><br />');
                   3211:             }
1.257     albertel 3212: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3213: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3214: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3215:             my ($feedurl,$showsymb) =
                   3216: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3217: 	    my $messagetail;
1.62      albertel 3218: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3219: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3220: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3221: 		$subject.=' ['.$restitle.']';
1.44      ng       3222: 		my (@msgnum) = split(/,/,$includemsg);
                   3223: 		foreach (@msgnum) {
1.257     albertel 3224: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3225: 		}
1.80      ng       3226: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3227: 		if ($env{'form.withgrades'.$ctr}) {
                   3228: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3229: 		    $messagetail = " for <a href=\"".
1.605     www      3230: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3231: 		}
                   3232: 		$msgstatus = 
                   3233:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3234: 						     $message.$messagetail,
1.418     albertel 3235:                                                      undef,$feedurl,undef,
1.386     raeburn  3236:                                                      undef,undef,$showsymb,
                   3237:                                                      $restitle);
1.574     bisitz   3238: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3239: 				$msgstatus.'<br />');
1.44      ng       3240: 	    }
1.257     albertel 3241: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3242: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3243: 		foreach my $collabstr (@collabstrs) {
                   3244: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3245: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3246: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3247: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3248: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3249: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3250: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3251: 			    next;
1.418     albertel 3252: 			} elsif ($message ne '') {
                   3253: 			    my ($baseurl,$showsymb) = 
                   3254: 				&get_feedurl_and_symb($symb,$collaborator,
                   3255: 						      $udom);
                   3256: 			    if ($env{'form.withgrades'.$ctr}) {
                   3257: 				$messagetail = " for <a href=\"".
1.605     www      3258:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3259: 			    }
1.418     albertel 3260: 			    $msgstatus = 
                   3261: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3262: 			}
1.44      ng       3263: 		    }
                   3264: 		}
                   3265: 	    }
                   3266: 	    $ctr++;
                   3267: 	}
                   3268:     }
                   3269: 
1.773     raeburn  3270:     my $res_error;
                   3271:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3272:     if ($res_error) {
                   3273:         $request->print(&navmap_errormsg());
                   3274:         return;
                   3275:     }
                   3276: 
                   3277:     my %keyhash = ();
                   3278:     if ($numessay) {
1.119     ng       3279: 	# Keywords sorted in alphabatical order
1.257     albertel 3280: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3281: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  3282: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3283: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3284: 	$env{'form.keywords'} = join(' ',@keywords);
                   3285: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3286: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3287: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3288: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3289: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  3290:     }
1.119     ng       3291: 
1.773     raeburn  3292:     if ($env{'form.compmsg'}) {
1.119     ng       3293: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3294: 	# New messages are saved in env for the next student.
1.119     ng       3295: 	# All messages are saved in nohist_handgrade.db
                   3296: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3297: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3298: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3299: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3300: 		$idx++;
                   3301: 	    }
                   3302: 	    $ctr++;
1.41      ng       3303: 	}
1.119     ng       3304: 	$ctr = 0;
                   3305: 	while ($ctr < $ngrade) {
1.257     albertel 3306: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  3307: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3308: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3309: 	        $idx++;
1.119     ng       3310: 	    }
                   3311: 	    $ctr++;
1.41      ng       3312: 	}
1.257     albertel 3313: 	$env{'form.savemsgN'} = --$idx;
                   3314: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       3315:     }
1.773     raeburn  3316:     if (($numessay) || ($env{'form.compmsg'})) {
                   3317:         my $putresult = &Apache::lonnet::put
                   3318:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   3319:     }
                   3320: 
1.44      ng       3321:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3322:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3323:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3324: 	my ($ctr,$total) = (0,0);
                   3325: 	while ($ctr < $ngrade) {
1.257     albertel 3326: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3327: 	    $ctr++;
                   3328: 	}
1.257     albertel 3329: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3330: 	$ctr = 0;
                   3331: 	while ($ctr < $total) {
1.257     albertel 3332: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3333: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3334: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3335: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3336: 	    $ctr++;
                   3337: 	}
                   3338: 	return '';
                   3339:     }
1.36      ng       3340: 
1.44      ng       3341:     # Get the next/previous one or group of students
1.257     albertel 3342:     my $firststu = $env{'form.unamedom0'};
                   3343:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3344:     my $ctr = 2;
1.41      ng       3345:     while ($laststu eq '') {
1.257     albertel 3346: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3347: 	$ctr++;
                   3348: 	$laststu = $firststu if ($ctr > $ngrade);
                   3349:     }
1.44      ng       3350: 
1.41      ng       3351:     my (@parsedlist,@nextlist);
                   3352:     my ($nextflg) = 0;
1.524     raeburn  3353:     foreach my $item (sort 
1.294     albertel 3354: 	     {
                   3355: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3356: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3357: 		 }
                   3358: 		 return $a cmp $b;
                   3359: 	     } (keys(%$fullname))) {
1.41      ng       3360: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3361: 	    push(@parsedlist,$item);
1.41      ng       3362: 	}
1.524     raeburn  3363: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3364: 	if ($button eq 'Previous') {
1.524     raeburn  3365: 	    last if ($item eq $firststu);
                   3366: 	    push(@parsedlist,$item);
1.41      ng       3367: 	}
                   3368:     }
                   3369:     $ctr = 0;
                   3370:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3371:     foreach my $student (@parsedlist) {
1.257     albertel 3372: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3373: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3374: 	
                   3375: 	if ($submitonly eq 'queued') {
                   3376: 	    my %queue_status = 
                   3377: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3378: 							$udom,$uname);
                   3379: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3380: 	}
                   3381: 
1.156     albertel 3382: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3383: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3384: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3385: 	    my $submitted = 0;
1.248     albertel 3386: 	    my $ungraded = 0;
                   3387: 	    my $incorrect = 0;
1.524     raeburn  3388: 	    foreach my $item (keys(%status)) {
                   3389: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3390: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3391: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3392: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3393: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3394: 		    $submitted = 0;
                   3395: 		}
1.41      ng       3396: 	    }
1.156     albertel 3397: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3398: 				     $submitonly eq 'incorrect' ||
                   3399: 				     $submitonly eq 'graded'));
1.248     albertel 3400: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3401: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3402: 	}
1.524     raeburn  3403: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3404: 	last if ($ctr == $ntstu);
1.41      ng       3405: 	$ctr++;
                   3406:     }
1.36      ng       3407: 
1.41      ng       3408:     $ctr = 0;
                   3409:     my $total = scalar(@nextlist)-1;
1.39      ng       3410: 
1.524     raeburn  3411:     foreach (sort(@nextlist)) {
1.41      ng       3412: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3413: 	$env{'form.student'}  = $uname;
                   3414: 	$env{'form.userdom'}  = $udom;
                   3415: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3416: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3417: 	$ctr++;
                   3418:     }
                   3419:     if ($total < 0) {
1.653     raeburn  3420: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3421: 	$request->print($the_end);
                   3422:     }
                   3423:     return '';
1.38      ng       3424: }
1.36      ng       3425: 
1.44      ng       3426: #---- Save the score and award for each student, if changed
1.38      ng       3427: sub saveHandGrade {
1.324     albertel 3428:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3429:     my @version_parts;
1.104     albertel 3430:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3431: 					   $env{'request.course.id'});
1.104     albertel 3432:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3433:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3434:     my @parts_graded;
1.77      ng       3435:     my %newrecord  = ();
1.726     raeburn  3436:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3437:     my %aggregate = ();
                   3438:     my $aggregateflag = 0;
1.726     raeburn  3439:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3440:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3441:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3442:         $totchg += $numchgs;
                   3443:     }
1.301     albertel 3444:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3445:     foreach my $new_part (@parts) {
1.337     banghart 3446: 	#collaborator ($submi may vary for different parts
1.259     banghart 3447: 	if ($submitter && $new_part ne $part) { next; }
                   3448: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3449: 	if ($dropMenu eq 'excused') {
1.259     banghart 3450: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3451: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3452: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3453: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3454: 		}
1.364     banghart 3455: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3456: 	    }
1.125     ng       3457: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3458: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3459: 	    foreach my $key (keys(%record)) {
1.259     banghart 3460: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3461: 	    }
1.259     banghart 3462: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3463: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3464:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3465: 
                   3466:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3467: 					       [$new_part]);
                   3468:             my $aggtries =$totaltries;
1.269     raeburn  3469:             if ($last_resets{$new_part}) {
1.270     albertel 3470:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3471: 					   $new_part);
1.269     raeburn  3472:             }
1.270     albertel 3473: 
                   3474:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3475:             if ($aggtries > 0) {
1.327     albertel 3476:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3477:                 $aggregateflag = 1;
                   3478:             }
1.125     ng       3479: 	} elsif ($dropMenu eq '') {
1.259     banghart 3480: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3481: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3482: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3483: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3484: 		next;
                   3485: 	    }
1.259     banghart 3486: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3487: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3488: 	    my $partial= $pts/$wgt;
1.259     banghart 3489: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3490: 		#do not update score for part if not changed.
1.346     banghart 3491:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3492: 		next;
1.251     banghart 3493: 	    } else {
1.524     raeburn  3494: 	        push(@parts_graded,$new_part);
1.153     albertel 3495: 	    }
1.259     banghart 3496: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3497: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3498: 	    }
1.259     banghart 3499: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3500: 	    if ($partial == 0) {
1.153     albertel 3501: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3502: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3503: 		}
1.41      ng       3504: 	    } else {
1.153     albertel 3505: 		if ($record{$reckey} ne 'correct_by_override') {
                   3506: 		    $newrecord{$reckey} = 'correct_by_override';
                   3507: 		}
                   3508: 	    }	    
                   3509: 	    if ($submitter && 
1.259     banghart 3510: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3511: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3512: 	    }
1.259     banghart 3513: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3514: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3515: 	}
1.259     banghart 3516: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3517: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3518: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3519: 	        $dropMenu eq 'reset status')
                   3520: 	   {
1.524     raeburn  3521: 	    push(@version_parts,$new_part);
1.259     banghart 3522: 	}
1.41      ng       3523:     }
1.301     albertel 3524:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3525:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3526: 
1.344     albertel 3527:     if (%newrecord) {
                   3528:         if (@version_parts) {
1.364     banghart 3529:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3530:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3531: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3532: 	    foreach my $new_part (@version_parts) {
                   3533: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3534: 				$new_part,\%newrecord);
                   3535: 	    }
1.259     banghart 3536:         }
1.44      ng       3537: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3538: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3539: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3540: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3541:     }
1.269     raeburn  3542:     if ($aggregateflag) {
                   3543:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3544: 			      $cdom,$cnum);
1.269     raeburn  3545:     }
1.726     raeburn  3546:     return ('',$pts,$wgt,$totchg);
                   3547: }
                   3548: 
                   3549: sub makehidden {
1.728     raeburn  3550:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3551:     return unless (ref($record) eq 'HASH');
                   3552:     my %modified;
                   3553:     my $numchanged = 0;
                   3554:     if (exists($record->{$version.':keys'})) {
                   3555:         my $partsregexp = $parts;
                   3556:         $partsregexp =~ s/,/|/g;
                   3557:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3558:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3559:                  my $item = $1;
                   3560:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3561:                      $modified{$key} = $record->{$version.':'.$key};
                   3562:                  }
                   3563:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3564:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3565:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3566:                 $modified{$key} = $record->{$version.':'.$key};
                   3567:             }
                   3568:         }
                   3569:         if (keys(%modified)) {
                   3570:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3571:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3572:                 $numchanged ++;
                   3573:             }
                   3574:         }
                   3575:     }
                   3576:     return $numchanged;
1.36      ng       3577: }
1.322     albertel 3578: 
1.380     albertel 3579: sub check_and_remove_from_queue {
                   3580:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3581:     my @ungraded_parts;
                   3582:     foreach my $part (@{$parts}) {
                   3583: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3584: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3585: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3586: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3587: 		) {
                   3588: 	    push(@ungraded_parts, $part);
                   3589: 	}
                   3590:     }
                   3591:     if ( !@ungraded_parts ) {
                   3592: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3593: 					       $cnum,$domain,$stuname);
                   3594:     }
                   3595: }
                   3596: 
1.337     banghart 3597: sub handback_files {
                   3598:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3599:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3600:     my $res_error;
                   3601:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3602:     if ($res_error) {
                   3603:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3604:         return;
                   3605:     }
1.654     raeburn  3606:     my @handedback;
                   3607:     my $file_msg;
1.375     albertel 3608:     my @part_response_id = &flatten_responseType($responseType);
                   3609:     foreach my $part_response_id (@part_response_id) {
                   3610:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3611: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3612:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3613:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3614:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3615:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3616:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3617:                     my ($directory,$answer_file) = 
1.654     raeburn  3618:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3619:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3620: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3621: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3622:                     my $getpropath = 1;
1.773     raeburn  3623:                     my ($dir_list,$listerror) =
1.662     raeburn  3624:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3625:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3626: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3627:                     # fix filename
1.355     banghart 3628:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3629:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3630:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3631:             	                                $save_file_name);
1.337     banghart 3632:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3633:                         $request->print('<br /><span class="LC_error">'.
                   3634:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3635:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3636:                                         '</span>');
1.356     banghart 3637:                     } else {
1.360     banghart 3638:                         # mark the file as read only
1.654     raeburn  3639:                         push(@handedback,$save_file_name);
1.367     albertel 3640: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3641: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3642: 			}
                   3643:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3644: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3645:                     }
1.686     bisitz   3646:                     $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 3647:                 }
                   3648:             }
                   3649:         }
1.654     raeburn  3650:     }
                   3651:     if (@handedback > 0) {
                   3652:         $request->print('<br />');
                   3653:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3654:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3655:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3656:         my ($subject,$message);
                   3657:         if (scalar(@handedback) == 1) {
                   3658:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3659:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3660:         } else {
                   3661:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3662:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3663:         }
                   3664:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3665:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3666:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3667:         my ($feedurl,$showsymb) =
                   3668:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3669:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3670:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3671:         my $msgstatus =
                   3672:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3673:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3674:                  $restitle);
                   3675:         if ($msgstatus) {
                   3676:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3677:         }
                   3678:     }
1.338     banghart 3679:     return;
1.337     banghart 3680: }
                   3681: 
1.418     albertel 3682: sub get_feedurl_and_symb {
                   3683:     my ($symb,$uname,$udom) = @_;
                   3684:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3685:     $url = &Apache::lonnet::clutter($url);
                   3686:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3687: 					$symb,$udom,$uname);
                   3688:     if ($encrypturl =~ /^yes$/i) {
                   3689: 	&Apache::lonenc::encrypted(\$url,1);
                   3690: 	&Apache::lonenc::encrypted(\$symb,1);
                   3691:     }
                   3692:     return ($url,$symb);
                   3693: }
                   3694: 
1.313     banghart 3695: sub get_submitted_files {
                   3696:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3697:     my @files;
                   3698:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3699:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3700:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3701:     	    push(@files,$file_url.$file);
                   3702:         }
                   3703:     }
                   3704:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3705:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3706:     }
                   3707:     return (\@files);
                   3708: }
1.322     albertel 3709: 
1.269     raeburn  3710: # ----------- Provides number of tries since last reset.
                   3711: sub get_num_tries {
                   3712:     my ($record,$last_reset,$part) = @_;
                   3713:     my $timestamp = '';
                   3714:     my $num_tries = 0;
                   3715:     if ($$record{'version'}) {
                   3716:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3717:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3718:                 $timestamp = $$record{$version.':timestamp'};
                   3719:                 if ($timestamp > $last_reset) {
                   3720:                     $num_tries ++;
                   3721:                 } else {
                   3722:                     last;
                   3723:                 }
                   3724:             }
                   3725:         }
                   3726:     }
                   3727:     return $num_tries;
                   3728: }
                   3729: 
                   3730: # ----------- Determine decrements required in aggregate totals 
                   3731: sub decrement_aggs {
                   3732:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3733:     my %decrement = (
                   3734:                         attempts => 0,
                   3735:                         users => 0,
                   3736:                         correct => 0
                   3737:                     );
                   3738:     $decrement{'attempts'} = $aggtries;
                   3739:     if ($solvedstatus =~ /^correct/) {
                   3740:         $decrement{'correct'} = 1;
                   3741:     }
                   3742:     if ($aggtries == $totaltries) {
                   3743:         $decrement{'users'} = 1;
                   3744:     }
1.524     raeburn  3745:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3746:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3747:     }
                   3748:     return;
                   3749: }
                   3750: 
                   3751: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3752: sub get_last_resets {
1.270     albertel 3753:     my ($symb,$courseid,$partids) =@_;
                   3754:     my %last_resets;
1.269     raeburn  3755:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3756:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3757:     my @keys;
                   3758:     foreach my $part (@{$partids}) {
                   3759: 	push(@keys,"$symb\0$part\0resettime");
                   3760:     }
                   3761:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3762: 				     $cdom,$cname);
                   3763:     foreach my $part (@{$partids}) {
                   3764: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3765:     }
1.270     albertel 3766:     return %last_resets;
1.269     raeburn  3767: }
                   3768: 
1.251     banghart 3769: # ----------- Handles creating versions for portfolio files as answers
                   3770: sub version_portfiles {
1.343     banghart 3771:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3772:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3773:     my @returned_keys;
1.255     banghart 3774:     my $parts = join('|', @$parts_graded);
1.277     albertel 3775:     foreach my $key (keys(%$record)) {
1.259     banghart 3776:         my $new_portfiles;
1.263     banghart 3777:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3778:             my @versioned_portfiles;
1.367     albertel 3779:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3780:             if (@portfiles) {
                   3781:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3782:                                                       \@versioned_portfiles);
1.252     banghart 3783:             }
1.343     banghart 3784:             $$record{$key} = join(',',@versioned_portfiles);
                   3785:             push(@returned_keys,$key);
1.251     banghart 3786:         }
                   3787:     } 
1.343     banghart 3788:     return (@returned_keys);   
1.305     banghart 3789: }
                   3790: 
1.44      ng       3791: #--------------------------------------------------------------------------------------
                   3792: #
                   3793: #-------------------------- Next few routines handles grading by section or whole class
                   3794: #
                   3795: #--- Javascript to handle grading by section or whole class
1.42      ng       3796: sub viewgrades_js {
                   3797:     my ($request) = shift;
                   3798: 
1.539     riegler  3799:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3800:     &js_escape(\$alertmsg);
1.597     wenzelju 3801:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3802:    function writePoint(partid,weight,point) {
1.125     ng       3803: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3804: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3805: 	if (point == "textval") {
1.125     ng       3806: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3807: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3808: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3809: 		var resetbox = false;
                   3810: 		for (var i=0; i<radioButton.length; i++) {
                   3811: 		    if (radioButton[i].checked) {
                   3812: 			textbox.value = i;
                   3813: 			resetbox = true;
                   3814: 		    }
                   3815: 		}
                   3816: 		if (!resetbox) {
                   3817: 		    textbox.value = "";
                   3818: 		}
                   3819: 		return;
                   3820: 	    }
1.109     matthew  3821: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3822: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3823: 				   ") greater than the weight for the part. Accept?");
                   3824: 		if (resp == false) {
                   3825: 		    textbox.value = "";
                   3826: 		    return;
                   3827: 		}
                   3828: 	    }
1.42      ng       3829: 	    for (var i=0; i<radioButton.length; i++) {
                   3830: 		radioButton[i].checked=false;
1.109     matthew  3831: 		if (parseFloat(point) == i) {
1.42      ng       3832: 		    radioButton[i].checked=true;
                   3833: 		}
                   3834: 	    }
1.41      ng       3835: 
1.42      ng       3836: 	} else {
1.125     ng       3837: 	    textbox.value = parseFloat(point);
1.42      ng       3838: 	}
1.41      ng       3839: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3840: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3841: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3842: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3843: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3844: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3845: 	    if (saveval != "correct") {
                   3846: 		scorename.value = point;
1.43      ng       3847: 		if (selname[0].selected != true) {
                   3848: 		    selname[0].selected = true;
                   3849: 		}
1.42      ng       3850: 	    }
                   3851: 	}
1.125     ng       3852: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3853:     }
                   3854: 
                   3855:     function writeRadText(partid,weight) {
1.125     ng       3856: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3857: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3858:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3859: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3860: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3861: 	    for (var i=0; i<radioButton.length; i++) {
                   3862: 		radioButton[i].checked=false;
                   3863: 
                   3864: 	    }
                   3865: 	    textbox.value = "";
                   3866: 
                   3867: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3868: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3869: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3870: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3871: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3872: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3873: 		if ((saveval != "correct") || override) {
1.42      ng       3874: 		    scorename.value = "";
1.125     ng       3875: 		    if (selval[1].selected) {
                   3876: 			selname[1].selected = true;
                   3877: 		    } else {
                   3878: 			selname[2].selected = true;
                   3879: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3880: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3881: 		    }
1.42      ng       3882: 		}
                   3883: 	    }
1.43      ng       3884: 	} else {
                   3885: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3886: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3887: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3888: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3889: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3890: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3891: 		if ((saveval != "correct") || override) {
1.125     ng       3892: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3893: 		    selname[0].selected = true;
                   3894: 		}
                   3895: 	    }
                   3896: 	}	    
1.42      ng       3897:     }
                   3898: 
                   3899:     function changeSelect(partid,user) {
1.125     ng       3900: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3901: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3902: 	var point  = textbox.value;
1.125     ng       3903: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3904: 
1.109     matthew  3905: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3906: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3907: 	    textbox.value = "";
                   3908: 	    return;
                   3909: 	}
1.109     matthew  3910: 	if (parseFloat(point) > parseFloat(weight)) {
                   3911: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3912: 			       ") greater than the weight of the part. Accept?");
                   3913: 	    if (resp == false) {
                   3914: 		textbox.value = "";
                   3915: 		return;
                   3916: 	    }
                   3917: 	}
1.42      ng       3918: 	selval[0].selected = true;
                   3919:     }
                   3920: 
                   3921:     function changeOneScore(partid,user) {
1.125     ng       3922: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3923: 	if (selval[1].selected || selval[2].selected) {
                   3924: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3925: 	    if (selval[2].selected) {
                   3926: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3927: 	    }
1.269     raeburn  3928:         }
1.42      ng       3929:     }
                   3930: 
                   3931:     function resetEntry(numpart) {
                   3932: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3933: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3934: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3935: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3936: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3937: 	    for (var i=0; i<radioButton.length; i++) {
                   3938: 		radioButton[i].checked=false;
                   3939: 
                   3940: 	    }
                   3941: 	    textbox.value = "";
                   3942: 	    selval[0].selected = true;
                   3943: 
                   3944: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3945: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3946: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3947: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3948: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3949: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3950: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3951: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3952: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3953: 		if (saveselval == "excused") {
1.43      ng       3954: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3955: 		} else {
1.43      ng       3956: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3957: 		}
                   3958: 	    }
1.41      ng       3959: 	}
1.42      ng       3960:     }
                   3961: 
1.41      ng       3962: VIEWJAVASCRIPT
1.42      ng       3963: }
                   3964: 
1.44      ng       3965: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3966: sub viewgrades {
1.608     www      3967:     my ($request,$symb) = @_;
1.745     raeburn  3968:     my ($is_tool,$toolsymb);
                   3969:     if ($symb =~ /ext\.tool$/) {
                   3970:         $is_tool = 1;
                   3971:         $toolsymb = $symb;
                   3972:     }
1.42      ng       3973:     &viewgrades_js($request);
1.41      ng       3974: 
1.168     albertel 3975:     #need to make sure we have the correct data for later EXT calls, 
                   3976:     #thus invalidate the cache
                   3977:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3978:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3979:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3980:     &Apache::lonnet::clear_EXT_cache_status();
                   3981: 
1.398     albertel 3982:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3983: 
                   3984:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3985:     $result.=&jscriptNform($symb);
1.41      ng       3986: 
1.44      ng       3987:     #beginning of class grading form
1.442     banghart 3988:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3989:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3990: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3991: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3992: 	&build_section_inputs().
1.442     banghart 3993: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3994: 
1.738     raeburn  3995:     #retrieve selected groups
                   3996:     my (@groups,$group_display);
                   3997:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3998:     if (grep(/^all$/,@groups)) {
                   3999:         @groups = ('all');
                   4000:     } elsif (grep(/^none$/,@groups)) {
                   4001:         @groups = ('none');
                   4002:     } elsif (@groups > 0) {
                   4003:         $group_display = join(', ',@groups);
                   4004:     }
                   4005: 
                   4006:     my ($common_header,$specific_header,@sections,$section_display);
1.780     raeburn  4007:     if ($env{'request.course.sec'} ne '') {
                   4008:         @sections = ($env{'request.course.sec'});
                   4009:     } else {
                   4010:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   4011:     }
                   4012: 
                   4013: # Check if Save button should be usable
                   4014:     my $disabled = ' disabled="disabled"';
                   4015:     if ($perm{'mgr'}) {
                   4016:         if (grep(/^all$/,@sections)) {
                   4017:             undef($disabled);
                   4018:         } else {
                   4019:             foreach my $sec (@sections) {
                   4020:                 if (&canmodify($sec)) {
                   4021:                     undef($disabled);
                   4022:                     last;
                   4023:                 }
                   4024:             }
                   4025:         }
                   4026:     }
1.738     raeburn  4027:     if (grep(/^all$/,@sections)) {
                   4028:         @sections = ('all');
                   4029:         if ($group_display) {
                   4030:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4031:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4032:         } elsif (grep(/^none$/,@groups)) {
                   4033:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4034:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4035:         } else {
                   4036: 	    $common_header = &mt('Assign Common Grade to Class');
                   4037:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4038:         }
                   4039:     } elsif (grep(/^none$/,@sections)) {
                   4040:         @sections = ('none');
                   4041:         if ($group_display) {
                   4042:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4043:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4044:         } elsif (grep(/^none$/,@groups)) {
                   4045:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4046:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4047:         } else {
                   4048:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4049: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4050:         }
                   4051:     } else {
                   4052:         $section_display = join (", ",@sections);
                   4053:         if ($group_display) {
                   4054:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4055:                                  $section_display,$group_display);
                   4056:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4057:                                    $section_display,$group_display);
                   4058:         } elsif (grep(/^none$/,@groups)) {
                   4059:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4060:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4061:         } else {
                   4062:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4063: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4064:         }
                   4065:     }
                   4066:     my %submit_types = &substatus_options();
                   4067:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4068: 
                   4069:     if ($env{'form.submitonly'} eq 'all') {
                   4070:         $result.= '<h3>'.$common_header.'</h3>';
                   4071:     } else {
1.745     raeburn  4072:         my $text;
                   4073:         if ($is_tool) {
                   4074:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4075:         } else {
                   4076:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4077:         }
                   4078:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 4079:     }
1.738     raeburn  4080:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4081:     #radio buttons/text box for assigning points for a section or class.
                   4082:     #handles different parts of a problem
1.582     raeburn  4083:     my $res_error;
                   4084:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4085:     if ($res_error) {
                   4086:         return &navmap_errormsg();
                   4087:     }
1.42      ng       4088:     my %weight = ();
                   4089:     my $ctsparts = 0;
1.45      ng       4090:     my %seen = ();
1.745     raeburn  4091:     my @part_response_id;
                   4092:     if ($is_tool) {
                   4093:         @part_response_id = ([0,'']);
                   4094:     } else {
                   4095:         @part_response_id = &flatten_responseType($responseType);
                   4096:     }
1.375     albertel 4097:     foreach my $part_response_id (@part_response_id) {
                   4098:     	my ($partid,$respid) = @{ $part_response_id };
                   4099: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4100: 	next if $seen{$partid};
                   4101: 	$seen{$partid}++;
1.42      ng       4102: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4103: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4104: 
1.324     albertel 4105: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4106: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4107: 	my $ctr = 0;
1.42      ng       4108: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4109: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4110: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4111: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4112: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4113: 	    $ctr++;
                   4114: 	}
1.485     albertel 4115: 	$radio.='</tr></table>';
                   4116: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4117: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4118: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4119: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   4120:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4121:             '<select name="SELVAL_'.$partid.'" '.
                   4122:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   4123:                 $weight{$partid}.')"> '.
1.401     albertel 4124: 	    '<option selected="selected"> </option>'.
1.485     albertel 4125: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4126: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4127: 	    '</select></td>'.
                   4128:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4129: 	$line.='<input type="hidden" name="partid_'.
                   4130: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4131: 	$line.='<input type="hidden" name="weight_'.
                   4132: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4133: 
                   4134: 	$result.=
                   4135: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4136: 	    '<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 4137: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4138: 	$ctsparts++;
1.41      ng       4139:     }
1.474     albertel 4140:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4141: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4142:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4143: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4144: 
1.44      ng       4145:     #table listing all the students in a section/class
                   4146:     #header of table
1.738     raeburn  4147:     if ($env{'form.submitonly'} eq 'all') {
                   4148:         $result.= '<h3>'.$specific_header.'</h3>';
                   4149:     } else {
1.745     raeburn  4150:         my $text;
                   4151:         if ($is_tool) {
                   4152:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4153:         } else {
                   4154:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4155:         }
                   4156:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  4157:     }
                   4158:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4159: 	      &Apache::loncommon::start_data_table_header_row().
                   4160: 	      '<th>'.&mt('No.').'</th>'.
                   4161: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4162:     my $partserror;
                   4163:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4164:     if ($partserror) {
                   4165:         return &navmap_errormsg();
                   4166:     }
1.324     albertel 4167:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4168:     my @partids = ();
1.41      ng       4169:     foreach my $part (@parts) {
1.745     raeburn  4170: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  4171:         my $narrowtext = &mt('Tries');
                   4172: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  4173: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 4174: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4175:         push(@partids,$partid);
1.628     www      4176: #
                   4177: # FIXME: Looks like $display looks at English text
                   4178: #
1.324     albertel 4179: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4180: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4181: 	    $result.='<th>'.
1.697     bisitz   4182: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   4183: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4184: 	    next;
1.485     albertel 4185: 	    
1.207     albertel 4186: 	} else {
1.485     albertel 4187: 	    if ($display =~ /Problem Status/) {
                   4188: 		my $grade_status_mt = &mt('Grade Status');
                   4189: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4190: 	    }
                   4191: 	    my $part_mt = &mt('Part:');
                   4192: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4193: 	}
1.485     albertel 4194: 
1.474     albertel 4195: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4196:     }
1.474     albertel 4197:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4198: 
1.270     albertel 4199:     my %last_resets = 
                   4200: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4201: 
1.41      ng       4202:     #get info for each student
1.44      ng       4203:     #list all the students - with points and grade status
1.738     raeburn  4204:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4205:     my $ctr = 0;
1.294     albertel 4206:     foreach (sort 
                   4207: 	     {
                   4208: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4209: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4210: 		 }
                   4211: 		 return $a cmp $b;
                   4212: 	     } (keys(%$fullname))) {
1.324     albertel 4213: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  4214: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4215:     }
1.474     albertel 4216:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4217:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.780     raeburn  4218:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   4219: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4220:     if ($ctr == 0) {
1.442     banghart 4221:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4222:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4223:                 '<span class="LC_warning">';
                   4224:         if ($env{'form.submitonly'} eq 'all') {
                   4225:             if (grep(/^all$/,@sections)) {
                   4226:                 if (grep(/^all$/,@groups)) {
                   4227:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4228:                                    $stu_status);
                   4229:                 } elsif (grep(/^none$/,@groups)) {
                   4230:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4231:                                    $stu_status); 
                   4232:                 } else {
                   4233:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4234:                                    $group_display,$stu_status);
                   4235:                 }
                   4236:             } elsif (grep(/^none$/,@sections)) {
                   4237:                 if (grep(/^all$/,@groups)) {
                   4238:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4239:                                    $stu_status);
                   4240:                 } elsif (grep(/^none$/,@groups)) {
                   4241:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4242:                                    $stu_status);
                   4243:                 } else {
                   4244:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4245:                                    $group_display,$stu_status);
                   4246:                 }
                   4247:             } else {
                   4248:                 if (grep(/^all$/,@groups)) {
                   4249:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4250:                                    $section_display,$stu_status);
                   4251:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4252:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4253:                                    $section_display,$stu_status);
                   4254:                 } else {
                   4255:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4256:                                    $section_display,$group_display,$stu_status);
                   4257:                 }
                   4258:             }
                   4259:         } else {
                   4260:             if (grep(/^all$/,@sections)) {
                   4261:                 if (grep(/^all$/,@groups)) {
                   4262:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4263:                                    $stu_status,$submission_status);
                   4264:                 } elsif (grep(/^none$/,@groups)) {
                   4265:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4266:                                    $stu_status,$submission_status);
                   4267:                 } else {
                   4268:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4269:                                    $group_display,$stu_status,$submission_status);
                   4270:                 }
                   4271:             } elsif (grep(/^none$/,@sections)) {
                   4272:                 if (grep(/^all$/,@groups)) {
                   4273:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4274:                                    $stu_status,$submission_status);
                   4275:                 } elsif (grep(/^none$/,@groups)) {
                   4276:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4277:                                    $stu_status,$submission_status);
                   4278:                 } else {
                   4279:                     $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.',
                   4280:                                    $group_display,$stu_status,$submission_status);
                   4281:                 }
                   4282:             } else {
                   4283:                 if (grep(/^all$/,@groups)) {
                   4284: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4285: 	                           $section_display,$stu_status,$submission_status);
                   4286:                 } elsif (grep(/^none$/,@groups)) {
                   4287:                     $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.',
                   4288:                                    $section_display,$stu_status,$submission_status);
                   4289:                 } else {
                   4290:                     $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.',
                   4291:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4292:                 }
                   4293:             }
                   4294:         }
                   4295: 	$result .= '</span><br />';
1.96      albertel 4296:     }
1.41      ng       4297:     return $result;
                   4298: }
                   4299: 
1.738     raeburn  4300: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4301: sub viewstudentgrade {
1.745     raeburn  4302:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4303:     my ($uname,$udom) = split(/:/,$student);
                   4304:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4305:     my $submitonly = $env{'form.submitonly'};
                   4306:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4307:         my %partstatus = ();
                   4308:         if (ref($parts) eq 'ARRAY') {
                   4309:             foreach my $apart (@{$parts}) {
                   4310:                 my ($part,$type) = &split_part_type($apart);
                   4311:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4312:                 $status = 'nothing' if ($status eq '');
                   4313:                 $partstatus{$part}      = $status;
                   4314:                 my $subkey = "resource.$part.submitted_by";
                   4315:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4316:             }
                   4317:             my $submitted = 0;
                   4318:             my $graded = 0;
                   4319:             my $incorrect = 0;
                   4320:             foreach my $key (keys(%partstatus)) {
                   4321:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4322:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4323:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4324: 
                   4325:                 my $partid = (split(/\./,$key))[1];
                   4326:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4327:                     $submitted = 0;
                   4328:                 }
                   4329:             }
                   4330:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4331:                                        $submitonly eq 'incorrect' ||
                   4332:                                        $submitonly eq 'graded'));
                   4333:             return if (!$graded && ($submitonly eq 'graded'));
                   4334:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4335:         }
                   4336:     }
                   4337:     if ($submitonly eq 'queued') {
                   4338:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4339:         my %queue_status =
                   4340:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4341:                                                     $udom,$uname);
                   4342:         return if (!defined($queue_status{'gradingqueue'}));
                   4343:     }
                   4344:     $$ctr++;
                   4345:     my %aggregates = ();
1.474     albertel 4346:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4347: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4348: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4349: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4350: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4351: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4352:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4353:     foreach my $apart (@$parts) {
                   4354: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4355: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4356:         $result.='<td align="center">';
1.269     raeburn  4357:         my ($aggtries,$totaltries);
                   4358:         unless (exists($aggregates{$part})) {
1.270     albertel 4359: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4360: 	    $aggtries = $totaltries;
1.269     raeburn  4361:             if ($$last_resets{$part}) {  
1.270     albertel 4362:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4363: 					   $part);
                   4364:             }
1.269     raeburn  4365:             $result.='<input type="hidden" name="'.
                   4366:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4367:             $result.='<input type="hidden" name="'.
                   4368:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4369:             $aggregates{$part} = 1;
                   4370:         }
1.41      ng       4371: 	if ($type eq 'awarded') {
1.320     albertel 4372: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4373: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4374: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4375: 	    $result.='<input type="text" name="'.
1.89      albertel 4376: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4377:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4378: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4379: 	} elsif ($type eq 'solved') {
                   4380: 	    my ($status,$foo)=split(/_/,$score,2);
                   4381: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4382: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4383: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4384: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4385: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4386:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4387: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4388: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4389: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4390: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4391: 	} else {
                   4392: 	    $result.='<input type="hidden" name="'.
                   4393: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4394: 		    "\n";
1.233     albertel 4395: 	    $result.='<input type="text" name="'.
1.122     ng       4396: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4397: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4398: 	}
                   4399:     }
1.474     albertel 4400:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4401:     return $result;
1.38      ng       4402: }
                   4403: 
1.44      ng       4404: #--- change scores for all the students in a section/class
                   4405: #    record does not get update if unchanged
1.38      ng       4406: sub editgrades {
1.608     www      4407:     my ($request,$symb) = @_;
1.745     raeburn  4408:     my $toolsymb;
                   4409:     if ($symb =~ /ext\.tool$/) {
                   4410:         $toolsymb = $symb;
                   4411:     }
1.41      ng       4412: 
1.433     banghart 4413:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4414:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  4415:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4416: 
1.477     albertel 4417:     my $result= &Apache::loncommon::start_data_table().
                   4418: 	&Apache::loncommon::start_data_table_header_row().
                   4419: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4420: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4421:     my %scoreptr = (
                   4422: 		    'correct'  =>'correct_by_override',
                   4423: 		    'incorrect'=>'incorrect_by_override',
                   4424: 		    'excused'  =>'excused',
                   4425: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4426:                     'credited' =>'credit_attempted',
1.43      ng       4427: 		    'nothing'  => '',
                   4428: 		    );
1.257     albertel 4429:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4430: 
1.44      ng       4431:     my (@partid);
                   4432:     my %weight = ();
1.54      albertel 4433:     my %columns = ();
1.44      ng       4434:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4435: 
1.582     raeburn  4436:     my $partserror;
                   4437:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4438:     if ($partserror) {
                   4439:         return &navmap_errormsg();
                   4440:     }
1.54      albertel 4441:     my $header;
1.257     albertel 4442:     while ($ctr < $env{'form.totalparts'}) {
                   4443: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4444: 	push(@partid,$partid);
1.257     albertel 4445: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4446: 	$ctr++;
1.54      albertel 4447:     }
1.324     albertel 4448:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4449:     my $totcolspan = 0;
1.54      albertel 4450:     foreach my $partid (@partid) {
1.478     albertel 4451: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4452: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4453: 	$columns{$partid}=2;
                   4454: 	foreach my $stores (@parts) {
                   4455: 	    my ($part,$type) = &split_part_type($stores);
                   4456: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4457: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4458: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4459: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4460:             my $narrowtext = &mt('Tries');
                   4461: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4462: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4463: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4464: 	    $columns{$partid}+=2;
                   4465: 	}
1.748     raeburn  4466:         $totcolspan += $columns{$partid};
1.54      albertel 4467:     }
                   4468:     foreach my $partid (@partid) {
1.324     albertel 4469: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4470: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4471: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4472: 	    '</th>';
1.54      albertel 4473: 
1.44      ng       4474:     }
1.477     albertel 4475:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4476: 	&Apache::loncommon::start_data_table_header_row().
                   4477: 	$header.
                   4478: 	&Apache::loncommon::end_data_table_header_row();
                   4479:     my @noupdate;
1.126     ng       4480:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4481:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4482: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4483: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4484: 	my %newrecord;
                   4485: 	my $updateflag = 0;
1.108     albertel 4486: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4487: 	my $canmodify = &canmodify($usec);
                   4488: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4489: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4490: 	if (!$canmodify) {
1.477     albertel 4491: 	    push(@noupdate,
1.748     raeburn  4492: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4493: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4494: 	    next;
                   4495: 	}
1.269     raeburn  4496:         my %aggregate = ();
                   4497:         my $aggregateflag = 0;
1.281     albertel 4498: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4499: 	foreach (@partid) {
1.257     albertel 4500: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4501: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4502: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4503: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4504: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4505: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4506: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4507: 	    my $score;
                   4508: 	    if ($partial eq '') {
1.257     albertel 4509: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4510: 	    } elsif ($partial > 0) {
                   4511: 		$score = 'correct_by_override';
                   4512: 	    } elsif ($partial == 0) {
                   4513: 		$score = 'incorrect_by_override';
                   4514: 	    }
1.257     albertel 4515: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4516: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4517: 
1.292     albertel 4518: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4519: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4520: 	    if ($dropMenu eq 'reset status' &&
                   4521: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4522: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4523: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4524: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4525: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4526: 		$updateflag = 1;
1.269     raeburn  4527:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4528:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4529:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4530:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4531:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4532:                     $aggregateflag = 1;
                   4533:                 }
1.139     albertel 4534: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4535: 		$updateflag = 1;
                   4536: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4537: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4538: 		$rec_update++;
1.125     ng       4539: 	    }
                   4540: 
1.93      albertel 4541: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4542: 		'<td align="center">'.$awarded.
                   4543: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4544: 
1.54      albertel 4545: 
                   4546: 	    my $partid=$_;
                   4547: 	    foreach my $stores (@parts) {
                   4548: 		my ($part,$type) = &split_part_type($stores);
                   4549: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4550: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4551: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4552: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4553: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4554: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4555: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4556: 		    $updateflag=1;
                   4557: 		}
1.93      albertel 4558: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4559: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4560: 	    }
1.44      ng       4561: 	}
1.477     albertel 4562: 	$line.="\n";
1.301     albertel 4563: 
                   4564: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4565: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4566: 
1.44      ng       4567: 	if ($updateflag) {
                   4568: 	    $count++;
1.257     albertel 4569: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4570: 				    $udom,$uname);
1.301     albertel 4571: 
                   4572: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4573: 					      $cnum,$udom,$uname)) {
                   4574: 		# need to figure out if should be in queue.
                   4575: 		my %record =  
                   4576: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4577: 					     $udom,$uname);
                   4578: 		my $all_graded = 1;
                   4579: 		my $none_graded = 1;
                   4580: 		foreach my $part (@parts) {
                   4581: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4582: 			$all_graded = 0;
                   4583: 		    } else {
                   4584: 			$none_graded = 0;
                   4585: 		    }
                   4586: 		}
                   4587: 
                   4588: 		if ($all_graded || $none_graded) {
                   4589: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4590: 							   $symb,$cdom,$cnum,
                   4591: 							   $udom,$uname);
                   4592: 		}
                   4593: 	    }
                   4594: 
1.477     albertel 4595: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4596: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4597: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4598: 	    $updateCtr++;
1.93      albertel 4599: 	} else {
1.477     albertel 4600: 	    push(@noupdate,
                   4601: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4602: 	    $noupdateCtr++;
1.44      ng       4603: 	}
1.269     raeburn  4604:         if ($aggregateflag) {
                   4605:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4606: 				  $cdom,$cnum);
1.269     raeburn  4607:         }
1.93      albertel 4608:     }
1.477     albertel 4609:     if (@noupdate) {
1.748     raeburn  4610:         my $numcols=$totcolspan+2;
1.477     albertel 4611: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4612: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4613: 	    &mt('No Changes Occurred For the Students Below').
                   4614: 	    '</td>'.
1.477     albertel 4615: 	    &Apache::loncommon::end_data_table_row();
                   4616: 	foreach my $line (@noupdate) {
                   4617: 	    $result.=
                   4618: 		&Apache::loncommon::start_data_table_row().
                   4619: 		$line.
                   4620: 		&Apache::loncommon::end_data_table_row();
                   4621: 	}
1.44      ng       4622:     }
1.614     www      4623:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4624:     my $msg = '<p><b>'.
                   4625: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4626: 	    $rec_update,$count).'</b><br />'.
                   4627: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4628: 	'</b></p>';
1.44      ng       4629:     return $title.$msg.$result;
1.5       albertel 4630: }
1.54      albertel 4631: 
                   4632: sub split_part_type {
                   4633:     my ($partstr) = @_;
                   4634:     my ($temp,@allparts)=split(/_/,$partstr);
                   4635:     my $type=pop(@allparts);
1.439     albertel 4636:     my $part=join('_',@allparts);
1.54      albertel 4637:     return ($part,$type);
                   4638: }
                   4639: 
1.44      ng       4640: #------------- end of section for handling grading by section/class ---------
                   4641: #
                   4642: #----------------------------------------------------------------------------
                   4643: 
1.5       albertel 4644: 
1.44      ng       4645: #----------------------------------------------------------------------------
                   4646: #
                   4647: #-------------------------- Next few routines handles grading by csv upload
                   4648: #
                   4649: #--- Javascript to handle csv upload
1.27      albertel 4650: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4651:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4652:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4653:   &js_escape(\$error1);
                   4654:   &js_escape(\$error2);
1.27      albertel 4655:   return(<<ENDPICK);
                   4656:   function verify(vf) {
                   4657:     var foundsomething=0;
                   4658:     var founduname=0;
1.243     albertel 4659:     var foundID=0;
1.743     raeburn  4660:     var foundclicker=0;
1.27      albertel 4661:     for (i=0;i<=vf.nfields.value;i++) {
                   4662:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4663:       if (i==0 && tw!=0) { foundID=1; }
                   4664:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4665:       if (i==2 && tw!=0) { foundclicker=1; }
                   4666:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4667:     }
1.743     raeburn  4668:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4669: 	alert('$error1');
                   4670: 	return;
1.27      albertel 4671:     }
                   4672:     if (foundsomething==0) {
1.246     albertel 4673: 	alert('$error2');
                   4674: 	return;
1.27      albertel 4675:     }
                   4676:     vf.submit();
                   4677:   }
                   4678:   function flip(vf,tf) {
                   4679:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4680:     var i;
                   4681:     for (i=0;i<=vf.nfields.value;i++) {
                   4682:       //can not pick the same destination field for both name and domain
                   4683:       if (((i ==0)||(i ==1)) && 
                   4684:           ((tf==0)||(tf==1)) && 
                   4685:           (i!=tf) &&
                   4686:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4687:         eval('vf.f'+i+'.selectedIndex=0;')
                   4688:       }
                   4689:     }
                   4690:   }
                   4691: ENDPICK
                   4692: }
                   4693: 
                   4694: sub csvupload_javascript_forward_associate {
1.743     raeburn  4695:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4696:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4697:   &js_escape(\$error1);
                   4698:   &js_escape(\$error2);
1.27      albertel 4699:   return(<<ENDPICK);
                   4700:   function verify(vf) {
                   4701:     var foundsomething=0;
                   4702:     var founduname=0;
1.243     albertel 4703:     var foundID=0;
1.743     raeburn  4704:     var foundclicker=0;
1.27      albertel 4705:     for (i=0;i<=vf.nfields.value;i++) {
                   4706:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4707:       if (tw==1) { foundID=1; }
                   4708:       if (tw==2) { founduname=1; }
1.745     raeburn  4709:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4710:       if (tw>4) { foundsomething=1; }
1.27      albertel 4711:     }
1.743     raeburn  4712:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4713: 	alert('$error1');
                   4714: 	return;
1.27      albertel 4715:     }
                   4716:     if (foundsomething==0) {
1.246     albertel 4717: 	alert('$error2');
                   4718: 	return;
1.27      albertel 4719:     }
                   4720:     vf.submit();
                   4721:   }
                   4722:   function flip(vf,tf) {
                   4723:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4724:     var i;
                   4725:     //can not pick the same destination field twice
                   4726:     for (i=0;i<=vf.nfields.value;i++) {
                   4727:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4728:         eval('vf.f'+i+'.selectedIndex=0;')
                   4729:       }
                   4730:     }
                   4731:   }
                   4732: ENDPICK
                   4733: }
                   4734: 
1.26      albertel 4735: sub csvuploadmap_header {
1.324     albertel 4736:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4737:     my $javascript;
1.257     albertel 4738:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4739: 	$javascript=&csvupload_javascript_reverse_associate();
                   4740:     } else {
                   4741: 	$javascript=&csvupload_javascript_forward_associate();
                   4742:     }
1.45      ng       4743: 
1.418     albertel 4744:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4745:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4746:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4747:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4748:     my $reverse=&mt("Reverse Association");
1.41      ng       4749:     $request->print(<<ENDPICK);
1.632     www      4750: <br />
                   4751: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4752: <input type="hidden" name="associate"  value="" />
                   4753: <input type="hidden" name="phase"      value="three" />
                   4754: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4755: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4756: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4757: <input type="hidden" name="upfile_associate" 
1.257     albertel 4758:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4759: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4760: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4761: <hr />
                   4762: ENDPICK
1.597     wenzelju 4763:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4764:     return '';
1.26      albertel 4765: 
                   4766: }
                   4767: 
                   4768: sub csvupload_fields {
1.582     raeburn  4769:     my ($symb,$errorref) = @_;
1.745     raeburn  4770:     my $toolsymb;
                   4771:     if ($symb =~ /ext\.tool$/) {
                   4772:         $toolsymb = $symb;
                   4773:     }
1.582     raeburn  4774:     my (@parts) = &getpartlist($symb,$errorref);
                   4775:     if (ref($errorref)) {
                   4776:         if ($$errorref) {
                   4777:             return;
                   4778:         }
                   4779:     }
                   4780: 
1.556     weissno  4781:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4782: 		['username','Student Username'],
1.743     raeburn  4783: 		['clicker','Clicker ID'],
1.243     albertel 4784: 		['domain','Student Domain']);
1.324     albertel 4785:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4786:     foreach my $part (sort(@parts)) {
                   4787: 	my @datum;
1.745     raeburn  4788: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4789: 	my $name=$part;
1.745     raeburn  4790: 	if (!$display) { $display = $name; }
1.41      ng       4791: 	@datum=($name,$display);
1.244     albertel 4792: 	if ($name=~/^stores_(.*)_awarded/) {
                   4793: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4794: 	}
1.41      ng       4795: 	push(@fields,\@datum);
                   4796:     }
                   4797:     return (@fields);
1.26      albertel 4798: }
                   4799: 
                   4800: sub csvuploadmap_footer {
1.41      ng       4801:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4802:     my $buttontext = &mt('Assign Grades');
1.41      ng       4803:     $request->print(<<ENDPICK);
1.26      albertel 4804: </table>
                   4805: <input type="hidden" name="nfields" value="$i" />
                   4806: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4807: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4808: </form>
                   4809: ENDPICK
                   4810: }
                   4811: 
1.283     albertel 4812: sub checkforfile_js {
1.638     www      4813:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4814:     &js_escape(\$alertmsg);
1.597     wenzelju 4815:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4816:     function checkUpload(formname) {
                   4817: 	if (formname.upfile.value == "") {
1.539     riegler  4818: 	    alert("$alertmsg");
1.86      ng       4819: 	    return false;
                   4820: 	}
                   4821: 	formname.submit();
                   4822:     }
                   4823: CSVFORMJS
1.283     albertel 4824:     return $result;
                   4825: }
                   4826: 
                   4827: sub upcsvScores_form {
1.608     www      4828:     my ($request,$symb) = @_;
1.283     albertel 4829:     if (!$symb) {return '';}
                   4830:     my $result=&checkforfile_js();
1.632     www      4831:     $result.=&Apache::loncommon::start_data_table().
                   4832:              &Apache::loncommon::start_data_table_header_row().
                   4833:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4834:              &Apache::loncommon::end_data_table_header_row().
                   4835:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4836:     my $upload=&mt("Upload Scores");
1.86      ng       4837:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4838:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4839:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4840:     $result.=<<ENDUPFORM;
1.106     albertel 4841: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4842: <input type="hidden" name="symb" value="$symb" />
                   4843: <input type="hidden" name="command" value="csvuploadmap" />
                   4844: $upfile_select
1.589     bisitz   4845: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4846: </form>
                   4847: ENDUPFORM
1.370     www      4848:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4849:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4850:              '</td>'.
                   4851:             &Apache::loncommon::end_data_table_row().
                   4852:             &Apache::loncommon::end_data_table();
1.86      ng       4853:     return $result;
                   4854: }
                   4855: 
                   4856: 
1.26      albertel 4857: sub csvuploadmap {
1.768     raeburn  4858:     my ($request,$symb) = @_;
1.41      ng       4859:     if (!$symb) {return '';}
1.72      ng       4860: 
1.41      ng       4861:     my $datatoken;
1.257     albertel 4862:     if (!$env{'form.datatoken'}) {
1.41      ng       4863: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4864:     } else {
1.742     raeburn  4865: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4866:         if ($datatoken ne '') {
                   4867: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4868:         }
1.26      albertel 4869:     }
1.41      ng       4870:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4871:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4872:     my ($i,$keyfields);
                   4873:     if (@records) {
1.582     raeburn  4874:         my $fieldserror;
                   4875: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4876:         if ($fieldserror) {
                   4877:             $request->print(&navmap_errormsg());
                   4878:             return;
                   4879:         }
1.257     albertel 4880: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4881: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4882: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4883: 							  \@fields);
                   4884: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4885: 	    chop($keyfields);
                   4886: 	} else {
                   4887: 	    unshift(@fields,['none','']);
                   4888: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4889: 							    \@fields);
1.311     banghart 4890:             foreach my $rec (@records) {
                   4891:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4892:                 if (%temp) {
                   4893:                     $keyfields=join(',',sort(keys(%temp)));
                   4894:                     last;
                   4895:                 }
                   4896:             }
1.41      ng       4897: 	}
                   4898:     }
                   4899:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4900: 
1.41      ng       4901:     return '';
1.27      albertel 4902: }
                   4903: 
1.246     albertel 4904: sub csvuploadoptions {
1.608     www      4905:     my ($request,$symb)= @_;
1.632     www      4906:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4907:     $request->print(<<ENDPICK);
                   4908: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4909: <input type="hidden" name="command"    value="csvuploadassign" />
                   4910: <p>
                   4911: <label>
                   4912:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4913:    $overwrite
1.246     albertel 4914: </label>
                   4915: </p>
                   4916: ENDPICK
                   4917:     my %fields=&get_fields();
                   4918:     if (!defined($fields{'domain'})) {
1.257     albertel 4919: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4920: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4921:     }
1.257     albertel 4922:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4923: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4924: 	my $cleankey=$1;
                   4925: 	if ($cleankey eq 'command') { next; }
                   4926: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4927: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4928:     }
                   4929:     # FIXME do a check for any duplicated user ids...
                   4930:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4931:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4932: <hr /></form>'."\n");
1.246     albertel 4933:     return '';
                   4934: }
                   4935: 
                   4936: sub get_fields {
                   4937:     my %fields;
1.257     albertel 4938:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4939:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4940: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4941: 	    if ($env{'form.f'.$i} ne 'none') {
                   4942: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4943: 	    }
                   4944: 	} else {
1.257     albertel 4945: 	    if ($env{'form.f'.$i} ne 'none') {
                   4946: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4947: 	    }
                   4948: 	}
1.27      albertel 4949:     }
1.246     albertel 4950:     return %fields;
                   4951: }
                   4952: 
                   4953: sub csvuploadassign {
1.766     raeburn  4954:     my ($request,$symb) = @_;
1.246     albertel 4955:     if (!$symb) {return '';}
1.345     bowersj2 4956:     my $error_msg = '';
1.742     raeburn  4957:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4958:     if ($datatoken ne '') { 
                   4959:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4960:     }
1.246     albertel 4961:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4962:     my %fields=&get_fields();
1.257     albertel 4963:     my $courseid=$env{'request.course.id'};
1.97      albertel 4964:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4965:     my @notallowed;
1.41      ng       4966:     my @skipped;
1.657     raeburn  4967:     my @warnings;
1.41      ng       4968:     my $countdone=0;
                   4969:     foreach my $grade (@gradedata) {
                   4970: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4971: 	my $domain;
                   4972: 	if ($entries{$fields{'domain'}}) {
                   4973: 	    $domain=$entries{$fields{'domain'}};
                   4974: 	} else {
1.257     albertel 4975: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4976: 	}
1.243     albertel 4977: 	$domain=~s/\s//g;
1.41      ng       4978: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4979: 	$username=~s/\s//g;
1.243     albertel 4980: 	if (!$username) {
                   4981: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4982: 	    $id=~s/\s//g;
1.737     raeburn  4983:             if ($id ne '') {
                   4984: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4985: 	        $username=$ids{$id};
                   4986:             } else {
                   4987:                 if ($entries{$fields{'clicker'}}) {
                   4988:                     my $clicker = $entries{$fields{'clicker'}};
                   4989:                     $clicker=~s/\s//g;
                   4990:                     if ($clicker ne '') {
                   4991:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4992:                         if ($clickers{$clicker} ne '') {  
                   4993:                             my $match = 0;
                   4994:                             my @inclass;
                   4995:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4996:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4997:                                     $username = $poss;
                   4998:                                     push(@inclass,$poss);
                   4999:                                     $match ++;
                   5000:                                     
                   5001:                                 }
                   5002:                             }
                   5003:                             if ($match > 1) {
                   5004:                                 undef($username); 
                   5005:                                 $request->print('<p class="LC_warning">'.
                   5006:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   5007:                                                 $clicker,join(', ',@inclass)).'</p>');
                   5008:                             }
                   5009:                         }
                   5010:                     }
                   5011:                 }
                   5012:             }
1.243     albertel 5013: 	}
1.41      ng       5014: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 5015: 	    my $id=$entries{$fields{'ID'}};
                   5016: 	    $id=~s/\s//g;
1.737     raeburn  5017:             my $clicker = $entries{$fields{'clicker'}};
                   5018:             $clicker=~s/\s//g;
                   5019:             if ($clicker) {
                   5020:                 push(@skipped,"$clicker:$domain");
                   5021: 	    } elsif ($id) {
1.247     albertel 5022: 		push(@skipped,"$id:$domain");
                   5023: 	    } else {
                   5024: 		push(@skipped,"$username:$domain");
                   5025: 	    }
1.41      ng       5026: 	    next;
                   5027: 	}
1.108     albertel 5028: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 5029: 	if (!&canmodify($usec)) {
                   5030: 	    push(@notallowed,"$username:$domain");
                   5031: 	    next;
                   5032: 	}
1.244     albertel 5033: 	my %points;
1.41      ng       5034: 	my %grades;
                   5035: 	foreach my $dest (keys(%fields)) {
1.244     albertel 5036: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   5037: 		$dest eq 'domain') { next; }
                   5038: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   5039: 	    if ($dest=~/stores_(.*)_points/) {
                   5040: 		my $part=$1;
                   5041: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   5042: 					      $symb,$domain,$username);
1.345     bowersj2 5043:                 if ($wgt) {
                   5044:                     $entries{$fields{$dest}}=~s/\s//g;
                   5045:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5046:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5047:                                           : 'correct_by_override';
1.638     www      5048:                     if ($pcr>1) {
1.657     raeburn  5049:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      5050:                     }
1.345     bowersj2 5051:                     $grades{"resource.$part.awarded"}=$pcr;
                   5052:                     $grades{"resource.$part.solved"}=$award;
                   5053:                     $points{$part}=1;
                   5054:                 } else {
                   5055:                     $error_msg = "<br />" .
                   5056:                         &mt("Some point values were assigned"
                   5057:                             ." for problems with a weight "
                   5058:                             ."of zero. These values were "
                   5059:                             ."ignored.");
                   5060:                 }
1.244     albertel 5061: 	    } else {
                   5062: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5063: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5064: 		my $store_key=$dest;
                   5065: 		$store_key=~s/^stores/resource/;
                   5066: 		$store_key=~s/_/\./g;
                   5067: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5068: 	    }
1.41      ng       5069: 	}
1.766     raeburn  5070: 	if (! %grades) {
1.508     www      5071:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5072:         } else {
                   5073: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5074: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5075: 					   $env{'request.course.id'},
                   5076: 					   $domain,$username);
1.508     www      5077: 	   if ($result eq 'ok') {
1.627     www      5078: # Successfully stored
1.508     www      5079: 	      $request->print('.');
1.627     www      5080: # Remove from grading queue
                   5081:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5082:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5083:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5084:                                              $domain,$username);
                   5085:               $countdone++;
                   5086:            } else {
1.508     www      5087: 	      $request->print("<p><span class=\"LC_error\">".
                   5088:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5089:                                   "$username:$domain",$result)."</span></p>");
                   5090: 	   }
                   5091: 	   $request->rflush();
                   5092:         }
1.41      ng       5093:     }
1.570     www      5094:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  5095:     if (@warnings) {
                   5096:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5097:         $request->print(join(', ',@warnings));
                   5098:     }
1.41      ng       5099:     if (@skipped) {
1.571     www      5100: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5101:         $request->print(join(', ',@skipped));
1.106     albertel 5102:     }
                   5103:     if (@notallowed) {
1.571     www      5104: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5105: 	$request->print(join(', ',@notallowed));
1.41      ng       5106:     }
1.106     albertel 5107:     $request->print("<br />\n");
1.345     bowersj2 5108:     return $error_msg;
1.26      albertel 5109: }
1.44      ng       5110: #------------- end of section for handling csv file upload ---------
                   5111: #
                   5112: #-------------------------------------------------------------------
                   5113: #
1.122     ng       5114: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5115: #
                   5116: #--- Select a page/sequence and a student to grade
1.68      ng       5117: sub pickStudentPage {
1.608     www      5118:     my ($request,$symb) = @_;
1.68      ng       5119: 
1.539     riegler  5120:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  5121:     &js_escape(\$alertmsg);
1.597     wenzelju 5122:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5123: 
                   5124: function checkPickOne(formname) {
1.76      ng       5125:     if (radioSelection(formname.student) == null) {
1.539     riegler  5126: 	alert("$alertmsg");
1.68      ng       5127: 	return;
                   5128:     }
1.125     ng       5129:     ptr = pullDownSelection(formname.selectpage);
                   5130:     formname.page.value = formname["page"+ptr].value;
                   5131:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5132:     formname.submit();
                   5133: }
                   5134: 
                   5135: LISTJAVASCRIPT
1.118     ng       5136:     &commonJSfunctions($request);
1.608     www      5137: 
1.257     albertel 5138:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5139:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5140:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  5141:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5142: 
1.398     albertel 5143:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5144: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5145: 
1.80      ng       5146:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5147:     my $map_error;
                   5148:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5149:     if ($map_error) {
                   5150:         $request->print(&navmap_errormsg());
                   5151:         return; 
                   5152:     }
1.137     albertel 5153:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5154: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5155: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   5156: 
                   5157:     # Collection of hidden fields
1.70      ng       5158:     my $ctr=0;
1.68      ng       5159:     foreach (@$titles) {
1.700     bisitz   5160:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5161:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5162:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5163:         $ctr++;
1.68      ng       5164:     }
1.700     bisitz   5165:     $result.='<input type="hidden" name="page" />'."\n".
                   5166:         '<input type="hidden" name="title" />'."\n";
                   5167: 
                   5168:     $result.=&build_section_inputs();
                   5169:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5170:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   5171: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   5172: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 5173: 
1.700     bisitz   5174:     # Show grading options
                   5175:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5176:     my $select = '<select name="selectpage">'."\n";
1.70      ng       5177:     $ctr=0;
                   5178:     foreach (@$titles) {
                   5179: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   5180: 	$select.='<option value="'.$ctr.'"'.
                   5181: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5182: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       5183: 	$ctr++;
                   5184:     }
1.700     bisitz   5185:     $select.= '</select>';
1.68      ng       5186: 
1.700     bisitz   5187:     $result.=
                   5188:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5189:        .$select
                   5190:        .&Apache::lonhtmlcommon::row_closure();
                   5191: 
                   5192:     $result.=
                   5193:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5194:        .'<label><input type="radio" name="vProb" value="no"'
                   5195:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5196:        .'<label><input type="radio" name="vProb" value="yes" />'
                   5197:            .&mt('yes').'</label>'."\n"
                   5198:        .&Apache::lonhtmlcommon::row_closure();
                   5199: 
                   5200:     $result.=
                   5201:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5202:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5203:            .&mt('none').' </label>'."\n"
                   5204:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5205:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5206:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5207:            .&mt('all submissions with details').' </label>'
                   5208:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 5209:     
1.700     bisitz   5210:     $result.=
                   5211:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5212:        .'<input type="text" name="CODE" value="" />'
                   5213:        .&Apache::lonhtmlcommon::row_closure(1)
                   5214:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5215: 
1.700     bisitz   5216:     # Show list of students to select for grading
                   5217:     $result.='<br /><input type="button" '.
1.589     bisitz   5218:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5219: 
1.68      ng       5220:     $request->print($result);
                   5221: 
1.485     albertel 5222:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5223: 	&Apache::loncommon::start_data_table().
                   5224: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5225: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5226: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5227: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5228: 	'<th>'.&nameUserString('header').'</th>'.
                   5229: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5230:  
1.761     raeburn  5231:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5232:     my $ptr = 1;
1.294     albertel 5233:     foreach my $student (sort 
                   5234: 			 {
                   5235: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5236: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5237: 			     }
                   5238: 			     return $a cmp $b;
                   5239: 			 } (keys(%$fullname))) {
1.68      ng       5240: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5241: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5242:                                   : '</td>');
1.126     ng       5243: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5244: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5245: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5246: 	$studentTable.=
                   5247: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5248:                          : '');
1.68      ng       5249: 	$ptr++;
                   5250:     }
1.484     albertel 5251:     if ($ptr%2 == 0) {
                   5252: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5253: 	    &Apache::loncommon::end_data_table_row();
                   5254:     }
                   5255:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5256:     $studentTable.='<input type="button" '.
1.589     bisitz   5257:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5258: 
                   5259:     $request->print($studentTable);
                   5260: 
                   5261:     return '';
                   5262: }
                   5263: 
                   5264: sub getSymbMap {
1.582     raeburn  5265:     my ($map_error) = @_;
1.132     bowersj2 5266:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5267:     unless (ref($navmap)) {
                   5268:         if (ref($map_error)) {
                   5269:             $$map_error = 'navmap';
                   5270:         }
                   5271:         return;
                   5272:     }
1.68      ng       5273:     my %symbx = ();
                   5274:     my @titles = ();
1.117     bowersj2 5275:     my $minder = 0;
                   5276: 
                   5277:     # Gather every sequence that has problems.
1.240     albertel 5278:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5279: 					       1,0,1);
1.117     bowersj2 5280:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5281: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5282: 	    my $title = $minder.'.'.
                   5283: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5284: 	    push(@titles, $title); # minder in case two titles are identical
                   5285: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5286: 	    $minder++;
1.241     albertel 5287: 	}
1.68      ng       5288:     }
                   5289:     return \@titles,\%symbx;
                   5290: }
                   5291: 
1.72      ng       5292: #
                   5293: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5294: sub displayPage {
1.608     www      5295:     my ($request,$symb) = @_;
1.257     albertel 5296:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5297:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5298:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5299:     my $pageTitle = $env{'form.page'};
1.103     albertel 5300:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5301:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5302:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5303: 
                   5304:     #need to make sure we have the correct data for later EXT calls, 
                   5305:     #thus invalidate the cache
                   5306:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5307:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5308:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5309:     &Apache::lonnet::clear_EXT_cache_status();
                   5310: 
1.103     albertel 5311:     if (!&canview($usec)) {
1.712     bisitz   5312:         $request->print(
                   5313:             '<span class="LC_warning">'.
                   5314:             &mt('Unable to view requested student. ([_1])',
                   5315:                     $env{'form.student'}).
                   5316:             '</span>');
                   5317:         return;
1.103     albertel 5318:     }
1.398     albertel 5319:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5320:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5321: 	'</h3>'."\n";
1.500     albertel 5322:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5323:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5324: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5325:     } else {
                   5326: 	delete($env{'form.CODE'});
                   5327:     }
1.71      ng       5328:     &sub_page_js($request);
                   5329:     $request->print($result);
                   5330: 
1.132     bowersj2 5331:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5332:     unless (ref($navmap)) {
                   5333:         $request->print(&navmap_errormsg());
                   5334:         return;
                   5335:     }
1.257     albertel 5336:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5337:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5338:     if (!$map) {
1.485     albertel 5339: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5340: 	return; 
                   5341:     }
1.68      ng       5342:     my $iterator = $navmap->getIterator($map->map_start(),
                   5343: 					$map->map_finish());
                   5344: 
1.71      ng       5345:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5346: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5347: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5348: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5349: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5350: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5351: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5352: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5353: 
1.382     albertel 5354:     if (defined($env{'form.CODE'})) {
                   5355: 	$studentTable.=
                   5356: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5357:     }
1.381     albertel 5358:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5359: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5360: 
1.594     bisitz   5361:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5362:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5363:         '</span>'."\n".
1.484     albertel 5364: 	&Apache::loncommon::start_data_table().
                   5365: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5366: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5367: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5368: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5369: 
1.329     albertel 5370:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5371:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5372:     $iterator->next(); # skip the first BEGIN_MAP
                   5373:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5374:     while ($depth > 0) {
1.68      ng       5375:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5376:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5377: 
1.745     raeburn  5378:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5379: 	    my $parts = $curRes->parts();
1.68      ng       5380:             my $title = $curRes->compTitle();
1.71      ng       5381: 	    my $symbx = $curRes->symb();
1.746     raeburn  5382:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5383: 	    $studentTable.=
                   5384: 		&Apache::loncommon::start_data_table_row().
                   5385: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5386: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5387: 		                        : '<br />('.&mt('[_1]parts',
                   5388: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5389: 		 ).
                   5390: 		 '</td>';
1.71      ng       5391: 	    $studentTable.='<td valign="top">';
1.382     albertel 5392: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5393:             if ($is_tool) {
                   5394:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5395:             } else {
1.745     raeburn  5396: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5397: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5398: 					         undef,'both',\%form);
                   5399: 	        } else {
                   5400: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5401: 		    $companswer =~ s|<form(.*?)>||g;
                   5402: 		    $companswer =~ s|</form>||g;
                   5403: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5404: #		        $companswer =~ s/$1/ /ms;
                   5405: #		        $request->print('match='.$1."<br />\n");
                   5406: #		    }
                   5407: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5408: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5409: 		}
1.71      ng       5410: 	    }
                   5411: 
1.257     albertel 5412: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5413: 
1.257     albertel 5414: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5415: 		if ($record{'version'} eq '') {
1.745     raeburn  5416:                     my $msg = &mt('No recorded submission for this problem.');
                   5417:                     if ($is_tool) {
                   5418:                         $msg = &mt('No recorded transactions for this external tool');
                   5419:                     }
                   5420: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5421: 		} else {
1.116     ng       5422: 		    my %responseType = ();
                   5423: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5424: 			my @responseIds =$curRes->responseIds($partid);
                   5425: 			my @responseType =$curRes->responseType($partid);
                   5426: 			my %responseIds;
                   5427: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5428: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5429: 			}
                   5430: 			$responseType{$partid} = \%responseIds;
1.116     ng       5431: 		    }
1.148     albertel 5432: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5433: 		}
1.257     albertel 5434: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5435: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5436:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5437: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5438: 									$env{'request.course.id'},
1.726     raeburn  5439: 									'','.submission',undef,
                   5440:                                                                         $usec,$identifier);
1.71      ng       5441:  
                   5442: 	    }
1.103     albertel 5443: 	    if (&canmodify($usec)) {
1.585     bisitz   5444:             $studentTable.=&gradeBox_start();
1.103     albertel 5445: 		foreach my $partid (@{$parts}) {
                   5446: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5447: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5448: 		    $question++;
                   5449: 		}
1.585     bisitz   5450:             $studentTable.=&gradeBox_end();
1.196     albertel 5451: 		$prob++;
1.71      ng       5452: 	    }
                   5453: 	    $studentTable.='</td></tr>';
1.68      ng       5454: 
1.103     albertel 5455: 	}
1.68      ng       5456:         $curRes = $iterator->next();
                   5457:     }
1.780     raeburn  5458:     my $disabled;
                   5459:     unless (&canmodify($usec)) {
                   5460:         $disabled = ' disabled="disabled"';
                   5461:     }
1.68      ng       5462: 
1.589     bisitz   5463:     $studentTable.=
                   5464:         '</table>'."\n".
1.780     raeburn  5465:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5466:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5467:         '</form>'."\n";
1.71      ng       5468:     $request->print($studentTable);
                   5469: 
                   5470:     return '';
1.119     ng       5471: }
                   5472: 
                   5473: sub displaySubByDates {
1.148     albertel 5474:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5475:     my $isCODE=0;
1.335     albertel 5476:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5477:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5478:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5479:     my $studentTable=&Apache::loncommon::start_data_table().
                   5480: 	&Apache::loncommon::start_data_table_header_row().
                   5481: 	'<th>'.&mt('Date/Time').'</th>'.
                   5482: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5483:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5484: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5485: 	'<th>'.&mt('Status').'</th>'.
                   5486: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5487:     my ($version);
                   5488:     my %mark;
1.148     albertel 5489:     my %orders;
1.119     ng       5490:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5491:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5492:         if ($is_tool) {
                   5493:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5494:         } else {
                   5495:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5496:         }
1.147     albertel 5497:     }
1.335     albertel 5498: 
                   5499:     my $interaction;
1.525     raeburn  5500:     my $no_increment = 1;
1.735     raeburn  5501:     my (%lastrndseed,%lasttype);
1.119     ng       5502:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5503: 	my $timestamp = 
                   5504: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5505: 	if (exists($$record{$version.':resource.0.version'})) {
                   5506: 	    $interaction = $$record{$version.':resource.0.version'};
                   5507: 	}
1.671     raeburn  5508:         if ($isTask && $env{'form.previousversion'}) {
                   5509:             next unless ($interaction == $env{'form.previousversion'});
                   5510:         }
1.335     albertel 5511: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5512: 		             : "$version:resource");
1.467     albertel 5513: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5514: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5515: 	if ($isCODE) {
                   5516: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5517: 	}
1.671     raeburn  5518:         if ($isTask) {
                   5519:             $studentTable.='<td>'.$interaction.'</td>';
                   5520:         }
1.119     ng       5521: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5522: 	my @displaySub = ();
                   5523: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5524:             my ($hidden,$type);
                   5525:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5526:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5527:                 $hidden = 1;
                   5528:             }
1.749     raeburn  5529:             my @matchKey;
                   5530:             if ($isTask) {
1.769     raeburn  5531:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  5532:             } elsif ($is_tool) {
1.769     raeburn  5533:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  5534:             } else {
1.769     raeburn  5535:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  5536:             }
1.122     ng       5537: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5538: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5539: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5540: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5541: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5542:                     if ($is_tool) {
                   5543:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5544:                     } else {
1.749     raeburn  5545: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5546: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5547:                         $displaySub[0].='<span class="LC_nobreak">';
                   5548:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5549:                                        .' <span class="LC_internal_info">'
                   5550:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5551:                                        .'</span>'
                   5552:                                        .' <b>';
                   5553:                         if ($hidden) {
                   5554:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5555:                         } else {
                   5556:                             my ($trial,$rndseed,$newvariation);
                   5557:                             if ($type eq 'randomizetry') {
                   5558:                                 $trial = $$record{"$where.$partid.tries"};
                   5559:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5560:                             }
                   5561: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5562: 			        $displaySub[0].=&mt('Trial not counted');
                   5563: 		            } else {
                   5564: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5565: 					        $$record{"$where.$partid.tries"});
                   5566:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5567:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5568:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5569:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5570:                                     }
1.640     raeburn  5571:                                 }
1.749     raeburn  5572:                                 $lastrndseed{$partid} = $rndseed;
                   5573:                                 $lasttype{$partid} = $type;
                   5574: 		            }
                   5575: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5576:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5577: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5578: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5579: 			        $orders{$partid}->{$responseId}=
                   5580: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5581:                                                $no_increment,$type,$trial,$rndseed);
                   5582: 		            }
                   5583: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5584: 		            $displaySub[0].='&nbsp; '.
                   5585: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5586:                         }
1.596     raeburn  5587:                     }
1.147     albertel 5588: 		}
                   5589: 	    }
1.335     albertel 5590: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5591: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5592: 				    $$record{"$where.$partid.checkedin"},
                   5593: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5594: 					'<br />';
1.335     albertel 5595: 	    }
                   5596: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5597: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5598: 		    lc($$record{"$where.$partid.award"}).' '.
                   5599: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5600: 		    '<br />';
1.749     raeburn  5601: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5602: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5603: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5604: 		}
1.147     albertel 5605: 	    }
1.335     albertel 5606: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5607: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5608: 		unless ($is_tool) {
                   5609: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5610: 		}
1.335     albertel 5611: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5612: 		$displaySub[2].=
1.749     raeburn  5613: 		    $$record{"$version:resource.$partid.regrader"};
                   5614:                 unless ($is_tool) {
                   5615: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5616:                 }
1.147     albertel 5617: 	    }
                   5618: 	}
                   5619: 	# needed because old essay regrader has not parts info
                   5620: 	if (exists $$record{"$version:resource.regrader"}) {
                   5621: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5622: 	}
                   5623: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5624: 	if ($displaySub[2]) {
1.467     albertel 5625: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5626: 	}
1.467     albertel 5627: 	$studentTable.='&nbsp;</td>'.
                   5628: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5629:     }
1.467     albertel 5630:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5631:     return $studentTable;
1.71      ng       5632: }
                   5633: 
                   5634: sub updateGradeByPage {
1.608     www      5635:     my ($request,$symb) = @_;
1.71      ng       5636: 
1.257     albertel 5637:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5638:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5639:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5640:     my $pageTitle = $env{'form.page'};
1.103     albertel 5641:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5642:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5643:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5644:     if (!&canmodify($usec)) {
1.526     raeburn  5645: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5646: 	return;
                   5647:     }
1.398     albertel 5648:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5649:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5650: 	'</h3>'."\n";
1.70      ng       5651: 
1.68      ng       5652:     $request->print($result);
                   5653: 
1.582     raeburn  5654: 
1.132     bowersj2 5655:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5656:     unless (ref($navmap)) {
                   5657:         $request->print(&navmap_errormsg());
                   5658:         return;
                   5659:     }
1.257     albertel 5660:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5661:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5662:     if (!$map) {
1.527     raeburn  5663: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5664: 	return; 
                   5665:     }
1.71      ng       5666:     my $iterator = $navmap->getIterator($map->map_start(),
                   5667: 					$map->map_finish());
1.70      ng       5668: 
1.484     albertel 5669:     my $studentTable=
                   5670: 	&Apache::loncommon::start_data_table().
                   5671: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5672: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5673: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5674: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5675: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5676: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5677: 
                   5678:     $iterator->next(); # skip the first BEGIN_MAP
                   5679:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5680:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5681:     while ($depth > 0) {
1.71      ng       5682:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5683:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5684: 
1.385     albertel 5685:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5686: 	    my $parts = $curRes->parts();
1.71      ng       5687:             my $title = $curRes->compTitle();
                   5688: 	    my $symbx = $curRes->symb();
1.484     albertel 5689: 	    $studentTable.=
                   5690: 		&Apache::loncommon::start_data_table_row().
                   5691: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5692: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5693:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5694: 		.')').'</td>';
1.71      ng       5695: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5696: 
                   5697: 	    my %newrecord=();
                   5698: 	    my @displayPts=();
1.269     raeburn  5699:             my %aggregate = ();
                   5700:             my $aggregateflag = 0;
1.726     raeburn  5701:             if ($env{'form.HIDE'.$prob}) {
                   5702:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5703:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5704:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5705:                 $hideflag += $numchgs;
                   5706:             }
1.71      ng       5707: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5708: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5709: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5710: 
1.257     albertel 5711: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5712: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5713: 		my $partial = $newpts/$wgt;
                   5714: 		my $score;
                   5715: 		if ($partial > 0) {
                   5716: 		    $score = 'correct_by_override';
1.125     ng       5717: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5718: 		    $score = 'incorrect_by_override';
                   5719: 		}
1.257     albertel 5720: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5721: 		if ($dropMenu eq 'excused') {
1.71      ng       5722: 		    $partial = '';
                   5723: 		    $score = 'excused';
1.125     ng       5724: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5725: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5726: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5727: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5728: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5729: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5730: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5731: 		    $changeflag++;
                   5732: 		    $newpts = '';
1.269     raeburn  5733:                     
                   5734:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5735:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5736:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5737:                     if ($aggtries > 0) {
                   5738:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5739:                         $aggregateflag = 1;
                   5740:                     }
1.71      ng       5741: 		}
1.324     albertel 5742: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5743: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5744: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5745: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5746: 		    '&nbsp;<br />';
1.526     raeburn  5747: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5748: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5749: 		    '&nbsp;<br />';
1.71      ng       5750: 		$question++;
1.380     albertel 5751: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5752: 
1.71      ng       5753: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5754: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5755: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5756: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5757: 
                   5758: 		$changeflag++;
                   5759: 	    }
                   5760: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5761: 		my %record = 
                   5762: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5763: 					     $udom,$uname);
                   5764: 
                   5765: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5766: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5767: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5768: 		    $newrecord{'resource.CODE'} = '';
                   5769: 		}
1.257     albertel 5770: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5771: 					$udom,$uname);
1.382     albertel 5772: 		%record = &Apache::lonnet::restore($symbx,
                   5773: 						   $env{'request.course.id'},
                   5774: 						   $udom,$uname);
1.380     albertel 5775: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5776: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5777: 	    }
1.380     albertel 5778: 	    
1.269     raeburn  5779:             if ($aggregateflag) {
                   5780:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5781:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5782:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5783:             }
1.125     ng       5784: 
1.71      ng       5785: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5786: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5787: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5788: 
1.196     albertel 5789: 	    $prob++;
1.68      ng       5790: 	}
1.71      ng       5791:         $curRes = $iterator->next();
1.68      ng       5792:     }
1.98      albertel 5793: 
1.484     albertel 5794:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5795:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5796: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5797: 		  $changeflag).'<br />');
                   5798:     my $hidemsg=($hideflag == 0 ? '' :
                   5799:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5800:                      $hideflag).'<br />');
                   5801:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5802: 
1.70      ng       5803:     return '';
                   5804: }
                   5805: 
1.72      ng       5806: #-------- end of section for handling grading by page/sequence ---------
                   5807: #
                   5808: #-------------------------------------------------------------------
                   5809: 
1.581     www      5810: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5811: #
                   5812: #------ start of section for handling grading by page/sequence ---------
                   5813: 
1.423     albertel 5814: =pod
                   5815: 
                   5816: =head1 Bubble sheet grading routines
                   5817: 
1.424     albertel 5818:   For this documentation:
                   5819: 
                   5820:    'scanline' refers to the full line of characters
                   5821:    from the file that we are parsing that represents one entire sheet
                   5822: 
                   5823:    'bubble line' refers to the data
1.659     raeburn  5824:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5825: 
                   5826: 
1.659     raeburn  5827: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5828: into a course. When a user wants to grade, they select a
1.659     raeburn  5829: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5830: one of the predefined configurations for what each scanline looks
                   5831: like.
                   5832: 
                   5833: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5834: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5835: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5836: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5837: invalid student/employee ID
1.424     albertel 5838: 
                   5839: If the CODE option is used that determines the randomization of the
1.556     weissno  5840: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5841: username:domain.
                   5842: 
                   5843: During the validation phase the instructor can choose to skip scanlines. 
                   5844: 
1.659     raeburn  5845: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5846: 
                   5847:   scantron_original_filename (unmodified original file)
                   5848:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5849:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5850: 
                   5851: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5852: correction information that isn't representable in the bubblesheet
1.424     albertel 5853: file (see &scantron_getfile() for more information)
                   5854: 
                   5855: After all scanlines are either valid, marked as valid or skipped, then
                   5856: foreach line foreach problem in the picked sequence, an ssi request is
                   5857: made that simulates a user submitting their selected letter(s) against
                   5858: the homework problem.
1.423     albertel 5859: 
                   5860: =over 4
                   5861: 
                   5862: 
                   5863: 
                   5864: =item defaultFormData
                   5865: 
                   5866:   Returns html hidden inputs used to hold context/default values.
                   5867: 
                   5868:  Arguments:
                   5869:   $symb - $symb of the current resource 
                   5870: 
                   5871: =cut
1.422     foxr     5872: 
1.81      albertel 5873: sub defaultFormData {
1.324     albertel 5874:     my ($symb)=@_;
1.766     raeburn  5875:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5876: }
                   5877: 
1.447     foxr     5878: 
1.423     albertel 5879: =pod 
                   5880: 
                   5881: =item getSequenceDropDown
                   5882: 
                   5883:    Return html dropdown of possible sequences to grade
                   5884:  
                   5885:  Arguments:
1.582     raeburn  5886:    $symb - $symb of the current resource
                   5887:    $map_error - ref to scalar which will container error if
                   5888:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5889: 
                   5890: =cut
1.422     foxr     5891: 
1.75      albertel 5892: sub getSequenceDropDown {
1.582     raeburn  5893:     my ($symb,$map_error)=@_;
1.75      albertel 5894:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5895:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5896:     if (ref($map_error)) {
                   5897:         return if ($$map_error);
                   5898:     }
1.137     albertel 5899:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5900:     my $ctr=0;
                   5901:     foreach (@$titles) {
                   5902: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5903: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5904: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5905: 	    '>'.$showtitle.'</option>'."\n";
                   5906: 	$ctr++;
                   5907:     }
                   5908:     $result.= '</select>';
                   5909:     return $result;
                   5910: }
                   5911: 
1.495     albertel 5912: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5913:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5914: 
                   5915: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5916: 
1.509     raeburn  5917: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5918:                                    # matchresponse or rankresponse, where 
                   5919:                                    # an individual response can have multiple 
                   5920:                                    # lines
1.503     raeburn  5921: 
                   5922: my %responsetype_per_response;     # responsetype for each response
                   5923: 
1.691     raeburn  5924: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5925:                                    # numbered response. Needed when randomorder
                   5926:                                    # or randompick are in use. Key is ID, value 
                   5927:                                    # is response number.
                   5928: 
1.495     albertel 5929: # Save and restore the bubble lines array to the form env.
                   5930: 
                   5931: 
                   5932: sub save_bubble_lines {
                   5933:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5934: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5935: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5936: 	    $first_bubble_line{$line};
1.503     raeburn  5937:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5938:             $subdivided_bubble_lines{$line};
                   5939:         $env{"form.scantron.responsetype.$line"} =
                   5940:             $responsetype_per_response{$line};
1.495     albertel 5941:     }
1.691     raeburn  5942:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5943:         my $line = $masterseq_id_responsenum{$resid};
                   5944:         $env{"form.scantron.residpart.$line"} = $resid;
                   5945:     }
1.495     albertel 5946: }
                   5947: 
                   5948: 
                   5949: sub restore_bubble_lines {
                   5950:     my $line = 0;
                   5951:     %bubble_lines_per_response = ();
1.691     raeburn  5952:     %masterseq_id_responsenum = ();
1.495     albertel 5953:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5954: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5955: 	$bubble_lines_per_response{$line} = $value;
                   5956: 	$first_bubble_line{$line}  =
                   5957: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5958:         $subdivided_bubble_lines{$line} =
                   5959:             $env{"form.scantron.sub_bubblelines.$line"};
                   5960:         $responsetype_per_response{$line} =
                   5961:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5962:         my $id = $env{"form.scantron.residpart.$line"};
                   5963:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5964: 	$line++;
                   5965:     }
                   5966: }
                   5967: 
1.423     albertel 5968: =pod 
                   5969: 
                   5970: =item scantron_filenames
                   5971: 
                   5972:    Returns a list of the scantron files in the current course 
                   5973: 
                   5974: =cut
1.422     foxr     5975: 
1.202     albertel 5976: sub scantron_filenames {
1.257     albertel 5977:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5978:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5979:     my $getpropath = 1;
1.662     raeburn  5980:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5981:                                                         $cname,$getpropath);
1.202     albertel 5982:     my @possiblenames;
1.662     raeburn  5983:     if (ref($dirlist) eq 'ARRAY') {
                   5984:         foreach my $filename (sort(@{$dirlist})) {
                   5985: 	    ($filename)=split(/&/,$filename);
                   5986: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5987: 	    $filename=~s/^scantron_orig_//;
                   5988: 	    push(@possiblenames,$filename);
                   5989:         }
1.202     albertel 5990:     }
                   5991:     return @possiblenames;
                   5992: }
                   5993: 
1.423     albertel 5994: =pod 
                   5995: 
                   5996: =item scantron_uploads
                   5997: 
                   5998:    Returns  html drop-down list of scantron files in current course.
                   5999: 
                   6000:  Arguments:
                   6001:    $file2grade - filename to set as selected in the dropdown
                   6002: 
                   6003: =cut
1.422     foxr     6004: 
1.202     albertel 6005: sub scantron_uploads {
1.209     ng       6006:     my ($file2grade) = @_;
1.202     albertel 6007:     my $result=	'<select name="scantron_selectfile">';
                   6008:     $result.="<option></option>";
                   6009:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 6010: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 6011:     }
                   6012:     $result.="</select>";
                   6013:     return $result;
                   6014: }
                   6015: 
1.423     albertel 6016: =pod 
                   6017: 
                   6018: =item scantron_scantab
                   6019: 
                   6020:   Returns html drop down of the scantron formats in the scantronformat.tab
                   6021:   file.
                   6022: 
                   6023: =cut
1.422     foxr     6024: 
1.82      albertel 6025: sub scantron_scantab {
                   6026:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 6027:     $result.='<option></option>'."\n";
1.754     raeburn  6028:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  6029:     if (@lines > 0) {
                   6030:         foreach my $line (@lines) {
                   6031:             next if (($line =~ /^\#/) || ($line eq ''));
                   6032: 	    my ($name,$descrip)=split(/:/,$line);
                   6033: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   6034:         }
1.82      albertel 6035:     }
                   6036:     $result.='</select>'."\n";
1.518     raeburn  6037:     return $result;
                   6038: }
                   6039: 
1.423     albertel 6040: =pod 
                   6041: 
                   6042: =item scantron_CODElist
                   6043: 
                   6044:   Returns html drop down of the saved CODE lists from current course,
                   6045:   generated from earlier printings.
                   6046: 
                   6047: =cut
1.422     foxr     6048: 
1.186     albertel 6049: sub scantron_CODElist {
1.257     albertel 6050:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6051:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 6052:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   6053:     my $namechoice='<option></option>';
1.225     albertel 6054:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 6055: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 6056: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 6057: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   6058:     }
                   6059:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6060:     return $namechoice;
                   6061: }
                   6062: 
1.423     albertel 6063: =pod 
                   6064: 
                   6065: =item scantron_CODEunique
                   6066: 
                   6067:   Returns the html for "Each CODE to be used once" radio.
                   6068: 
                   6069: =cut
1.422     foxr     6070: 
1.186     albertel 6071: sub scantron_CODEunique {
1.532     bisitz   6072:     my $result='<span class="LC_nobreak">
1.272     albertel 6073:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6074:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6075:                 </span>
1.532     bisitz   6076:                 <span class="LC_nobreak">
1.272     albertel 6077:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6078:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6079:                 </span>';
1.186     albertel 6080:     return $result;
                   6081: }
1.423     albertel 6082: 
                   6083: =pod 
                   6084: 
                   6085: =item scantron_selectphase
                   6086: 
1.659     raeburn  6087:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6088:   Allows for - starting a grading run.
1.424     albertel 6089:              - downloading existing scan data (original, corrected
1.423     albertel 6090:                                                 or skipped info)
                   6091: 
                   6092:              - uploading new scan data
                   6093: 
                   6094:  Arguments:
                   6095:   $r          - The Apache request object
                   6096:   $file2grade - name of the file that contain the scanned data to score
                   6097: 
                   6098: =cut
1.186     albertel 6099: 
1.75      albertel 6100: sub scantron_selectphase {
1.608     www      6101:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6102:     if (!$symb) {return '';}
1.582     raeburn  6103:     my $map_error;
                   6104:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6105:     if ($map_error) {
                   6106:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6107:         return;
                   6108:     }
1.324     albertel 6109:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6110:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6111:     my $format_selector=&scantron_scantab();
1.186     albertel 6112:     my $CODE_selector=&scantron_CODElist();
                   6113:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6114:     my $result;
1.422     foxr     6115: 
1.513     foxr     6116:     $ssi_error = 0;
                   6117: 
1.770     raeburn  6118:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 6119: 
                   6120: 	# Chunk of form to prompt for a scantron file upload.
                   6121: 
                   6122:         $r->print('
1.754     raeburn  6123:     <br />');
1.606     wenzelju 6124:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6125:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  6126:     my $csec= $env{'request.course.sec'};
1.736     damieng  6127:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6128:     &js_escape(\$alertmsg);
1.754     raeburn  6129:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 6130:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   6131:     function checkUpload(formname) {
                   6132: 	if (formname.upfile.value == "") {
1.736     damieng  6133: 	    alert("'.$alertmsg.'");
1.606     wenzelju 6134: 	    return false;
                   6135: 	}
                   6136: 	formname.submit();
1.756     raeburn  6137:     }'."\n".$formatjs));
1.606     wenzelju 6138:     $r->print('
                   6139:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6140:                 '.$default_form_data.'
                   6141:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  6142:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 6143:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6144:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  6145:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6146:               '.&Apache::loncommon::start_data_table_header_row().'
                   6147:                 <th>
                   6148:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6149:                 </th>
                   6150:               '.&Apache::loncommon::end_data_table_header_row().'
                   6151:               '.&Apache::loncommon::start_data_table_row().'
                   6152:             <td>
                   6153:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6154:     if ($formatoptions) {
                   6155:         $r->print('</td>
                   6156:                  '.&Apache::loncommon::end_data_table_row().'
                   6157:                  '.&Apache::loncommon::start_data_table_row().'
                   6158:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6159:                  </td>
                   6160:                  '.&Apache::loncommon::end_data_table_row().'
                   6161:                  '.&Apache::loncommon::start_data_table_row().'
                   6162:                  <td>'
                   6163:         );
                   6164:     } else {
                   6165:         $r->print(' <br />');
                   6166:     }
                   6167:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6168:               </td>
                   6169:              '.&Apache::loncommon::end_data_table_row().'
                   6170:              '.&Apache::loncommon::end_data_table().'
                   6171:              </form>'
                   6172:     );
1.606     wenzelju 6173: 
                   6174:     }
                   6175: 
1.422     foxr     6176:     # Chunk of form to prompt for a file to grade and how:
                   6177: 
1.489     albertel 6178:     $result.= '
                   6179:     <br />
                   6180:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6181:     <input type="hidden" name="command" value="scantron_warning" />
                   6182:     '.$default_form_data.'
                   6183:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6184:        '.&Apache::loncommon::start_data_table_header_row().'
                   6185:             <th colspan="2">
1.492     albertel 6186:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6187:             </th>
                   6188:        '.&Apache::loncommon::end_data_table_header_row().'
                   6189:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6190:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6191:        '.&Apache::loncommon::end_data_table_row().'
                   6192:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6193:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6194:        '.&Apache::loncommon::end_data_table_row().'
                   6195:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6196:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6197:        '.&Apache::loncommon::end_data_table_row().'
                   6198:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6199:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6200:        '.&Apache::loncommon::end_data_table_row().'
                   6201:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6202:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6203:        '.&Apache::loncommon::end_data_table_row().'
                   6204:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6205: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6206:             <td>
1.492     albertel 6207: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6208:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6209:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6210: 	    </td>
1.489     albertel 6211:        '.&Apache::loncommon::end_data_table_row().'
                   6212:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6213:             <td colspan="2">
1.572     www      6214:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6215:             </td>
1.489     albertel 6216:        '.&Apache::loncommon::end_data_table_row().'
                   6217:     '.&Apache::loncommon::end_data_table().'
                   6218:     </form>
                   6219: ';
1.162     albertel 6220:    
                   6221:     $r->print($result);
                   6222: 
1.422     foxr     6223:     # Chunk of the form that prompts to view a scoring office file,
                   6224:     # corrected file, skipped records in a file.
                   6225: 
1.489     albertel 6226:     $r->print('
                   6227:    <br />
                   6228:    <form action="/adm/grades" name="scantron_download">
                   6229:      '.$default_form_data.'
                   6230:      <input type="hidden" name="command" value="scantron_download" />
                   6231:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6232:        '.&Apache::loncommon::start_data_table_header_row().'
                   6233:               <th>
1.492     albertel 6234:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6235:               </th>
                   6236:        '.&Apache::loncommon::end_data_table_header_row().'
                   6237:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6238:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6239:                 <br />
1.492     albertel 6240:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6241:        '.&Apache::loncommon::end_data_table_row().'
                   6242:      '.&Apache::loncommon::end_data_table().'
                   6243:    </form>
                   6244:    <br />
                   6245: ');
1.162     albertel 6246: 
1.457     banghart 6247:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6248: 
1.694     bisitz   6249:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6250:              $default_form_data."\n".
                   6251:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6252:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6253:              '<th colspan="2">
1.572     www      6254:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6255:              '</th>'."\n".
                   6256:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6257:               &Apache::loncommon::start_data_table_row()."\n".
                   6258:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6259:               '<td> '.$sequence_selector.' </td>'.
                   6260:               &Apache::loncommon::end_data_table_row()."\n".
                   6261:               &Apache::loncommon::start_data_table_row()."\n".
                   6262:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6263:               '<td> '.$file_selector.' </td>'."\n".
                   6264:               &Apache::loncommon::end_data_table_row()."\n".
                   6265:               &Apache::loncommon::start_data_table_row()."\n".
                   6266:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6267:               '<td> '.$format_selector.' </td>'."\n".
                   6268:               &Apache::loncommon::end_data_table_row()."\n".
                   6269:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6270:               '<td> '.&mt('Options').' </td>'."\n".
                   6271:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6272:               &Apache::loncommon::end_data_table_row()."\n".
                   6273:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6274:               '<td colspan="2">'."\n".
                   6275:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6276:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6277:               '</td>'."\n".
                   6278:               &Apache::loncommon::end_data_table_row()."\n".
                   6279:               &Apache::loncommon::end_data_table()."\n".
                   6280:               '</form><br />');
                   6281:     return;
1.75      albertel 6282: }
                   6283: 
1.423     albertel 6284: =pod 
                   6285: 
                   6286: =item username_to_idmap
                   6287: 
1.556     weissno  6288:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6289:     student username:domain. If a single ID occurs for more than one student,
                   6290:     the status of the student is checked, and if Active, the value in the hash
                   6291:     will be set to the Active student.
1.423     albertel 6292: 
                   6293:   Arguments:
                   6294: 
                   6295:     $classlist - reference to the class list hash. This is a hash
                   6296:                  keyed by student name:domain  whose elements are references
1.424     albertel 6297:                  to arrays containing various chunks of information
1.423     albertel 6298:                  about the student. (See loncoursedata for more info).
                   6299: 
                   6300:   Returns
                   6301:     %idmap - the constructed hash
                   6302: 
                   6303: =cut
                   6304: 
1.82      albertel 6305: sub username_to_idmap {
                   6306:     my ($classlist)= @_;
                   6307:     my %idmap;
                   6308:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6309:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6310:         unless ($id eq '') {
                   6311:             if (!exists($idmap{$id})) {
                   6312:                 $idmap{$id} = $student;
                   6313:             } else {
                   6314:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6315:                 if ($status eq 'Active') {
                   6316:                     $idmap{$id} = $student;
                   6317:                 }
                   6318:             }
                   6319:         }
1.82      albertel 6320:     }
                   6321:     return %idmap;
                   6322: }
1.423     albertel 6323: 
                   6324: =pod
                   6325: 
1.424     albertel 6326: =item scantron_fixup_scanline
1.423     albertel 6327: 
                   6328:    Process a requested correction to a scanline.
                   6329: 
                   6330:   Arguments:
1.754     raeburn  6331:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6332:     $scan_data         - hash of correction information 
                   6333:                           (see &scantron_getfile())
                   6334:     $line              - existing scanline
                   6335:     $whichline         - line number of the passed in scanline
                   6336:     $field             - type of change to process 
                   6337:                          (either 
1.573     bisitz   6338:                           'ID'     -> correct the student/employee ID
1.423     albertel 6339:                           'CODE'   -> correct the CODE
                   6340:                           'answer' -> fixup the submitted answers)
                   6341:     
                   6342:    $args               - hash of additional info,
                   6343:                           - 'ID' 
                   6344:                                'newid' -> studentID to use in replacement
1.424     albertel 6345:                                           of existing one
1.423     albertel 6346:                           - 'CODE' 
                   6347:                                'CODE_ignore_dup' - set to true if duplicates
                   6348:                                                    should be ignored.
                   6349: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6350:                                         if the existing unfound code should
1.423     albertel 6351:                                         be used as is
                   6352:                           - 'answer'
                   6353:                                'response' - new answer or 'none' if blank
                   6354:                                'question' - the bubble line to change
1.503     raeburn  6355:                                'questionnum' - the question identifier,
                   6356:                                                may include subquestion. 
1.423     albertel 6357: 
                   6358:   Returns:
                   6359:     $line - the modified scanline
                   6360: 
                   6361:   Side effects: 
                   6362:     $scan_data - may be updated
                   6363: 
                   6364: =cut
                   6365: 
1.82      albertel 6366: 
1.157     albertel 6367: sub scantron_fixup_scanline {
                   6368:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6369:     if ($field eq 'ID') {
                   6370: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6371: 	    return ($line,1,'New value too large');
1.157     albertel 6372: 	}
                   6373: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6374: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6375: 				     $args->{'newid'});
                   6376: 	}
                   6377: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6378: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6379: 	if ($args->{'newid'}=~/^\s*$/) {
                   6380: 	    &scan_data($scan_data,"$whichline.user",
                   6381: 		       $args->{'username'}.':'.$args->{'domain'});
                   6382: 	}
1.186     albertel 6383:     } elsif ($field eq 'CODE') {
1.192     albertel 6384: 	if ($args->{'CODE_ignore_dup'}) {
                   6385: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6386: 	}
                   6387: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6388: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6389: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6390: 		return ($line,1,'New CODE value too large');
                   6391: 	    }
                   6392: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6393: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6394: 	    }
                   6395: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6396: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6397: 	}
1.157     albertel 6398:     } elsif ($field eq 'answer') {
1.497     foxr     6399: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6400: 	my $off=$scantron_config->{'Qoff'};
                   6401: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6402: 	my $answer=${off}x$length;
                   6403: 	if ($args->{'response'} eq 'none') {
                   6404: 	    &scan_data($scan_data,
1.503     raeburn  6405: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6406: 	} else {
                   6407: 	    if ($on eq 'letter') {
                   6408: 		my @alphabet=('A'..'Z');
                   6409: 		$answer=$alphabet[$args->{'response'}];
                   6410: 	    } elsif ($on eq 'number') {
                   6411: 		$answer=$args->{'response'}+1;
                   6412: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6413: 	    } else {
1.497     foxr     6414: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6415: 	    }
1.497     foxr     6416: 	    &scan_data($scan_data,
1.503     raeburn  6417: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6418: 	}
1.497     foxr     6419: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6420: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6421:     }
                   6422:     return $line;
                   6423: }
1.423     albertel 6424: 
                   6425: =pod
                   6426: 
                   6427: =item scan_data
                   6428: 
                   6429:     Edit or look up  an item in the scan_data hash.
                   6430: 
                   6431:   Arguments:
                   6432:     $scan_data  - The hash (see scantron_getfile)
                   6433:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6434:                   scantronfilename_key).
1.423     albertel 6435:     $data        - New value of the hash entry.
                   6436:     $delete      - If true, the entry is removed from the hash.
                   6437: 
                   6438:   Returns:
                   6439:     The new value of the hash table field (undefined if deleted).
                   6440: 
                   6441: =cut
                   6442: 
                   6443: 
1.157     albertel 6444: sub scan_data {
                   6445:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6446:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6447:     if (defined($value)) {
                   6448: 	$scan_data->{$filename.'_'.$key} = $value;
                   6449:     }
                   6450:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6451:     return $scan_data->{$filename.'_'.$key};
                   6452: }
1.423     albertel 6453: 
1.495     albertel 6454: # ----- These first few routines are general use routines.----
                   6455: 
                   6456: # Return the number of occurences of a pattern in a string.
                   6457: 
                   6458: sub occurence_count {
                   6459:     my ($string, $pattern) = @_;
                   6460: 
                   6461:     my @matches = ($string =~ /$pattern/g);
                   6462: 
                   6463:     return scalar(@matches);
                   6464: }
                   6465: 
                   6466: 
                   6467: # Take a string known to have digits and convert all the
                   6468: # digits into letters in the range J,A..I.
                   6469: 
                   6470: sub digits_to_letters {
                   6471:     my ($input) = @_;
                   6472: 
                   6473:     my @alphabet = ('J', 'A'..'I');
                   6474: 
                   6475:     my @input    = split(//, $input);
                   6476:     my $output ='';
                   6477:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6478: 	if ($input[$i] =~ /\d/) {
                   6479: 	    $output .= $alphabet[$input[$i]];
                   6480: 	} else {
                   6481: 	    $output .= $input[$i];
                   6482: 	}
                   6483:     }
                   6484:     return $output;
                   6485: }
                   6486: 
1.423     albertel 6487: =pod 
                   6488: 
                   6489: =item scantron_parse_scanline
                   6490: 
1.711     bisitz   6491:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6492: 
                   6493:  Arguments:
1.711     bisitz   6494:     line             - The text of the bubblesheet file line to process
1.423     albertel 6495:     whichline        - Line number
1.711     bisitz   6496:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6497:     scan_data        - Hash of extra information about the scanline
                   6498:                        (see scantron_getfile for more information)
                   6499:     just_header      - True if should not process question answers but only
                   6500:                        the stuff to the left of the answers.
1.691     raeburn  6501:     randomorder      - True if randomorder in use
                   6502:     randompick       - True if randompick in use
                   6503:     sequence         - Exam folder URL
                   6504:     master_seq       - Ref to array containing symbs in exam folder
                   6505:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6506:                        (corresponding values are resource objects)
                   6507:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6508:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6509:                        are refs to an array of resource objects, ordered
                   6510:                        according to order used for CODE, when randomorder
                   6511:                        and or randompick are in use.
                   6512:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6513:                        for current line to question number used for same question
                   6514:                         in "Master Sequence" (as seen by Course Coordinator).
                   6515:     startline        - Ref to hash where key is question number (0 is first)
                   6516:                        and value is number of first bubble line for current 
                   6517:                        student or code-based randompick and/or randomorder.
                   6518:     totalref         - Ref of scalar used to score total number of bubble
                   6519:                        lines needed for responses in a scan line (used when
                   6520:                        randompick in use. 
                   6521:     
1.423     albertel 6522:  Returns:
                   6523:    Hash containing the result of parsing the scanline
                   6524: 
                   6525:    Keys are all proceeded by the string 'scantron.'
                   6526: 
                   6527:        CODE    - the CODE in use for this scanline
                   6528:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6529:                  by the operator
                   6530:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6531:                             CODEs were selected, but the usage has been
                   6532:                             forced by the operator
1.556     weissno  6533:        ID  - student/employee ID
1.423     albertel 6534:        PaperID - if used, the ID number printed on the sheet when the 
                   6535:                  paper was scanned
                   6536:        FirstName - first name from the sheet
                   6537:        LastName  - last name from the sheet
                   6538: 
                   6539:      if just_header was not true these key may also exist
                   6540: 
1.447     foxr     6541:        missingerror - a list of bubble ranges that are considered to be answers
                   6542:                       to a single question that don't have any bubbles filled in.
                   6543:                       Of the form questionnumber:firstbubblenumber:count.
                   6544:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6545:                       to a single question that have more than one bubble filled in.
                   6546:                       Of the form questionnumber::firstbubblenumber:count
                   6547:    
                   6548:                 In the above, count is the number of bubble responses in the
                   6549:                 input line needed to represent the possible answers to the question.
                   6550:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6551:                 per line would have count = 2.
                   6552: 
1.423     albertel 6553:        maxquest     - the number of the last bubble line that was parsed
                   6554: 
                   6555:        (<number> starts at 1)
                   6556:        <number>.answer - zero or more letters representing the selected
                   6557:                          letters from the scanline for the bubble line 
                   6558:                          <number>.
                   6559:                          if blank there was either no bubble or there where
                   6560:                          multiple bubbles, (consult the keys missingerror and
                   6561:                          doubleerror if this is an error condition)
                   6562: 
                   6563: =cut
                   6564: 
1.82      albertel 6565: sub scantron_parse_scanline {
1.691     raeburn  6566:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6567:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6568:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6569: 
1.82      albertel 6570:     my %record;
1.691     raeburn  6571:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6572:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6573: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6574: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6575: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6576: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6577: 	    $record{'scantron.CODE'}=substr($data,
                   6578: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6579: 					    $$scantron_config{'CODElength'});
1.191     albertel 6580: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6581: 		$record{'scantron.useCODE'}=1;
                   6582: 	    }
1.192     albertel 6583: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6584: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6585: 	    }
1.82      albertel 6586: 	} else {
                   6587: 	    #FIXME interpret first N questions
                   6588: 	}
                   6589:     }
1.83      albertel 6590:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6591: 				  $$scantron_config{'IDlength'});
1.157     albertel 6592:     $record{'scantron.PaperID'}=
                   6593: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6594: 	       $$scantron_config{'PaperIDlength'});
                   6595:     $record{'scantron.FirstName'}=
                   6596: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6597: 	       $$scantron_config{'FirstNamelength'});
                   6598:     $record{'scantron.LastName'}=
                   6599: 	substr($data,$$scantron_config{'LastName'}-1,
                   6600: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6601:     if ($just_header) { return \%record; }
1.194     albertel 6602: 
1.82      albertel 6603:     my @alphabet=('A'..'Z');
                   6604:     my $questnum=0;
1.447     foxr     6605:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6606: 
1.691     raeburn  6607:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6608:     if ($randompick || $randomorder) {
                   6609:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6610:                                          $master_seq,$symb_to_resource,
                   6611:                                          $partids_by_symb,$orderedforcode,
                   6612:                                          $respnumlookup,$startline);
                   6613:         if ($total) {
                   6614:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6615:         }
                   6616:         if (ref($totalref)) {
                   6617:             $$totalref = $total;
                   6618:         }
                   6619:     }
                   6620:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6621:     chomp($questions);		# Get rid of any trailing \n.
                   6622:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6623:     while (length($questions)) {
1.691     raeburn  6624:         my $answers_needed;
                   6625:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6626:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6627:         } else {
                   6628: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6629:         }
1.503     raeburn  6630:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6631:                              || 1;
                   6632:         $questnum++;
                   6633:         my $quest_id = $questnum;
                   6634:         my $currentquest = substr($questions,0,$answer_length);
                   6635:         $questions       = substr($questions,$answer_length);
                   6636:         if (length($currentquest) < $answer_length) { next; }
                   6637: 
1.691     raeburn  6638:         my $subdivided;
                   6639:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6640:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6641:         } else {
                   6642:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6643:         }
                   6644:         if ($subdivided =~ /,/) {
1.503     raeburn  6645:             my $subquestnum = 1;
                   6646:             my $subquestions = $currentquest;
1.691     raeburn  6647:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6648:             foreach my $subans (@subanswers_needed) {
                   6649:                 my $subans_length =
                   6650:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6651:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6652:                 $subquestions   = substr($subquestions,$subans_length);
                   6653:                 $quest_id = "$questnum.$subquestnum";
                   6654:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6655:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6656:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6657:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6658:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6659:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6660:                 } else {
                   6661:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6662:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6663:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6664:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6665:                 }
                   6666:                 $subquestnum ++;
                   6667:             }
                   6668:         } else {
                   6669:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6670:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6671:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6672:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6673:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6674:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6675:             } else {
                   6676:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6677:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6678:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6679:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6680:             }
                   6681:         }
                   6682:     }
                   6683:     $record{'scantron.maxquest'}=$questnum;
                   6684:     return \%record;
                   6685: }
1.447     foxr     6686: 
1.691     raeburn  6687: sub get_master_seq {
                   6688:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6689:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6690:                    (ref($symb_to_resource) eq 'HASH'));
                   6691:     my $resource_error;
                   6692:     foreach my $resource (@{$resources}) {
                   6693:         my $ressymb;
                   6694:         if (ref($resource)) {
                   6695:             $ressymb = $resource->symb();
                   6696:             push(@{$master_seq},$ressymb);
                   6697:             $symb_to_resource->{$ressymb} = $resource;
                   6698:         } else {
                   6699:             $resource_error = 1;
                   6700:             last;
                   6701:         }
                   6702:     }
                   6703:     return $resource_error;
                   6704: }
                   6705: 
                   6706: sub get_respnum_lookups {
                   6707:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6708:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6709:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6710:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6711:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6712:                    (ref($startline) eq 'HASH'));
                   6713:     my ($user,$scancode);
                   6714:     if ((exists($record->{'scantron.CODE'})) &&
                   6715:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6716:         $scancode = $record->{'scantron.CODE'};
                   6717:     } else {
                   6718:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6719:     }
                   6720:     my @mapresources =
                   6721:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6722:                      $orderedforcode);
                   6723:     my $total = 0;
                   6724:     my $count = 0;
                   6725:     foreach my $resource (@mapresources) {
                   6726:         my $id = $resource->id();
                   6727:         my $symb = $resource->symb();
                   6728:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6729:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6730:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6731:                 if ($respnum ne '') {
                   6732:                     $respnumlookup->{$count} = $respnum;
                   6733:                     $startline->{$count} = $total;
                   6734:                     $total += $bubble_lines_per_response{$respnum};
                   6735:                     $count ++;
                   6736:                 }
                   6737:             }
                   6738:         }
                   6739:     }
                   6740:     return $total;
                   6741: }
                   6742: 
1.503     raeburn  6743: sub scantron_validator_lettnum {
                   6744:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6745:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6746:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6747: 
                   6748:     # Qon 'letter' implies for each slot in currquest we have:
                   6749:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6750:     #    about anything else (esp. a value of Qoff) for missing
                   6751:     #    bubbles.
                   6752:     #
                   6753:     # Qon 'number' implies each slot gives a digit that indexes the
                   6754:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6755:     #    and * or ? for double bubbles on a single line.
                   6756:     #
1.447     foxr     6757: 
1.503     raeburn  6758:     my $matchon;
                   6759:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6760:         $matchon = '[A-Z]';
                   6761:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6762:         $matchon = '\d';
                   6763:     }
                   6764:     my $occurrences = 0;
1.691     raeburn  6765:     my $responsenum = $questnum-1;
                   6766:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6767:        $responsenum = $respnumlookup->{$questnum-1} 
                   6768:     }
                   6769:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6770:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6771:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6772:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6773:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6774:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6775:         my @singlelines = split('',$currquest);
                   6776:         foreach my $entry (@singlelines) {
                   6777:             $occurrences = &occurence_count($entry,$matchon);
                   6778:             if ($occurrences > 1) {
                   6779:                 last;
                   6780:             }
1.691     raeburn  6781:         }
1.503     raeburn  6782:     } else {
                   6783:         $occurrences = &occurence_count($currquest,$matchon); 
                   6784:     }
                   6785:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6786:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6787:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6788:             my $bubble = substr($currquest,$ans,1);
                   6789:             if ($bubble =~ /$matchon/ ) {
                   6790:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6791:                     if ($bubble == 0) {
                   6792:                         $bubble = 10; 
                   6793:                     }
                   6794:                     $record->{"scantron.$ansnum.answer"} = 
                   6795:                         $alphabet->[$bubble-1];
                   6796:                 } else {
                   6797:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6798:                 }
                   6799:             } else {
                   6800:                 $record->{"scantron.$ansnum.answer"}='';
                   6801:             }
                   6802:             $ansnum++;
                   6803:         }
                   6804:     } elsif (!defined($currquest)
                   6805:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6806:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6807:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6808:             $record->{"scantron.$ansnum.answer"}='';
                   6809:             $ansnum++;
                   6810:         }
                   6811:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6812:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6813:         }
                   6814:     } else {
                   6815:         if ($$scantron_config{'Qon'} eq 'number') {
                   6816:             $currquest = &digits_to_letters($currquest);            
                   6817:         }
                   6818:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6819:             my $bubble = substr($currquest,$ans,1);
                   6820:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6821:             $ansnum++;
                   6822:         }
                   6823:     }
                   6824:     return $ansnum;
                   6825: }
1.447     foxr     6826: 
1.503     raeburn  6827: sub scantron_validator_positional {
                   6828:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6829:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6830:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6831: 
1.503     raeburn  6832:     # Otherwise there's a positional notation;
                   6833:     # each bubble line requires Qlength items, and there are filled in
                   6834:     # bubbles for each case where there 'Qon' characters.
                   6835:     #
1.447     foxr     6836: 
1.503     raeburn  6837:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6838: 
1.503     raeburn  6839:     # If the split only gives us one element.. the full length of the
                   6840:     # answer string, no bubbles are filled in:
1.447     foxr     6841: 
1.507     raeburn  6842:     if ($answers_needed eq '') {
                   6843:         return;
                   6844:     }
                   6845: 
1.503     raeburn  6846:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6847:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6848:             $record->{"scantron.$ansnum.answer"}='';
                   6849:             $ansnum++;
                   6850:         }
                   6851:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6852:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6853:         }
                   6854:     } elsif (scalar(@array) == 2) {
                   6855:         my $location = length($array[0]);
                   6856:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6857:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6858:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6859:             if ($ans eq $line_num) {
                   6860:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6861:             } else {
                   6862:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6863:             }
                   6864:             $ansnum++;
                   6865:          }
                   6866:     } else {
                   6867:         #  If there's more than one instance of a bubble character
                   6868:         #  That's a double bubble; with positional notation we can
                   6869:         #  record all the bubbles filled in as well as the
                   6870:         #  fact this response consists of multiple bubbles.
                   6871:         #
1.691     raeburn  6872:         my $responsenum = $questnum-1;
                   6873:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6874:             $responsenum = $respnumlookup->{$questnum-1}
                   6875:         }
                   6876:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6877:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6878:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6879:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6880:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6881:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6882:             my $doubleerror = 0;
                   6883:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6884:                    (!$doubleerror)) {
                   6885:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6886:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6887:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6888:                if (length(@currarray) > 2) {
                   6889:                    $doubleerror = 1;
                   6890:                } 
                   6891:             }
                   6892:             if ($doubleerror) {
                   6893:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6894:             }
                   6895:         } else {
                   6896:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6897:         }
                   6898:         my $item = $ansnum;
                   6899:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6900:             $record->{"scantron.$item.answer"} = '';
                   6901:             $item ++;
                   6902:         }
1.447     foxr     6903: 
1.503     raeburn  6904:         my @ans=@array;
                   6905:         my $i=0;
                   6906:         my $increment = 0;
                   6907:         while ($#ans) {
                   6908:             $i+=length($ans[0]) + $increment;
                   6909:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6910:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6911:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6912:             shift(@ans);
                   6913:             $increment = 1;
                   6914:         }
                   6915:         $ansnum += $answers_needed;
1.82      albertel 6916:     }
1.503     raeburn  6917:     return $ansnum;
1.82      albertel 6918: }
                   6919: 
1.423     albertel 6920: =pod
                   6921: 
                   6922: =item scantron_add_delay
                   6923: 
                   6924:    Adds an error message that occurred during the grading phase to a
                   6925:    queue of messages to be shown after grading pass is complete
                   6926: 
                   6927:  Arguments:
1.424     albertel 6928:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6929:    $scanline    - the scanline that caused the error
                   6930:    $errormesage - the error message
                   6931:    $errorcode   - a numeric code for the error
                   6932: 
                   6933:  Side Effects:
1.424     albertel 6934:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6935: 
                   6936: =cut
                   6937: 
1.82      albertel 6938: sub scantron_add_delay {
1.140     albertel 6939:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6940:     push(@$delayqueue,
                   6941: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6942: 	  'ecode' => $errorcode }
                   6943: 	 );
1.82      albertel 6944: }
                   6945: 
1.423     albertel 6946: =pod
                   6947: 
                   6948: =item scantron_find_student
                   6949: 
1.424     albertel 6950:    Finds the username for the current scanline
                   6951: 
                   6952:   Arguments:
                   6953:    $scantron_record - hash result from scantron_parse_scanline
                   6954:    $scan_data       - hash of correction information 
                   6955:                       (see &scantron_getfile() form more information)
                   6956:    $idmap           - hash from &username_to_idmap()
                   6957:    $line            - number of current scanline
                   6958:  
                   6959:   Returns:
                   6960:    Either 'username:domain' or undef if unknown
                   6961: 
1.423     albertel 6962: =cut
                   6963: 
1.82      albertel 6964: sub scantron_find_student {
1.157     albertel 6965:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6966:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6967:     if ($scanID =~ /^\s*$/) {
                   6968:  	return &scan_data($scan_data,"$line.user");
                   6969:     }
1.83      albertel 6970:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6971:  	if (lc($id) eq lc($scanID)) {
                   6972:  	    return $$idmap{$id};
                   6973:  	}
1.83      albertel 6974:     }
                   6975:     return undef;
                   6976: }
                   6977: 
1.423     albertel 6978: =pod
                   6979: 
                   6980: =item scantron_filter
                   6981: 
1.424     albertel 6982:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6983:    hidden resources was selected
                   6984: 
1.423     albertel 6985: =cut
                   6986: 
1.83      albertel 6987: sub scantron_filter {
                   6988:     my ($curres)=@_;
1.331     albertel 6989: 
                   6990:     if (ref($curres) && $curres->is_problem()) {
                   6991: 	# if the user has asked to not have either hidden
                   6992: 	# or 'randomout' controlled resources to be graded
                   6993: 	# don't include them
                   6994: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6995: 	    && $curres->randomout) {
                   6996: 	    return 0;
                   6997: 	}
1.83      albertel 6998: 	return 1;
                   6999:     }
                   7000:     return 0;
1.82      albertel 7001: }
                   7002: 
1.423     albertel 7003: =pod
                   7004: 
                   7005: =item scantron_process_corrections
                   7006: 
1.424     albertel 7007:    Gets correction information out of submitted form data and corrects
                   7008:    the scanline
                   7009: 
1.423     albertel 7010: =cut
                   7011: 
1.157     albertel 7012: sub scantron_process_corrections {
                   7013:     my ($r) = @_;
1.754     raeburn  7014:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7015:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7016:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 7017:     my $which=$env{'form.scantron_line'};
1.200     albertel 7018:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 7019:     my ($skip,$err,$errmsg);
1.257     albertel 7020:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 7021: 	$skip=1;
1.257     albertel 7022:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   7023: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   7024: 	    $env{'form.scantron_domain'};
1.157     albertel 7025: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   7026: 	($line,$err,$errmsg)=
                   7027: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   7028: 				     'ID',{'newid'=>$newid,
1.257     albertel 7029: 				    'username'=>$env{'form.scantron_username'},
                   7030: 				    'domain'=>$env{'form.scantron_domain'}});
                   7031:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   7032: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 7033: 	my $newCODE;
1.192     albertel 7034: 	my %args;
1.190     albertel 7035: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 7036: 	    $newCODE='use_unfound';
1.190     albertel 7037: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 7038: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 7039: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 7040: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 7041: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 7042: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 7043: 	}
1.257     albertel 7044: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 7045: 	    $args{'CODE_ignore_dup'}=1;
                   7046: 	}
                   7047: 	$args{'CODE'}=$newCODE;
1.186     albertel 7048: 	($line,$err,$errmsg)=
                   7049: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7050: 				     'CODE',\%args);
1.257     albertel 7051:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7052: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7053: 	    ($line,$err,$errmsg)=
                   7054: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7055: 					 $which,'answer',
                   7056: 					 { 'question'=>$question,
1.503     raeburn  7057: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7058:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7059: 	    if ($err) { last; }
                   7060: 	}
                   7061:     }
                   7062:     if ($err) {
1.703     bisitz   7063:         $r->print(
                   7064:             '<p class="LC_error">'
                   7065:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7066:                 $errmsg)
1.704     raeburn  7067:            .'</p>');
1.157     albertel 7068:     } else {
1.200     albertel 7069: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7070: 	&scantron_putfile($scanlines,$scan_data);
                   7071:     }
                   7072: }
                   7073: 
1.423     albertel 7074: =pod
                   7075: 
                   7076: =item reset_skipping_status
                   7077: 
1.424     albertel 7078:    Forgets the current set of remember skipped scanlines (and thus
                   7079:    reverts back to considering all lines in the
                   7080:    scantron_skipped_<filename> file)
                   7081: 
1.423     albertel 7082: =cut
                   7083: 
1.200     albertel 7084: sub reset_skipping_status {
                   7085:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7086:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7087:     &scantron_putfile(undef,$scan_data);
                   7088: }
                   7089: 
1.423     albertel 7090: =pod
                   7091: 
                   7092: =item start_skipping
                   7093: 
1.424     albertel 7094:    Marks a scanline to be skipped. 
                   7095: 
1.423     albertel 7096: =cut
                   7097: 
1.376     albertel 7098: sub start_skipping {
1.200     albertel 7099:     my ($scan_data,$i)=@_;
                   7100:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7101:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7102: 	$remembered{$i}=2;
                   7103:     } else {
                   7104: 	$remembered{$i}=1;
                   7105:     }
1.200     albertel 7106:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7107: }
                   7108: 
1.423     albertel 7109: =pod
                   7110: 
                   7111: =item should_be_skipped
                   7112: 
1.424     albertel 7113:    Checks whether a scanline should be skipped.
                   7114: 
1.423     albertel 7115: =cut
                   7116: 
1.200     albertel 7117: sub should_be_skipped {
1.376     albertel 7118:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7119:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7120: 	# not redoing old skips
1.376     albertel 7121: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7122: 	return 0;
                   7123:     }
                   7124:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7125: 
                   7126:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7127: 	return 0;
                   7128:     }
1.200     albertel 7129:     return 1;
                   7130: }
                   7131: 
1.423     albertel 7132: =pod
                   7133: 
                   7134: =item remember_current_skipped
                   7135: 
1.424     albertel 7136:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7137:    file and remembers them into scan_data for later use.
                   7138: 
1.423     albertel 7139: =cut
                   7140: 
1.200     albertel 7141: sub remember_current_skipped {
                   7142:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7143:     my %to_remember;
                   7144:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7145: 	if ($scanlines->{'skipped'}[$i]) {
                   7146: 	    $to_remember{$i}=1;
                   7147: 	}
                   7148:     }
1.376     albertel 7149: 
1.200     albertel 7150:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7151:     &scantron_putfile(undef,$scan_data);
                   7152: }
                   7153: 
1.423     albertel 7154: =pod
                   7155: 
                   7156: =item check_for_error
                   7157: 
1.424     albertel 7158:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  7159:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7160:     something went wrong.
                   7161: 
1.423     albertel 7162: =cut
                   7163: 
1.200     albertel 7164: sub check_for_error {
                   7165:     my ($r,$result)=@_;
                   7166:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7167: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7168:     }
                   7169: }
1.157     albertel 7170: 
1.423     albertel 7171: =pod
                   7172: 
                   7173: =item scantron_warning_screen
                   7174: 
1.424     albertel 7175:    Interstitial screen to make sure the operator has selected the
                   7176:    correct options before we start the validation phase.
                   7177: 
1.423     albertel 7178: =cut
                   7179: 
1.203     albertel 7180: sub scantron_warning_screen {
1.650     raeburn  7181:     my ($button_text,$symb)=@_;
1.257     albertel 7182:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  7183:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7184:     my $CODElist;
1.284     albertel 7185:     if ($scantron_config{'CODElocation'} &&
                   7186: 	$scantron_config{'CODEstart'} &&
                   7187: 	$scantron_config{'CODElength'}) {
                   7188: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   7189: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7190: 	$CODElist=
1.492     albertel 7191: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7192: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7193:     }
1.663     raeburn  7194:     my $lastbubblepoints;
                   7195:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7196:         $lastbubblepoints =
                   7197:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7198:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7199:     }
1.770     raeburn  7200:     return '
1.203     albertel 7201: <p>
1.492     albertel 7202: <span class="LC_warning">
1.705     raeburn  7203: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7204: </p>
                   7205: <table>
1.492     albertel 7206: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7207: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  7208: '.$CODElist.$lastbubblepoints.'
1.203     albertel 7209: </table>
1.680     raeburn  7210: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  7211: '.&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  7212: ';
1.203     albertel 7213: }
                   7214: 
1.423     albertel 7215: =pod
                   7216: 
                   7217: =item scantron_do_warning
                   7218: 
1.424     albertel 7219:    Check if the operator has picked something for all required
                   7220:    fields. Error out if something is missing.
                   7221: 
1.423     albertel 7222: =cut
                   7223: 
1.203     albertel 7224: sub scantron_do_warning {
1.608     www      7225:     my ($r,$symb)=@_;
1.203     albertel 7226:     if (!$symb) {return '';}
1.324     albertel 7227:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7228:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7229:     if ( $env{'form.selectpage'} eq '' ||
                   7230: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7231: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7232: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7233: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7234: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7235: 	} 
1.257     albertel 7236: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7237: 	    $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  7238: 	}
1.257     albertel 7239: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7240: 	    $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  7241: 	}
1.237     albertel 7242:     } else {
1.650     raeburn  7243: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  7244:         my ($checksec,@possibles) = &gradable_sections();
                   7245:         my $gradesections;
                   7246:         if ($checksec) {
                   7247:             my $file=$env{'form.scantron_selectfile'};
                   7248:             if (&valid_file($file)) {
                   7249:                 my %bysec = &scantron_get_sections();
                   7250:                 my $table;
                   7251:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   7252:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   7253:                     $table = &Apache::loncommon::start_data_table()."\n".
                   7254:                              &Apache::loncommon::start_data_table_header_row().
                   7255:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   7256:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   7257:                     if ($bysec{'none'}) {
                   7258:                         $table .= &Apache::loncommon::start_data_table_row().
                   7259:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   7260:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7261:                     }
                   7262:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   7263:                         next if ($sec eq 'none');
                   7264:                         $table .= &Apache::loncommon::start_data_table_row().
                   7265:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   7266:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7267:                     }
                   7268:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   7269:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   7270:                                       '<p>'.$table.'</p>';
                   7271:                     if (@possibles) {
                   7272:                         $gradesections .= '<p>'.
                   7273:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   7274:                                               scalar(@possibles)).'<br />'.
                   7275:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   7276:                                               '<i>'.$checksec.'</i>').' ';
                   7277:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   7278:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   7279:                         }
                   7280:                         $gradesections .= '</p>';
                   7281:                     }
                   7282:                 }
                   7283:             } else {
                   7284:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   7285:             }
                   7286:         }
1.663     raeburn  7287:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7288: 	$r->print('
1.770     raeburn  7289: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 7290: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7291: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7292: ');
1.237     albertel 7293:     }
1.614     www      7294:     $r->print("</form><br />");
1.203     albertel 7295:     return '';
                   7296: }
                   7297: 
1.423     albertel 7298: =pod
                   7299: 
                   7300: =item scantron_form_start
                   7301: 
1.424     albertel 7302:     html hidden input for remembering all selected grading options
                   7303: 
1.423     albertel 7304: =cut
                   7305: 
1.203     albertel 7306: sub scantron_form_start {
                   7307:     my ($max_bubble)=@_;
                   7308:     my $result= <<SCANTRONFORM;
                   7309: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7310:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7311:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7312:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7313:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7314:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7315:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7316:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7317:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7318:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7319: SCANTRONFORM
1.447     foxr     7320: 
                   7321:   my $line = 0;
                   7322:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7323:        my $chunk =
                   7324: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7325:        $chunk .=
                   7326: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7327:        $chunk .= 
                   7328:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7329:        $chunk .=
                   7330:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7331:        $chunk .=
                   7332:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7333:        $result .= $chunk;
                   7334:        $line++;
1.691     raeburn  7335:     }
1.203     albertel 7336:     return $result;
                   7337: }
                   7338: 
1.423     albertel 7339: =pod
                   7340: 
                   7341: =item scantron_validate_file
                   7342: 
1.659     raeburn  7343:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7344: 
                   7345:     Also processes any necessary information resets that need to
                   7346:     occur before validation begins (ignore previous corrections,
                   7347:     restarting the skipped records processing)
                   7348: 
1.423     albertel 7349: =cut
                   7350: 
1.157     albertel 7351: sub scantron_validate_file {
1.608     www      7352:     my ($r,$symb) = @_;
1.157     albertel 7353:     if (!$symb) {return '';}
1.324     albertel 7354:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7355:     
1.703     bisitz   7356:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7357:     # them when doing the corrections reset
1.257     albertel 7358:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7359: 	&reset_skipping_status();
                   7360:     }
1.257     albertel 7361:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7362: 	&remember_current_skipped();
1.257     albertel 7363: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7364:     }
                   7365: 
1.257     albertel 7366:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7367: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7368: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7369: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7370: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7371:     }
1.200     albertel 7372: 
1.257     albertel 7373:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7374: 	&scantron_process_corrections($r);
                   7375:     }
1.770     raeburn  7376: 
                   7377:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   7378:     my ($checksec,@gradable);
                   7379:     if ($env{'request.course.sec'}) {
                   7380:         ($checksec,my @possibles) = &gradable_sections();
                   7381:         if ($checksec) {
                   7382:             if (@possibles) {
                   7383:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   7384:                 if (@chosensecs) {
                   7385:                     foreach my $sec (@chosensecs) {
                   7386:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   7387:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   7388:                                 push(@gradable,$sec);
                   7389:                             }
                   7390:                         }
                   7391:                     }
                   7392:                 }
                   7393:             }
                   7394:             $r->print('<p><table>');
                   7395:             if (@gradable) {
                   7396:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   7397:                 $r->print(
                   7398:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   7399:             } else {
                   7400:                 $r->print(
                   7401:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   7402:             }
                   7403:             $r->print('</table></p>');
                   7404:         }
                   7405:     }
                   7406:     $r->rflush();
                   7407: 
1.157     albertel 7408:     #get the student pick code ready
                   7409:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7410:     my $nav_error;
1.754     raeburn  7411:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7412:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7413:     if ($nav_error) {
                   7414:         $r->print(&navmap_errormsg());
                   7415:         return '';
                   7416:     }
1.203     albertel 7417:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7418:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7419:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7420:     }
1.157     albertel 7421:     $r->print($result);
                   7422:     
1.334     albertel 7423:     my @validate_phases=( 'sequence',
                   7424: 			  'ID',
1.157     albertel 7425: 			  'CODE',
                   7426: 			  'doublebubble',
                   7427: 			  'missingbubbles');
1.257     albertel 7428:     if (!$env{'form.validatepass'}) {
                   7429: 	$env{'form.validatepass'} = 0;
1.157     albertel 7430:     }
1.257     albertel 7431:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  7432:     my %skipbysec=();
1.448     foxr     7433: 
1.157     albertel 7434:     my $stop=0;
                   7435:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7436: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7437: 	$r->rflush();
1.691     raeburn  7438:      
1.157     albertel 7439: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7440: 	{
                   7441: 	    no strict 'refs';
1.770     raeburn  7442:             my @extras=();
                   7443:             if ($validate_phases[$currentphase] eq 'ID') {
                   7444:                 @extras = (\%skipbysec,$checksec,@gradable);
                   7445:             }
                   7446: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 7447: 	}
                   7448:     }
                   7449:     if (!$stop) {
1.650     raeburn  7450: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  7451:         my $secinfo;
                   7452:         if (keys(%skipbysec) > 0) {
                   7453:             my $seclist = '<ul>';
                   7454:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   7455:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   7456:             }
                   7457:             $seclist .= '</ul>';
                   7458:             $secinfo = '<p class="LC_info">'.
                   7459:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   7460:                            $seclist).
                   7461:                        '</p>';
                   7462:         }
1.542     raeburn  7463: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  7464:                   $secinfo.$warning.
1.542     raeburn  7465:                   &mt('Perform verification for each student after storage of submissions?').
                   7466:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7467:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7468:                   ('&nbsp;'x3).'<label>'.
                   7469:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7470:                   '</label></span><br />'.
                   7471:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7472:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7473:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7474:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7475:     } else {
                   7476: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7477: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7478:     }
                   7479:     if ($stop) {
1.334     albertel 7480: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7481: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7482: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7483: 
1.650     raeburn  7484: 	    $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 7485: 	} else {
1.503     raeburn  7486:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7487: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7488:             } else {
1.539     riegler  7489:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7490:             }
1.492     albertel 7491: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7492: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7493: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7494: 	}
1.157     albertel 7495:     }
1.614     www      7496:     $r->print(" </form><br />");
1.157     albertel 7497:     return '';
                   7498: }
                   7499: 
1.423     albertel 7500: 
                   7501: =pod
                   7502: 
                   7503: =item scantron_remove_file
                   7504: 
1.659     raeburn  7505:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7506:    scantron_original_<filename> is never removed
                   7507: 
                   7508: 
1.423     albertel 7509: =cut
                   7510: 
1.200     albertel 7511: sub scantron_remove_file {
1.192     albertel 7512:     my ($which)=@_;
1.257     albertel 7513:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7514:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7515:     my $file='scantron_';
1.200     albertel 7516:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7517: 	$file.=$which.'_';
1.192     albertel 7518:     } else {
                   7519: 	return 'refused';
                   7520:     }
1.257     albertel 7521:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7522:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7523: }
                   7524: 
1.423     albertel 7525: 
                   7526: =pod
                   7527: 
                   7528: =item scantron_remove_scan_data
                   7529: 
1.659     raeburn  7530:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7531:    data file.  (In the case that both the are doing skipped records we need
                   7532:    to remember the old skipped lines for the time being so that element
                   7533:    persists for a while.)
                   7534: 
1.423     albertel 7535: =cut
                   7536: 
1.200     albertel 7537: sub scantron_remove_scan_data {
1.257     albertel 7538:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7539:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7540:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7541:     my @todelete;
1.257     albertel 7542:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7543:     foreach my $key (@keys) {
                   7544: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7545: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7546: 		$key=~/remember_skipping/) {
                   7547: 		next;
                   7548: 	    }
1.192     albertel 7549: 	    push(@todelete,$key);
                   7550: 	}
                   7551:     }
1.200     albertel 7552:     my $result;
1.192     albertel 7553:     if (@todelete) {
1.491     albertel 7554: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7555: 				       \@todelete,$cdom,$cname);
                   7556:     } else {
                   7557: 	$result = 'ok';
1.192     albertel 7558:     }
                   7559:     return $result;
                   7560: }
                   7561: 
1.423     albertel 7562: 
                   7563: =pod
                   7564: 
                   7565: =item scantron_getfile
                   7566: 
1.659     raeburn  7567:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7568:     the scan_data hash
                   7569:   
                   7570:   Arguments:
                   7571:     None
                   7572: 
                   7573:   Returns:
                   7574:     2 hash references
                   7575: 
                   7576:      - first one has 
                   7577:          orig      -
                   7578:          corrected -
                   7579:          skipped   -  each of which points to an array ref of the specified
                   7580:                       file broken up into individual lines
                   7581:          count     - number of scanlines
                   7582:  
                   7583:      - second is the scan_data hash possible keys are
1.425     albertel 7584:        ($number refers to scanline numbered $number and thus the key affects
                   7585:         only that scanline
                   7586:         $bubline refers to the specific bubble line element and the aspects
                   7587:         refers to that specific bubble line element)
                   7588: 
                   7589:        $number.user - username:domain to use
                   7590:        $number.CODE_ignore_dup 
                   7591:                     - ignore the duplicate CODE error 
                   7592:        $number.useCODE
                   7593:                     - use the CODE in the scanline as is
                   7594:        $number.no_bubble.$bubline
                   7595:                     - it is valid that there is no bubbled in bubble
                   7596:                       at $number $bubline
                   7597:        remember_skipping
                   7598:                     - a frozen hash containing keys of $number and values
                   7599:                       of either 
                   7600:                         1 - we are on a 'do skipped records pass' and plan
                   7601:                             on processing this line
                   7602:                         2 - we are on a 'do skipped records pass' and this
                   7603:                             scanline has been marked to skip yet again
1.424     albertel 7604: 
1.423     albertel 7605: =cut
                   7606: 
1.157     albertel 7607: sub scantron_getfile {
1.200     albertel 7608:     #FIXME really would prefer a scantron directory
1.257     albertel 7609:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7610:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7611:     my $lines;
                   7612:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7613: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7614:     my %scanlines;
                   7615:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7616:     my $temp=$scanlines{'orig'};
                   7617:     $scanlines{'count'}=$#$temp;
                   7618: 
                   7619:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7620: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7621:     if ($lines eq '-1') {
                   7622: 	$scanlines{'corrected'}=[];
                   7623:     } else {
                   7624: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7625:     }
                   7626:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7627: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7628:     if ($lines eq '-1') {
                   7629: 	$scanlines{'skipped'}=[];
                   7630:     } else {
                   7631: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7632:     }
1.175     albertel 7633:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7634:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7635:     my %scan_data = @tmp;
                   7636:     return (\%scanlines,\%scan_data);
                   7637: }
                   7638: 
1.423     albertel 7639: =pod
                   7640: 
                   7641: =item lonnet_putfile
                   7642: 
1.424     albertel 7643:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7644: 
                   7645:  Arguments:
                   7646:    $contents - data to store
                   7647:    $filename - filename to store $contents into
                   7648: 
                   7649:  Returns:
                   7650:    result value from &Apache::lonnet::finishuserfileupload
                   7651: 
1.423     albertel 7652: =cut
                   7653: 
1.157     albertel 7654: sub lonnet_putfile {
                   7655:     my ($contents,$filename)=@_;
1.257     albertel 7656:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7657:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7658:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7659:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7660: 
                   7661: }
                   7662: 
1.423     albertel 7663: =pod
                   7664: 
                   7665: =item scantron_putfile
                   7666: 
1.659     raeburn  7667:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7668:     scan_data hash. (Does not modify the original version only the
                   7669:     corrected and skipped versions.
                   7670: 
                   7671:  Arguments:
                   7672:     $scanlines - hash ref that looks like the first return value from
                   7673:                  &scantron_getfile()
                   7674:     $scan_data - hash ref that looks like the second return value from
                   7675:                  &scantron_getfile()
                   7676: 
1.423     albertel 7677: =cut
                   7678: 
1.157     albertel 7679: sub scantron_putfile {
                   7680:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7681:     #FIXME really would prefer a scantron directory
1.257     albertel 7682:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7683:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7684:     if ($scanlines) {
                   7685: 	my $prefix='scantron_';
1.157     albertel 7686: # no need to update orig, shouldn't change
                   7687: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7688: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7689: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7690: 			$prefix.'corrected_'.
1.257     albertel 7691: 			$env{'form.scantron_selectfile'});
1.200     albertel 7692: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7693: 			$prefix.'skipped_'.
1.257     albertel 7694: 			$env{'form.scantron_selectfile'});
1.200     albertel 7695:     }
1.175     albertel 7696:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7697: }
                   7698: 
1.423     albertel 7699: =pod
                   7700: 
                   7701: =item scantron_get_line
                   7702: 
1.424     albertel 7703:    Returns the correct version of the scanline
                   7704: 
                   7705:  Arguments:
                   7706:     $scanlines - hash ref that looks like the first return value from
                   7707:                  &scantron_getfile()
                   7708:     $scan_data - hash ref that looks like the second return value from
                   7709:                  &scantron_getfile()
                   7710:     $i         - number of the requested line (starts at 0)
                   7711: 
                   7712:  Returns:
                   7713:    A scanline, (either the original or the corrected one if it
                   7714:    exists), or undef if the requested scanline should be
                   7715:    skipped. (Either because it's an skipped scanline, or it's an
                   7716:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7717:    pass.
                   7718: 
1.423     albertel 7719: =cut
                   7720: 
1.157     albertel 7721: sub scantron_get_line {
1.200     albertel 7722:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7723:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7724:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7725:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7726:     return $scanlines->{'orig'}[$i]; 
                   7727: }
                   7728: 
1.423     albertel 7729: =pod
                   7730: 
                   7731: =item scantron_todo_count
                   7732: 
1.424     albertel 7733:     Counts the number of scanlines that need processing.
                   7734: 
                   7735:  Arguments:
                   7736:     $scanlines - hash ref that looks like the first return value from
                   7737:                  &scantron_getfile()
                   7738:     $scan_data - hash ref that looks like the second return value from
                   7739:                  &scantron_getfile()
                   7740: 
                   7741:  Returns:
                   7742:     $count - number of scanlines to process
                   7743: 
1.423     albertel 7744: =cut
                   7745: 
1.200     albertel 7746: sub get_todo_count {
                   7747:     my ($scanlines,$scan_data)=@_;
                   7748:     my $count=0;
                   7749:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7750: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7751: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7752: 	$count++;
                   7753:     }
                   7754:     return $count;
                   7755: }
                   7756: 
1.423     albertel 7757: =pod
                   7758: 
                   7759: =item scantron_put_line
                   7760: 
1.659     raeburn  7761:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7762:     data file.
                   7763: 
                   7764:  Arguments:
                   7765:     $scanlines - hash ref that looks like the first return value from
                   7766:                  &scantron_getfile()
                   7767:     $scan_data - hash ref that looks like the second return value from
                   7768:                  &scantron_getfile()
                   7769:     $i         - line number to update
                   7770:     $newline   - contents of the updated scanline
                   7771:     $skip      - if true make the line for skipping and update the
                   7772:                  'skipped' file
                   7773: 
1.423     albertel 7774: =cut
                   7775: 
1.157     albertel 7776: sub scantron_put_line {
1.200     albertel 7777:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7778:     if ($skip) {
                   7779: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7780: 	&start_skipping($scan_data,$i);
1.157     albertel 7781: 	return;
                   7782:     }
                   7783:     $scanlines->{'corrected'}[$i]=$newline;
                   7784: }
                   7785: 
1.423     albertel 7786: =pod
                   7787: 
                   7788: =item scantron_clear_skip
                   7789: 
1.424     albertel 7790:    Remove a line from the 'skipped' file
                   7791: 
                   7792:  Arguments:
                   7793:     $scanlines - hash ref that looks like the first return value from
                   7794:                  &scantron_getfile()
                   7795:     $scan_data - hash ref that looks like the second return value from
                   7796:                  &scantron_getfile()
                   7797:     $i         - line number to update
                   7798: 
1.423     albertel 7799: =cut
                   7800: 
1.376     albertel 7801: sub scantron_clear_skip {
                   7802:     my ($scanlines,$scan_data,$i)=@_;
                   7803:     if (exists($scanlines->{'skipped'}[$i])) {
                   7804: 	undef($scanlines->{'skipped'}[$i]);
                   7805: 	return 1;
                   7806:     }
                   7807:     return 0;
                   7808: }
                   7809: 
1.423     albertel 7810: =pod
                   7811: 
                   7812: =item scantron_filter_not_exam
                   7813: 
1.424     albertel 7814:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7815:    filter out resources that are not marked as 'exam' mode
                   7816: 
1.423     albertel 7817: =cut
                   7818: 
1.334     albertel 7819: sub scantron_filter_not_exam {
                   7820:     my ($curres)=@_;
                   7821:     
                   7822:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7823: 	# if the user has asked to not have either hidden
                   7824: 	# or 'randomout' controlled resources to be graded
                   7825: 	# don't include them
                   7826: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7827: 	    && $curres->randomout) {
                   7828: 	    return 0;
                   7829: 	}
                   7830: 	return 1;
                   7831:     }
                   7832:     return 0;
                   7833: }
                   7834: 
1.423     albertel 7835: =pod
                   7836: 
                   7837: =item scantron_validate_sequence
                   7838: 
1.424     albertel 7839:     Validates the selected sequence, checking for resource that are
                   7840:     not set to exam mode.
                   7841: 
1.423     albertel 7842: =cut
                   7843: 
1.334     albertel 7844: sub scantron_validate_sequence {
                   7845:     my ($r,$currentphase) = @_;
                   7846: 
                   7847:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7848:     unless (ref($navmap)) {
                   7849:         $r->print(&navmap_errormsg());
                   7850:         return (1,$currentphase);
                   7851:     }
1.334     albertel 7852:     my (undef,undef,$sequence)=
                   7853: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7854: 
                   7855:     my $map=$navmap->getResourceByUrl($sequence);
                   7856: 
                   7857:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7858:                                     value="ignore" />');
                   7859:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7860: 	my @resources=
                   7861: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7862: 	if (@resources) {
1.675     bisitz   7863: 	    $r->print(
                   7864:                 '<p class="LC_warning">'
                   7865:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7866:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7867:                    .' work correctly.')
                   7868:                .'</p>'
                   7869:             );
1.334     albertel 7870: 	    return (1,$currentphase);
                   7871: 	}
                   7872:     }
                   7873: 
                   7874:     return (0,$currentphase+1);
                   7875: }
                   7876: 
1.423     albertel 7877: 
                   7878: 
1.157     albertel 7879: sub scantron_validate_ID {
1.770     raeburn  7880:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 7881:     
                   7882:     #get student info
                   7883:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7884:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  7885:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 7886: 
                   7887:     #get scantron line setup
1.754     raeburn  7888:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7889:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7890: 
                   7891:     my $nav_error;
1.649     raeburn  7892:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7893:     if ($nav_error) {
                   7894:         $r->print(&navmap_errormsg());
                   7895:         return(1,$currentphase);
                   7896:     }
1.157     albertel 7897: 
                   7898:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  7899:     my $unsavedskips = 0;
1.157     albertel 7900:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7901: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7902: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7903: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7904: 						 $scan_data);
                   7905: 	my $id=$$scan_record{'scantron.ID'};
                   7906: 	my $found;
                   7907: 	foreach my $checkid (keys(%idmap)) {
                   7908: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7909: 	}
                   7910: 	if ($found) {
                   7911: 	    my $username=$idmap{$found};
1.770     raeburn  7912:             if ($checksec) {
                   7913:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   7914:                     my $stusec = $classlist->{$username}->[$secidx];
                   7915:                     if ($stusec ne $checksec) {
                   7916:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7917:                             my $skip=1;
                   7918:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7919:                             if (ref($skipbysec) eq 'HASH') {
                   7920:                                 if ($stusec eq '') {
                   7921:                                     $skipbysec->{'none'} ++;
                   7922:                                 } else {
                   7923:                                     $skipbysec->{$stusec} ++;
                   7924:                                 }
                   7925:                             }
                   7926:                             $unsavedskips ++;
                   7927:                             next;
                   7928:                         }
                   7929:                     }
                   7930:                 }
                   7931:             }
1.157     albertel 7932: 	    if ($found{'ids'}{$found}) {
                   7933: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7934: 					 $line,'duplicateID',$found);
1.770     raeburn  7935:                 if ($unsavedskips) {
                   7936:                     &scantron_putfile($scanlines,$scan_data);
                   7937:                     $unsavedskips = 0;
                   7938:                 }
1.194     albertel 7939: 		return(1,$currentphase);
1.157     albertel 7940: 	    } elsif ($found{'usernames'}{$username}) {
                   7941: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7942: 					 $line,'duplicateID',$username);
1.770     raeburn  7943:                 if ($unsavedskips) {
                   7944:                     &scantron_putfile($scanlines,$scan_data);
                   7945:                     $unsavedskips = 0;
                   7946:                 }
1.194     albertel 7947: 		return(1,$currentphase);
1.157     albertel 7948: 	    }
1.186     albertel 7949: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7950: 	    $found{'ids'}{$found}++;
                   7951: 	    $found{'usernames'}{$username}++;
                   7952: 	} else {
                   7953: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7954: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  7955:                 if (($checksec && $username ne '')) {
                   7956:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   7957:                         my $stusec = $classlist->{$username}->[$secidx];
                   7958:                         if ($stusec ne $checksec) {
                   7959:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7960:                                 my $skip=1;
                   7961:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7962:                                 if (ref($skipbysec) eq 'HASH') {
                   7963:                                     if ($stusec eq '') {
                   7964:                                         $skipbysec->{'none'} ++;
                   7965:                                     } else {
                   7966:                                         $skipbysec->{$stusec} ++;
                   7967:                                     }
                   7968:                                 }
                   7969:                                 $unsavedskips ++;
                   7970:                                 next;
                   7971:                             }
                   7972:                         }
                   7973:                     }
                   7974: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 7975: 		    &scantron_get_correction($r,$i,$scan_record,
                   7976: 					     \%scantron_config,
                   7977: 					     $line,'duplicateID',$username);
1.770     raeburn  7978:                     if ($unsavedskips) {
                   7979:                         &scantron_putfile($scanlines,$scan_data);
                   7980:                         $unsavedskips = 0;
                   7981:                     }
1.194     albertel 7982: 		    return(1,$currentphase);
1.157     albertel 7983: 		} elsif (!defined($username)) {
                   7984: 		    &scantron_get_correction($r,$i,$scan_record,
                   7985: 					     \%scantron_config,
                   7986: 					     $line,'incorrectID');
1.770     raeburn  7987:                     if ($unsavedskips) {
                   7988:                         &scantron_putfile($scanlines,$scan_data);
                   7989:                         $unsavedskips = 0;
                   7990:                     }
1.194     albertel 7991: 		    return(1,$currentphase);
1.157     albertel 7992: 		}
                   7993: 		$found{'usernames'}{$username}++;
                   7994: 	    } else {
                   7995: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7996: 					 $line,'incorrectID');
1.770     raeburn  7997:                 if ($unsavedskips) {
                   7998:                     &scantron_putfile($scanlines,$scan_data);
                   7999:                     $unsavedskips = 0;
                   8000:                 }
1.194     albertel 8001: 		return(1,$currentphase);
1.157     albertel 8002: 	    }
                   8003: 	}
                   8004:     }
1.770     raeburn  8005:     if ($unsavedskips) {
                   8006:         &scantron_putfile($scanlines,$scan_data);
                   8007:         $unsavedskips = 0;
                   8008:     }
1.157     albertel 8009:     return (0,$currentphase+1);
                   8010: }
                   8011: 
1.770     raeburn  8012: sub scantron_get_sections {
                   8013:     my %bysec;
                   8014:     if ($env{'form.scantron_format'} ne '') {
                   8015:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   8016:         my ($scanlines,$scan_data)=&scantron_getfile();
                   8017:         my $classlist=&Apache::loncoursedata::get_classlist();
                   8018:         my %idmap=&username_to_idmap($classlist);
                   8019:         foreach my $key (keys(%idmap)) {
                   8020:             my $lckey = lc($key);
                   8021:             $idmap{$lckey} = $idmap{$key};
                   8022:         }
                   8023:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   8024:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8025:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   8026:             if ($line=~/^[\s\cz]*$/) { next; }
                   8027:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8028:                                                      $scan_data);
                   8029:             my $id=lc($$scan_record{'scantron.ID'});
                   8030:             if (exists($idmap{$id})) {
                   8031:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   8032:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   8033:                     if ($stusec eq '') {
                   8034:                         $bysec{'none'} ++;
                   8035:                     } else {
                   8036:                         $bysec{$stusec} ++;
                   8037:                     }
                   8038:                 }
                   8039:             }
                   8040:         }
                   8041:     }
                   8042:     return %bysec;
                   8043: }
1.423     albertel 8044: 
1.157     albertel 8045: sub scantron_get_correction {
1.691     raeburn  8046:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   8047:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 8048: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 8049: #to show both the current line and the previous one and allow skipping
                   8050: #the previous one or the current one
                   8051: 
1.333     albertel 8052:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   8053:         $r->print(
                   8054:             '<p class="LC_warning">'
                   8055:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   8056:                 "<b>$error</b>",
                   8057:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   8058:            ."</p> \n");
1.157     albertel 8059:     } else {
1.658     bisitz   8060:         $r->print(
                   8061:             '<p class="LC_warning">'
                   8062:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8063:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8064:            ."</p> \n");
                   8065:     }
                   8066:     my $message =
                   8067:         '<p>'
                   8068:        .&mt('The ID on the form is [_1]',
                   8069:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8070:        .'<br />'
1.665     raeburn  8071:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   8072:             $$scan_record{'scantron.LastName'},
                   8073:             $$scan_record{'scantron.FirstName'})
                   8074:        .'</p>';
1.242     albertel 8075: 
1.157     albertel 8076:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8077:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8078:                            # Array populated for doublebubble or
                   8079:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8080:                            # to validate radio button checking   
                   8081: 
1.157     albertel 8082:     if ($error =~ /ID$/) {
1.186     albertel 8083: 	if ($error eq 'incorrectID') {
1.658     bisitz   8084:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8085: 		      "</p>\n");
1.157     albertel 8086: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   8087:             $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 8088: 	}
1.242     albertel 8089: 	$r->print($message);
1.492     albertel 8090: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8091: 	$r->print("\n<ul><li> ");
                   8092: 	#FIXME it would be nice if this sent back the user ID and
                   8093: 	#could do partial userID matches
                   8094: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8095: 				       'scantron_username','scantron_domain'));
                   8096: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   8097: 	$r->print("\n:\n".
1.257     albertel 8098: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8099: 
                   8100: 	$r->print('</li>');
1.186     albertel 8101:     } elsif ($error =~ /CODE$/) {
                   8102: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   8103: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8104: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   8105: 	    $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 8106: 	}
1.658     bisitz   8107: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   8108: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8109:                  ."</p>\n");
1.242     albertel 8110: 	$r->print($message);
1.658     bisitz   8111: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8112: 	$r->print("\n<br /> ");
1.194     albertel 8113: 	my $i=0;
1.273     albertel 8114: 	if ($error eq 'incorrectCODE' 
                   8115: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8116: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8117: 	    if ($closest > 0) {
                   8118: 		foreach my $testcode (@{$closest}) {
                   8119: 		    my $checked='';
1.569     bisitz   8120: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8121: 		    $r->print("
                   8122:    <label>
1.569     bisitz   8123:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8124:        ".&mt("Use the similar CODE [_1] instead.",
                   8125: 	    "<b><tt>".$testcode."</tt></b>")."
                   8126:     </label>
                   8127:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8128: 		    $r->print("\n<br />");
                   8129: 		    $i++;
                   8130: 		}
1.194     albertel 8131: 	    }
                   8132: 	}
1.273     albertel 8133: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8134: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8135: 	    $r->print("
                   8136:     <label>
1.569     bisitz   8137:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  8138:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8139: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8140:     </label>");
1.273     albertel 8141: 	    $r->print("\n<br />");
                   8142: 	}
1.194     albertel 8143: 
1.597     wenzelju 8144: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8145: function change_radio(field) {
1.190     albertel 8146:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8147:     var i;
                   8148:     for (i=0;i<slct.length;i++) {
                   8149:         if (slct[i].value==field) { slct[i].checked=true; }
                   8150:     }
                   8151: }
                   8152: ENDSCRIPT
1.187     albertel 8153: 	my $href="/adm/pickcode?".
1.359     www      8154: 	   "form=".&escape("scantronupload").
                   8155: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8156: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8157: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8158: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8159: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8160: 	    $r->print("
                   8161:     <label>
                   8162:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8163:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8164: 	     "<a target='_blank' href='$href'>","</a>")."
                   8165:     </label> 
1.558     bisitz   8166:     ".&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 8167: 	    $r->print("\n<br />");
                   8168: 	}
1.492     albertel 8169: 	$r->print("
                   8170:     <label>
                   8171:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8172:        ".&mt("Use [_1] as the CODE.",
                   8173: 	     "</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 8174: 	$r->print("\n<br /><br />");
1.157     albertel 8175:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   8176: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8177: 
                   8178: 	# The form field scantron_questions is acutally a list of line numbers.
                   8179: 	# represented by this form so:
                   8180: 
1.691     raeburn  8181: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8182:                                                 $respnumlookup,$startline);
1.497     foxr     8183: 
1.157     albertel 8184: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8185: 		  $line_list.'" />');
1.242     albertel 8186: 	$r->print($message);
1.492     albertel 8187: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8188: 	foreach my $question (@{$arg}) {
1.503     raeburn  8189: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8190:                                                    $scan_record, $error,
                   8191:                                                    $randomorder,$randompick,
                   8192:                                                    $respnumlookup,$startline);
1.524     raeburn  8193:             push(@lines_to_correct,@linenums);
1.157     albertel 8194: 	}
1.503     raeburn  8195:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8196:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   8197: 	$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 8198: 	$r->print($message);
1.492     albertel 8199: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8200: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8201: 
1.503     raeburn  8202: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8203: 	# a list of question numbers. Therefore:
                   8204: 	#
1.691     raeburn  8205: 
                   8206: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8207:                                                 $respnumlookup,$startline);
1.497     foxr     8208: 
1.157     albertel 8209: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8210: 		  $line_list.'" />');
1.157     albertel 8211: 	foreach my $question (@{$arg}) {
1.503     raeburn  8212: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8213:                                                    $scan_record, $error,
                   8214:                                                    $randomorder,$randompick,
                   8215:                                                    $respnumlookup,$startline);
1.524     raeburn  8216:             push(@lines_to_correct,@linenums);
1.157     albertel 8217: 	}
1.503     raeburn  8218:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8219:     } else {
                   8220: 	$r->print("\n<ul>");
                   8221:     }
                   8222:     $r->print("\n</li></ul>");
1.497     foxr     8223: }
                   8224: 
1.503     raeburn  8225: sub verify_bubbles_checked {
                   8226:     my (@ansnums) = @_;
                   8227:     my $ansnumstr = join('","',@ansnums);
                   8228:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  8229:     &js_escape(\$warning);
1.767     raeburn  8230:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8231: function verify_bubble_radio(form) {
                   8232:     var ansnumArray = new Array ("$ansnumstr");
                   8233:     var need_bubble_count = 0;
                   8234:     for (var i=0; i<ansnumArray.length; i++) {
                   8235:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8236:             var bubble_picked = 0; 
                   8237:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8238:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8239:                     bubble_picked = 1;
                   8240:                 }
                   8241:             }
                   8242:             if (bubble_picked == 0) {
                   8243:                 need_bubble_count ++;
                   8244:             }
                   8245:         }
                   8246:     }
                   8247:     if (need_bubble_count) {
                   8248:         alert("$warning");
                   8249:         return;
                   8250:     }
                   8251:     form.submit(); 
                   8252: }
                   8253: ENDSCRIPT
                   8254:     return $output;
                   8255: }
                   8256: 
1.497     foxr     8257: =pod
                   8258: 
                   8259: =item  questions_to_line_list
1.157     albertel 8260: 
1.497     foxr     8261: Converts a list of questions into a string of comma separated
                   8262: line numbers in the answer sheet used by the questions.  This is
                   8263: used to fill in the scantron_questions form field.
                   8264: 
                   8265:   Arguments:
                   8266:      questions    - Reference to an array of questions.
1.691     raeburn  8267:      randomorder  - True if randomorder in use.
                   8268:      randompick   - True if randompick in use.
                   8269:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8270:                      for current line to question number used for same question
                   8271:                      in "Master Seqence" (as seen by Course Coordinator).
                   8272:      startline    - Reference to hash where key is question number (0 is first)
                   8273:                     and key is number of first bubble line for current student
                   8274:                     or code-based randompick and/or randomorder.
1.693     raeburn  8275: 
1.497     foxr     8276: =cut
                   8277: 
                   8278: 
                   8279: sub questions_to_line_list {
1.691     raeburn  8280:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8281:     my @lines;
                   8282: 
1.503     raeburn  8283:     foreach my $item (@{$questions}) {
                   8284:         my $question = $item;
                   8285:         my ($first,$count,$last);
                   8286:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8287:             $question = $1;
                   8288:             my $subquestion = $2;
1.691     raeburn  8289:             my $responsenum = $question-1;
                   8290:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8291:                 $responsenum = $respnumlookup->{$question-1};
                   8292:                 if (ref($startline) eq 'HASH') {
                   8293:                     $first = $startline->{$question-1} + 1;
                   8294:                 }
                   8295:             } else {
                   8296:                 $first = $first_bubble_line{$responsenum} + 1;
                   8297:             }
                   8298:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8299:             my $subcount = 1;
                   8300:             while ($subcount<$subquestion) {
                   8301:                 $first += $subans[$subcount-1];
                   8302:                 $subcount ++;
                   8303:             }
                   8304:             $count = $subans[$subquestion-1];
                   8305:         } else {
1.691     raeburn  8306:             my $responsenum = $question-1;
                   8307:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8308:                 $responsenum = $respnumlookup->{$question-1};
                   8309:                 if (ref($startline) eq 'HASH') {
                   8310:                     $first = $startline->{$question-1} + 1;
                   8311:                 }
                   8312:             } else {
                   8313:                 $first = $first_bubble_line{$responsenum} + 1;
                   8314:             }
                   8315: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8316:         }
1.506     raeburn  8317:         $last = $first+$count-1;
1.503     raeburn  8318:         push(@lines, ($first..$last));
1.497     foxr     8319:     }
                   8320:     return join(',', @lines);
                   8321: }
                   8322: 
                   8323: =pod 
                   8324: 
                   8325: =item prompt_for_corrections
                   8326: 
                   8327: Prompts for a potentially multiline correction to the
                   8328: user's bubbling (factors out common code from scantron_get_correction
                   8329: for multi and missing bubble cases).
                   8330: 
                   8331:  Arguments:
                   8332:    $r           - Apache request object.
                   8333:    $question    - The question number to prompt for.
                   8334:    $scan_config - The scantron file configuration hash.
                   8335:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8336:    $error       - Type of error
1.691     raeburn  8337:    $randomorder - True if randomorder in use.
                   8338:    $randompick  - True if randompick in use.
                   8339:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8340:                     for current line to question number used for same question
                   8341:                     in "Master Seqence" (as seen by Course Coordinator).
                   8342:    $startline   - Reference to hash where key is question number (0 is first)
                   8343:                   and value is number of first bubble line for current student
                   8344:                   or code-based randompick and/or randomorder.
                   8345: 
1.497     foxr     8346: 
                   8347:  Implicit inputs:
                   8348:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8349:                                   Numbered from 0 (but question numbers are from
                   8350:                                   1.
                   8351:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8352:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8353:                                   type problems render as separate sub-questions, 
1.503     raeburn  8354:                                   in exam mode. This hash contains a 
                   8355:                                   comma-separated list of the lines per 
                   8356:                                   sub-question.
1.510     raeburn  8357:    %responsetype_per_response   - essayresponse, formularesponse,
                   8358:                                   stringresponse, imageresponse, reactionresponse,
                   8359:                                   and organicresponse type problem parts can have
1.503     raeburn  8360:                                   multiple lines per response if the weight
                   8361:                                   assigned exceeds 10.  In this case, only
                   8362:                                   one bubble per line is permitted, but more 
                   8363:                                   than one line might contain bubbles, e.g.
                   8364:                                   bubbling of: line 1 - J, line 2 - J, 
                   8365:                                   line 3 - B would assign 22 points.  
1.497     foxr     8366: 
                   8367: =cut
                   8368: 
                   8369: sub prompt_for_corrections {
1.691     raeburn  8370:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8371:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8372:     my ($current_line,$lines);
                   8373:     my @linenums;
                   8374:     my $questionnum = $question;
1.691     raeburn  8375:     my ($first,$responsenum);
1.503     raeburn  8376:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8377:         $question = $1;
                   8378:         my $subquestion = $2;
1.691     raeburn  8379:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8380:             $responsenum = $respnumlookup->{$question-1};
                   8381:             if (ref($startline) eq 'HASH') {
                   8382:                 $first = $startline->{$question-1};
                   8383:             }
                   8384:         } else {
                   8385:             $responsenum = $question-1;
1.714     raeburn  8386:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8387:         }
                   8388:         $current_line = $first + 1 ;
                   8389:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8390:         my $subcount = 1;
                   8391:         while ($subcount<$subquestion) {
                   8392:             $current_line += $subans[$subcount-1];
                   8393:             $subcount ++;
                   8394:         }
                   8395:         $lines = $subans[$subquestion-1];
                   8396:     } else {
1.691     raeburn  8397:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8398:             $responsenum = $respnumlookup->{$question-1};
                   8399:             if (ref($startline) eq 'HASH') { 
                   8400:                 $first = $startline->{$question-1};
                   8401:             }
                   8402:         } else {
                   8403:             $responsenum = $question-1;
                   8404:             $first = $first_bubble_line{$responsenum};
                   8405:         }
                   8406:         $current_line = $first + 1;
                   8407:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8408:     }
1.497     foxr     8409:     if ($lines > 1) {
1.503     raeburn  8410:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8411:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8412:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8413:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8414:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8415:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8416:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8417:             $r->print(
                   8418:                 &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)
                   8419:                .'<br /><br />'
                   8420:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8421:                .'<br />'
                   8422:                .&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.')
                   8423:                .'<br />'
                   8424:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8425:                .'<br /><br />'
                   8426:             );
1.503     raeburn  8427:         } else {
                   8428:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8429:         }
1.497     foxr     8430:     }
                   8431:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8432:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8433: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8434: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8435:         push(@linenums,$current_line);
1.497     foxr     8436: 	$current_line++;
                   8437:     }
                   8438:     if ($lines > 1) {
                   8439: 	$r->print("<hr /><br />");
                   8440:     }
1.503     raeburn  8441:     return @linenums;
1.157     albertel 8442: }
1.423     albertel 8443: 
                   8444: =pod
                   8445: 
                   8446: =item scantron_bubble_selector
                   8447:   
                   8448:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8449:    possibly showing the existing the selected bubbles if known
1.423     albertel 8450: 
                   8451:  Arguments:
                   8452:     $r           - Apache request object
1.754     raeburn  8453:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8454:     $line        - Number of the line being displayed.
1.503     raeburn  8455:     $questionnum - Question number (may include subquestion)
                   8456:     $error       - Type of error.
1.497     foxr     8457:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8458: 
                   8459: =cut
                   8460: 
1.157     albertel 8461: sub scantron_bubble_selector {
1.503     raeburn  8462:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8463:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8464: 
                   8465:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8466:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8467:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8468:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8469:             $max=$$scan_config{'BubblesPerRow'};
                   8470:             if (($scmode eq 'number') && ($max > 10)) {
                   8471:                 $max = 10;
                   8472:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8473:                 $max = 26;
                   8474:             }
                   8475:         } else {
                   8476:             $max = 10;
                   8477:         }
                   8478:     }
1.274     albertel 8479: 
1.157     albertel 8480:     my @alphabet=('A'..'Z');
1.503     raeburn  8481:     $r->print(&Apache::loncommon::start_data_table().
                   8482:               &Apache::loncommon::start_data_table_row());
                   8483:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8484:     for (my $i=0;$i<$max+1;$i++) {
                   8485: 	$r->print("\n".'<td align="center">');
                   8486: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8487: 	else { $r->print('&nbsp;'); }
                   8488: 	$r->print('</td>');
                   8489:     }
1.503     raeburn  8490:     $r->print(&Apache::loncommon::end_data_table_row().
                   8491:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8492:     for (my $i=0;$i<$max;$i++) {
                   8493: 	$r->print("\n".
                   8494: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8495: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8496:     }
1.503     raeburn  8497:     my $nobub_checked = ' ';
                   8498:     if ($error eq 'missingbubble') {
                   8499:         $nobub_checked = ' checked = "checked" ';
                   8500:     }
                   8501:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8502: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8503:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8504:               $line.'" value="'.$questionnum.'" /></td>');
                   8505:     $r->print(&Apache::loncommon::end_data_table_row().
                   8506:               &Apache::loncommon::end_data_table());
1.157     albertel 8507: }
                   8508: 
1.423     albertel 8509: =pod
                   8510: 
                   8511: =item num_matches
                   8512: 
1.424     albertel 8513:    Counts the number of characters that are the same between the two arguments.
                   8514: 
                   8515:  Arguments:
                   8516:    $orig - CODE from the scanline
                   8517:    $code - CODE to match against
                   8518: 
                   8519:  Returns:
                   8520:    $count - integer count of the number of same characters between the
                   8521:             two arguments
                   8522: 
1.423     albertel 8523: =cut
                   8524: 
1.194     albertel 8525: sub num_matches {
                   8526:     my ($orig,$code) = @_;
                   8527:     my @code=split(//,$code);
                   8528:     my @orig=split(//,$orig);
                   8529:     my $same=0;
                   8530:     for (my $i=0;$i<scalar(@code);$i++) {
                   8531: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8532:     }
                   8533:     return $same;
                   8534: }
                   8535: 
1.423     albertel 8536: =pod
                   8537: 
                   8538: =item scantron_get_closely_matching_CODEs
                   8539: 
1.424     albertel 8540:    Cycles through all CODEs and finds the set that has the greatest
                   8541:    number of same characters as the provided CODE
                   8542: 
                   8543:  Arguments:
                   8544:    $allcodes - hash ref returned by &get_codes()
                   8545:    $CODE     - CODE from the current scanline
                   8546: 
                   8547:  Returns:
                   8548:    2 element list
                   8549:     - first elements is number of how closely matching the best fit is 
                   8550:       (5 means best set has 5 matching characters)
                   8551:     - second element is an arrary ref containing the set of valid CODEs
                   8552:       that best fit the passed in CODE
                   8553: 
1.423     albertel 8554: =cut
                   8555: 
1.194     albertel 8556: sub scantron_get_closely_matching_CODEs {
                   8557:     my ($allcodes,$CODE)=@_;
                   8558:     my @CODEs;
                   8559:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8560: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8561:     }
                   8562: 
                   8563:     return ($#CODEs,$CODEs[-1]);
                   8564: }
                   8565: 
1.423     albertel 8566: =pod
                   8567: 
                   8568: =item get_codes
                   8569: 
1.424     albertel 8570:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8571:    set of remembered CODEs.
                   8572: 
                   8573:  Arguments:
                   8574:   $old_name - name of the set of remembered CODEs
                   8575:   $cdom     - domain of the course
                   8576:   $cnum     - internal course name
                   8577: 
                   8578:  Returns:
                   8579:   %allcodes - keys are the valid CODEs, values are all 1
                   8580: 
1.423     albertel 8581: =cut
                   8582: 
1.194     albertel 8583: sub get_codes {
1.280     foxr     8584:     my ($old_name, $cdom, $cnum) = @_;
                   8585:     if (!$old_name) {
                   8586: 	$old_name=$env{'form.scantron_CODElist'};
                   8587:     }
                   8588:     if (!$cdom) {
                   8589: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8590:     }
                   8591:     if (!$cnum) {
                   8592: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8593:     }
1.278     albertel 8594:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8595: 				    $cdom,$cnum);
                   8596:     my %allcodes;
                   8597:     if ($result{"type\0$old_name"} eq 'number') {
                   8598: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8599:     } else {
                   8600: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8601:     }
1.194     albertel 8602:     return %allcodes;
                   8603: }
                   8604: 
1.423     albertel 8605: =pod
                   8606: 
                   8607: =item scantron_validate_CODE
                   8608: 
1.424     albertel 8609:    Validates all scanlines in the selected file to not have any
                   8610:    invalid or underspecified CODEs and that none of the codes are
                   8611:    duplicated if this was requested.
                   8612: 
1.423     albertel 8613: =cut
                   8614: 
1.157     albertel 8615: sub scantron_validate_CODE {
                   8616:     my ($r,$currentphase) = @_;
1.754     raeburn  8617:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8618:     if ($scantron_config{'CODElocation'} &&
                   8619: 	$scantron_config{'CODEstart'} &&
                   8620: 	$scantron_config{'CODElength'}) {
1.257     albertel 8621: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8622: 	    &FIXME_blow_up()
                   8623: 	}
                   8624:     } else {
                   8625: 	return (0,$currentphase+1);
                   8626:     }
                   8627:     
                   8628:     my %usedCODEs;
                   8629: 
1.194     albertel 8630:     my %allcodes=&get_codes();
1.186     albertel 8631: 
1.582     raeburn  8632:     my $nav_error;
1.649     raeburn  8633:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8634:     if ($nav_error) {
                   8635:         $r->print(&navmap_errormsg());
                   8636:         return(1,$currentphase);
                   8637:     }
1.447     foxr     8638: 
1.186     albertel 8639:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8640:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8641: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8642: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8643: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8644: 						 $scan_data);
                   8645: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8646: 	my $error=0;
1.224     albertel 8647: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8648: 	    &scantron_get_correction($r,$i,$scan_record,
                   8649: 				     \%scantron_config,
                   8650: 				     $line,'incorrectCODE',\%allcodes);
                   8651: 	    return(1,$currentphase);
                   8652: 	}
1.221     albertel 8653: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8654: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8655: 	    &scantron_get_correction($r,$i,$scan_record,
                   8656: 				     \%scantron_config,
1.194     albertel 8657: 				     $line,'incorrectCODE',\%allcodes);
                   8658: 	    return(1,$currentphase);
1.186     albertel 8659: 	}
1.214     albertel 8660: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8661: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8662: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8663: 	    &scantron_get_correction($r,$i,$scan_record,
                   8664: 				     \%scantron_config,
1.194     albertel 8665: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8666: 	    return(1,$currentphase);
1.186     albertel 8667: 	}
1.524     raeburn  8668: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8669:     }
1.157     albertel 8670:     return (0,$currentphase+1);
                   8671: }
                   8672: 
1.423     albertel 8673: =pod
                   8674: 
                   8675: =item scantron_validate_doublebubble
                   8676: 
1.424     albertel 8677:    Validates all scanlines in the selected file to not have any
                   8678:    bubble lines with multiple bubbles marked.
                   8679: 
1.423     albertel 8680: =cut
                   8681: 
1.157     albertel 8682: sub scantron_validate_doublebubble {
                   8683:     my ($r,$currentphase) = @_;
                   8684:     #get student info
                   8685:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8686:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8687:     my (undef,undef,$sequence)=
                   8688:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8689: 
                   8690:     #get scantron line setup
1.754     raeburn  8691:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8692:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8693: 
                   8694:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8695:     unless (ref($navmap)) {
                   8696:         $r->print(&navmap_errormsg());
                   8697:         return(1,$currentphase);
                   8698:     }
                   8699:     my $map=$navmap->getResourceByUrl($sequence);
                   8700:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8701:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8702:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8703:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8704: 
1.583     raeburn  8705:     my $nav_error;
1.691     raeburn  8706:     if (ref($map)) {
                   8707:         $randomorder = $map->randomorder();
                   8708:         $randompick = $map->randompick();
                   8709:         if ($randomorder || $randompick) {
                   8710:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8711:             if ($nav_error) {
                   8712:                 $r->print(&navmap_errormsg());
                   8713:                 return(1,$currentphase);
                   8714:             }
                   8715:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8716:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8717:         }
                   8718:     } else {
                   8719:         $r->print(&navmap_errormsg());
                   8720:         return(1,$currentphase);
                   8721:     }
                   8722: 
1.649     raeburn  8723:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8724:     if ($nav_error) {
                   8725:         $r->print(&navmap_errormsg());
                   8726:         return(1,$currentphase);
                   8727:     }
1.447     foxr     8728: 
1.157     albertel 8729:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8730: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8731: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8732: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8733: 						 $scan_data,undef,\%idmap,$randomorder,
                   8734:                                                  $randompick,$sequence,\@master_seq,
                   8735:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8736:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8737: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8738: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8739: 				 'doublebubble',
1.691     raeburn  8740: 				 $$scan_record{'scantron.doubleerror'},
                   8741:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8742:     	return (1,$currentphase);
                   8743:     }
                   8744:     return (0,$currentphase+1);
                   8745: }
                   8746: 
1.423     albertel 8747: 
1.503     raeburn  8748: sub scantron_get_maxbubble {
1.649     raeburn  8749:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8750:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8751: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8752: 	&restore_bubble_lines();
1.257     albertel 8753: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8754:     }
1.330     albertel 8755: 
1.447     foxr     8756:     my (undef, undef, $sequence) =
1.257     albertel 8757: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8758: 
1.447     foxr     8759:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8760:     unless (ref($navmap)) {
                   8761:         if (ref($nav_error)) {
                   8762:             $$nav_error = 1;
                   8763:         }
1.591     raeburn  8764:         return;
1.582     raeburn  8765:     }
1.191     albertel 8766:     my $map=$navmap->getResourceByUrl($sequence);
                   8767:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8768:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8769: 
                   8770:     &Apache::lonxml::clear_problem_counter();
                   8771: 
1.557     raeburn  8772:     my $uname       = $env{'user.name'};
                   8773:     my $udom        = $env{'user.domain'};
1.435     foxr     8774:     my $cid         = $env{'request.course.id'};
                   8775:     my $total_lines = 0;
                   8776:     %bubble_lines_per_response = ();
1.447     foxr     8777:     %first_bubble_line         = ();
1.503     raeburn  8778:     %subdivided_bubble_lines   = ();
                   8779:     %responsetype_per_response = ();
1.691     raeburn  8780:     %masterseq_id_responsenum  = ();
1.554     raeburn  8781: 
1.447     foxr     8782:     my $response_number = 0;
                   8783:     my $bubble_line     = 0;
1.191     albertel 8784:     foreach my $resource (@resources) {
1.691     raeburn  8785:         my $resid = $resource->id(); 
1.672     raeburn  8786:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8787:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8788:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8789: 	    foreach my $part_id (@{$parts}) {
                   8790:                 my $lines;
                   8791: 
                   8792: 	        # TODO - make this a persistent hash not an array.
                   8793: 
                   8794:                 # optionresponse, matchresponse and rankresponse type items 
                   8795:                 # render as separate sub-questions in exam mode.
                   8796:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8797:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8798:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8799:                     my ($numbub,$numshown);
                   8800:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8801:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8802:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8803:                         }
                   8804:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8805:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8806:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8807:                         }
                   8808:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8809:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8810:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8811:                         }
                   8812:                     }
                   8813:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8814:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8815:                     }
1.649     raeburn  8816:                     my $bubbles_per_row =
                   8817:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8818:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8819:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8820:                         $inner_bubble_lines++;
                   8821:                     }
                   8822:                     for (my $i=0; $i<$numshown; $i++) {
                   8823:                         $subdivided_bubble_lines{$response_number} .= 
                   8824:                             $inner_bubble_lines.',';
                   8825:                     }
                   8826:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8827:                     $lines = $numshown * $inner_bubble_lines;
                   8828:                 } else {
                   8829:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8830:                 }
1.542     raeburn  8831: 
                   8832:                 $first_bubble_line{$response_number} = $bubble_line;
                   8833: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8834:                 $responsetype_per_response{$response_number} = 
                   8835:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8836:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8837: 	        $response_number++;
                   8838: 
                   8839: 	        $bubble_line +=  $lines;
                   8840: 	        $total_lines +=  $lines;
                   8841: 	    }
                   8842:         }
                   8843:     }
1.552     raeburn  8844:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8845: 
                   8846:     &save_bubble_lines();
                   8847:     $env{'form.scantron_maxbubble'} =
                   8848: 	$total_lines;
                   8849:     return $env{'form.scantron_maxbubble'};
                   8850: }
1.523     raeburn  8851: 
1.649     raeburn  8852: sub bubblesheet_bubbles_per_row {
                   8853:     my ($scantron_config) = @_;
                   8854:     my $bubbles_per_row;
                   8855:     if (ref($scantron_config) eq 'HASH') {
                   8856:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8857:     }
                   8858:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8859:         $bubbles_per_row = 10;
                   8860:     }
                   8861:     return $bubbles_per_row;
                   8862: }
                   8863: 
1.157     albertel 8864: sub scantron_validate_missingbubbles {
                   8865:     my ($r,$currentphase) = @_;
                   8866:     #get student info
                   8867:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8868:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8869:     my (undef,undef,$sequence)=
                   8870:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8871: 
                   8872:     #get scantron line setup
1.754     raeburn  8873:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8874:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8875: 
                   8876:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8877:     unless (ref($navmap)) {
                   8878:         $r->print(&navmap_errormsg());
                   8879:         return(1,$currentphase);
                   8880:     }
                   8881: 
                   8882:     my $map=$navmap->getResourceByUrl($sequence);
                   8883:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8884:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8885:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8886:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8887: 
1.582     raeburn  8888:     my $nav_error;
1.691     raeburn  8889:     if (ref($map)) {
                   8890:         $randomorder = $map->randomorder();
                   8891:         $randompick = $map->randompick();
                   8892:         if ($randomorder || $randompick) {
                   8893:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8894:             if ($nav_error) {
                   8895:                 $r->print(&navmap_errormsg());
                   8896:                 return(1,$currentphase);
                   8897:             }
                   8898:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8899:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8900:         }
                   8901:     } else {
                   8902:         $r->print(&navmap_errormsg());
                   8903:         return(1,$currentphase);
                   8904:     }
                   8905: 
                   8906: 
1.649     raeburn  8907:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8908:     if ($nav_error) {
1.691     raeburn  8909:         $r->print(&navmap_errormsg());
1.693     raeburn  8910:         return(1,$currentphase);
1.582     raeburn  8911:     }
1.691     raeburn  8912: 
1.157     albertel 8913:     if (!$max_bubble) { $max_bubble=2**31; }
                   8914:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8915: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8916: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8917: 	my $scan_record =
                   8918:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8919: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8920:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8921:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8922: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8923: 	my @to_correct;
1.470     foxr     8924: 	
                   8925: 	# Probably here's where the error is...
                   8926: 
1.157     albertel 8927: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8928:             my $lastbubble;
                   8929:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8930:                my $question = $1;
                   8931:                my $subquestion = $2;
1.691     raeburn  8932:                my ($first,$responsenum);
                   8933:                if ($randomorder || $randompick) {
                   8934:                    $responsenum = $respnumlookup{$question-1};
                   8935:                    $first = $startline{$question-1};
                   8936:                } else {
                   8937:                    $responsenum = $question-1; 
                   8938:                    $first = $first_bubble_line{$responsenum};
                   8939:                }
                   8940:                if (!defined($first)) { next; }
                   8941:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8942:                my $subcount = 1;
                   8943:                while ($subcount<$subquestion) {
                   8944:                    $first += $subans[$subcount-1];
                   8945:                    $subcount ++;
                   8946:                }
                   8947:                my $count = $subans[$subquestion-1];
                   8948:                $lastbubble = $first + $count;
                   8949:             } else {
1.691     raeburn  8950:                my ($first,$responsenum);
                   8951:                if ($randomorder || $randompick) {
                   8952:                    $responsenum = $respnumlookup{$missing-1};
                   8953:                    $first = $startline{$missing-1};
                   8954:                } else {
                   8955:                    $responsenum = $missing-1;
                   8956:                    $first = $first_bubble_line{$responsenum};
                   8957:                }
                   8958:                if (!defined($first)) { next; }
                   8959:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8960:             }
                   8961:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8962: 	    push(@to_correct,$missing);
                   8963: 	}
                   8964: 	if (@to_correct) {
                   8965: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8966: 				     $line,'missingbubble',\@to_correct,
                   8967:                                      $randomorder,$randompick,\%respnumlookup,
                   8968:                                      \%startline);
1.157     albertel 8969: 	    return (1,$currentphase);
                   8970: 	}
                   8971: 
                   8972:     }
                   8973:     return (0,$currentphase+1);
                   8974: }
                   8975: 
1.663     raeburn  8976: sub hand_bubble_option {
                   8977:     my (undef, undef, $sequence) =
                   8978:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8979:     return if ($sequence eq '');
                   8980:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8981:     unless (ref($navmap)) {
                   8982:         return;
                   8983:     }
                   8984:     my $needs_hand_bubbles;
                   8985:     my $map=$navmap->getResourceByUrl($sequence);
                   8986:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8987:     foreach my $res (@resources) {
                   8988:         if (ref($res)) {
                   8989:             if ($res->is_problem()) {
                   8990:                 my $partlist = $res->parts();
                   8991:                 foreach my $part (@{ $partlist }) {
                   8992:                     my @types = $res->responseType($part);
                   8993:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8994:                         $needs_hand_bubbles = 1;
                   8995:                         last;
                   8996:                     }
                   8997:                 }
                   8998:             }
                   8999:         }
                   9000:     }
                   9001:     if ($needs_hand_bubbles) {
1.754     raeburn  9002:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  9003:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9004:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   9005:                &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 />').
                   9006:                '<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  9007:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  9008:     }
                   9009:     return;
                   9010: }
1.423     albertel 9011: 
1.82      albertel 9012: sub scantron_process_students {
1.608     www      9013:     my ($r,$symb) = @_;
1.513     foxr     9014: 
1.257     albertel 9015:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     9016:     if (!$symb) {
                   9017: 	return '';
                   9018:     }
1.324     albertel 9019:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 9020: 
1.754     raeburn  9021:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  9022:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 9023:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 9024:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9025:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 9026:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9027:     unless (ref($navmap)) {
                   9028:         $r->print(&navmap_errormsg());
                   9029:         return '';
1.691     raeburn  9030:     }
1.83      albertel 9031:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9032:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  9033:         %grader_randomlists_by_symb);
1.677     raeburn  9034:     if (ref($map)) {
                   9035:         $randomorder = $map->randomorder();
1.689     raeburn  9036:         $randompick = $map->randompick();
1.691     raeburn  9037:     } else {
                   9038:         $r->print(&navmap_errormsg());
                   9039:         return '';
1.677     raeburn  9040:     }
1.691     raeburn  9041:     my $nav_error;
1.83      albertel 9042:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9043:     if ($randomorder || $randompick) {
                   9044:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9045:         if ($nav_error) {
                   9046:             $r->print(&navmap_errormsg());
                   9047:             return '';
                   9048:         }
                   9049:     }
1.557     raeburn  9050:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  9051:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  9052: 
1.554     raeburn  9053:     my ($uname,$udom);
1.82      albertel 9054:     my $result= <<SCANTRONFORM;
1.81      albertel 9055: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   9056:   <input type="hidden" name="command" value="scantron_configphase" />
                   9057:   $default_form_data
                   9058: SCANTRONFORM
1.82      albertel 9059:     $r->print($result);
                   9060: 
1.770     raeburn  9061:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 9062:     my @delayqueue;
1.542     raeburn  9063:     my (%completedstudents,%scandata);
1.770     raeburn  9064: 
1.520     www      9065:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9066:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9067:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   9068:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9069:     $r->print('<br />');
1.140     albertel 9070:     my $start=&Time::HiRes::time();
1.158     albertel 9071:     my $i=-1;
1.542     raeburn  9072:     my $started;
1.447     foxr     9073: 
1.649     raeburn  9074:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9075:     if ($nav_error) {
                   9076:         $r->print(&navmap_errormsg());
                   9077:         return '';
                   9078:     }
                   9079: 
1.513     foxr     9080:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9081:     # the user and return.
                   9082: 
                   9083:     if ($ssi_error) {
                   9084: 	$r->print("</form>");
                   9085: 	&ssi_print_error($r);
1.520     www      9086:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9087: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9088:     }
1.447     foxr     9089: 
1.755     raeburn  9090:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9091:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  9092:     my %orderedforcode;
1.542     raeburn  9093: 
1.157     albertel 9094:     while ($i<$scanlines->{'count'}) {
                   9095:  	($uname,$udom)=('','');
                   9096:  	$i++;
1.200     albertel 9097:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9098:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9099: 	if ($started) {
1.667     www      9100: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9101: 	}
                   9102: 	$started=1;
1.691     raeburn  9103:         my %respnumlookup = ();
                   9104:         my %startline = ();
                   9105:         my $total;
1.157     albertel 9106:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9107:                                                  $scan_data,undef,\%idmap,$randomorder,
                   9108:                                                  $randompick,$sequence,\@master_seq,
                   9109:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9110:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9111:                                                  \$total);
1.157     albertel 9112:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9113:  					      \%idmap,$i)) {
                   9114:   	    &scantron_add_delay(\@delayqueue,$line,
                   9115:  				'Unable to find a student that matches',1);
                   9116:  	    next;
                   9117:   	}
                   9118:  	if (exists $completedstudents{$uname}) {
                   9119:  	    &scantron_add_delay(\@delayqueue,$line,
                   9120:  				'Student '.$uname.' has multiple sheets',2);
                   9121:  	    next;
                   9122:  	}
1.677     raeburn  9123:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  9124:         if (($checksec ne '') && ($checksec ne $usec)) {
                   9125:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   9126:                 &scantron_add_delay(\@delayqueue,$line,
                   9127:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   9128:                 next;
                   9129:             }
                   9130:         }
1.677     raeburn  9131:         my $user = $uname.':'.$usec;
1.157     albertel 9132:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9133: 
1.677     raeburn  9134:         my $scancode;
                   9135:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9136:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9137:             $scancode = $scan_record->{'scantron.CODE'};
                   9138:         } else {
                   9139:             $scancode = '';
                   9140:         }
                   9141: 
                   9142:         my @mapresources = @resources;
1.689     raeburn  9143:         if ($randomorder || $randompick) {
1.678     raeburn  9144:             @mapresources = 
1.691     raeburn  9145:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9146:                              \%orderedforcode);
1.677     raeburn  9147:         }
1.586     raeburn  9148:         my (%partids_by_symb,$res_error);
1.677     raeburn  9149:         foreach my $resource (@mapresources) {
1.586     raeburn  9150:             my $ressymb;
                   9151:             if (ref($resource)) {
                   9152:                 $ressymb = $resource->symb();
                   9153:             } else {
                   9154:                 $res_error = 1;
                   9155:                 last;
                   9156:             }
1.557     raeburn  9157:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9158:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9159:                 my $currcode;
                   9160:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9161:                     $currcode = $scancode;
                   9162:                 }
1.557     raeburn  9163:                 my ($analysis,$parts) =
1.672     raeburn  9164:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  9165:                                               $uname,$udom,undef,$bubbles_per_row,
                   9166:                                               $currcode);
1.557     raeburn  9167:                 $partids_by_symb{$ressymb} = $parts;
                   9168:             } else {
                   9169:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9170:             }
1.554     raeburn  9171:         }
                   9172: 
1.586     raeburn  9173:         if ($res_error) {
                   9174:             &scantron_add_delay(\@delayqueue,$line,
                   9175:                                 'An error occurred while grading student '.$uname,2);
                   9176:             next;
                   9177:         }
                   9178: 
1.330     albertel 9179: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9180:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9181: 
                   9182: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9183: 	    &scantron_putfile($scanlines,$scan_data);
                   9184: 	}
1.161     albertel 9185: 	
1.542     raeburn  9186:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9187:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  9188:                                    $bubbles_per_row,$randomorder,$randompick,
                   9189:                                    \%respnumlookup,\%startline) 
                   9190:             eq 'ssi_error') {
1.542     raeburn  9191:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9192:             $r->print("</form>");
                   9193:             &ssi_print_error($r);
                   9194:             &Apache::lonnet::remove_lock($lock);
                   9195:             return '';      # Why return ''?  Beats me.
                   9196:         }
1.513     foxr     9197: 
1.692     raeburn  9198:         if (($scancode) && ($randomorder || $randompick)) {
                   9199:             my $parmresult =
                   9200:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   9201:                                                        '0_examcode',2,$scancode,
                   9202:                                                        'string_examcode',$uname,
                   9203:                                                        $udom);
                   9204:         }
1.140     albertel 9205: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9206:         if ($env{'form.verifyrecord'}) {
                   9207:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  9208:             if ($randompick) {
                   9209:                 if ($total) {
                   9210:                     $lastpos = $total*$scantron_config{'Qlength'};
                   9211:                 }
                   9212:             }
                   9213: 
1.542     raeburn  9214:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9215:             chomp($studentdata);
                   9216:             $studentdata =~ s/\r$//;
                   9217:             my $studentrecord = '';
                   9218:             my $counter = -1;
1.677     raeburn  9219:             foreach my $resource (@mapresources) {
1.554     raeburn  9220:                 my $ressymb = $resource->symb();
1.542     raeburn  9221:                 ($counter,my $recording) =
                   9222:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9223:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9224:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9225:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9226:                 $studentrecord .= $recording;
                   9227:             }
                   9228:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9229:                 &Apache::lonxml::clear_problem_counter();
                   9230:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9231:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  9232:                                            $bubbles_per_row,$randomorder,$randompick,
                   9233:                                            \%respnumlookup,\%startline) 
                   9234:                     eq 'ssi_error') {
1.554     raeburn  9235:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9236:                     $r->print("</form>");
                   9237:                     &ssi_print_error($r);
                   9238:                     &Apache::lonnet::remove_lock($lock);
                   9239:                     delete($completedstudents{$uname});
                   9240:                     return '';
                   9241:                 }
1.542     raeburn  9242:                 $counter = -1;
                   9243:                 $studentrecord = '';
1.677     raeburn  9244:                 foreach my $resource (@mapresources) {
1.554     raeburn  9245:                     my $ressymb = $resource->symb();
1.542     raeburn  9246:                     ($counter,my $recording) =
                   9247:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9248:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9249:                                                  \%scantron_config,\%lettdig,$numletts,
                   9250:                                                  $randomorder,$randompick,\%respnumlookup,
                   9251:                                                  \%startline);
1.542     raeburn  9252:                     $studentrecord .= $recording;
                   9253:                 }
                   9254:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   9255:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9256:                     if ($scancode eq '') {
1.658     bisitz   9257:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9258:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9259:                     } else {
1.658     bisitz   9260:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9261:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9262:                     }
                   9263:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9264:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9265:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9266:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9267:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9268:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   9269:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9270:                               &Apache::loncommon::end_data_table_row().
                   9271:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9272:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   9273:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9274:                               &Apache::loncommon::end_data_table_row().
                   9275:                               &Apache::loncommon::end_data_table().'</p>');
                   9276:                 } else {
                   9277:                     $r->print('<br /><span class="LC_warning">'.
                   9278:                              &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 />'.
                   9279:                              &mt("As a consequence, this user's submission history records two tries.").
                   9280:                                  '</span><br />');
                   9281:                 }
                   9282:             }
                   9283:         }
1.543     raeburn  9284:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9285:     } continue {
1.330     albertel 9286: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9287: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9288:     }
1.140     albertel 9289:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9290:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9291: #    my $lasttime = &Time::HiRes::time()-$start;
                   9292: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9293: 
1.200     albertel 9294:     $r->print("</form>");
1.157     albertel 9295:     return '';
1.75      albertel 9296: }
1.157     albertel 9297: 
1.557     raeburn  9298: sub graders_resources_pass {
1.649     raeburn  9299:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9300:         $bubbles_per_row) = @_;
1.557     raeburn  9301:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9302:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9303:         foreach my $resource (@{$resources}) {
                   9304:             my $ressymb = $resource->symb();
                   9305:             my ($analysis,$parts) =
                   9306:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  9307:                                           $env{'user.name'},$env{'user.domain'},
                   9308:                                           1,$bubbles_per_row);
1.557     raeburn  9309:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9310:             if (ref($analysis) eq 'HASH') {
                   9311:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9312:                     $grader_randomlists_by_symb->{$ressymb} =
                   9313:                         $analysis->{'parts_withrandomlist'};
                   9314:                 }
                   9315:             }
                   9316:         }
                   9317:     }
                   9318:     return;
                   9319: }
                   9320: 
1.678     raeburn  9321: =pod
                   9322: 
                   9323: =item users_order
                   9324: 
                   9325:   Returns array of resources in current map, ordered based on either CODE,
                   9326:   if this is a CODEd exam, or based on student's identity if this is a 
                   9327:   "NAMEd" exam.
                   9328: 
1.691     raeburn  9329:   Should be used when randomorder and/or randompick applied when the 
                   9330:   corresponding exam was printed, prior to students completing bubblesheets 
                   9331:   for the version of the exam the student received.
1.678     raeburn  9332: 
                   9333: =cut
                   9334: 
                   9335: sub users_order  {
1.691     raeburn  9336:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9337:     my @mapresources;
1.691     raeburn  9338:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9339:         return @mapresources;
1.691     raeburn  9340:     }
                   9341:     if ($scancode) {
                   9342:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9343:             @mapresources = @{$orderedforcode->{$scancode}};
                   9344:         } else {
                   9345:             $env{'form.CODE'} = $scancode;
                   9346:             my $actual_seq =
                   9347:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9348:                                                                $master_seq,
                   9349:                                                                $user,$scancode,1);
                   9350:             if (ref($actual_seq) eq 'ARRAY') {
                   9351:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9352:                 if (ref($orderedforcode) eq 'HASH') {
                   9353:                     if (@mapresources > 0) { 
                   9354:                         $orderedforcode->{$scancode} = \@mapresources;
                   9355:                     }
                   9356:                 }
                   9357:             }
                   9358:             delete($env{'form.CODE'});
1.678     raeburn  9359:         }
                   9360:     } else {
                   9361:         my $actual_seq =
                   9362:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9363:                                                            $master_seq,
1.688     raeburn  9364:                                                            $user,undef,1);
1.678     raeburn  9365:         if (ref($actual_seq) eq 'ARRAY') {
                   9366:             @mapresources = 
                   9367:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9368:         }
1.691     raeburn  9369:     }
                   9370:     return @mapresources;
1.678     raeburn  9371: }
                   9372: 
1.542     raeburn  9373: sub grade_student_bubbles {
1.691     raeburn  9374:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9375:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9376:     my $uselookup = 0;
                   9377:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9378:         (ref($startline) eq 'HASH')) {
                   9379:         $uselookup = 1;
                   9380:     }
                   9381: 
1.554     raeburn  9382:     if (ref($resources) eq 'ARRAY') {
                   9383:         my $count = 0;
                   9384:         foreach my $resource (@{$resources}) {
                   9385:             my $ressymb = $resource->symb();
                   9386:             my %form = ('submitted'      => 'scantron',
                   9387:                         'grade_target'   => 'grade',
                   9388:                         'grade_username' => $uname,
                   9389:                         'grade_domain'   => $udom,
                   9390:                         'grade_courseid' => $env{'request.course.id'},
                   9391:                         'grade_symb'     => $ressymb,
                   9392:                         'CODE'           => $scancode
                   9393:                        );
1.649     raeburn  9394:             if ($bubbles_per_row ne '') {
                   9395:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9396:             }
1.663     raeburn  9397:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9398:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9399:             }
1.554     raeburn  9400:             if (ref($parts) eq 'HASH') {
                   9401:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9402:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9403:                         if ($uselookup) {
                   9404:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9405:                         } else {
                   9406:                             $form{'scantron_questnum_start.'.$part} =
                   9407:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9408:                         }
1.554     raeburn  9409:                         $count++;
                   9410:                     }
                   9411:                 }
                   9412:             }
                   9413:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9414:             return 'ssi_error' if ($ssi_error);
                   9415:             last if (&Apache::loncommon::connection_aborted($r));
                   9416:         }
1.542     raeburn  9417:     }
                   9418:     return;
                   9419: }
                   9420: 
1.157     albertel 9421: sub scantron_upload_scantron_data {
1.767     raeburn  9422:     my ($r,$symb) = @_;
1.565     raeburn  9423:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9424:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9425:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9426:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9427:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9428: 							  'domainid',
1.565     raeburn  9429: 							  'coursename',$dom);
                   9430:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9431:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9432:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9433:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9434:     &js_escape(\$nofile_alert);
1.579     raeburn  9435:     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  9436:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9437:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9438:     function checkUpload(formname) {
                   9439: 	if (formname.upfile.value == "") {
1.579     raeburn  9440: 	    alert("'.$nofile_alert.'");
1.157     albertel 9441: 	    return false;
                   9442: 	}
1.565     raeburn  9443:         if (formname.courseid.value == "") {
1.579     raeburn  9444:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9445:             return false;
                   9446:         }
1.157     albertel 9447: 	formname.submit();
                   9448:     }
1.565     raeburn  9449: 
                   9450:     function ToSyllabus() {
                   9451:         var cdom = '."'$dom'".';
                   9452:         var cnum = document.rules.courseid.value;
                   9453:         if (cdom == "" || cdom == null) {
                   9454:             return;
                   9455:         }
                   9456:         if (cnum == "" || cnum == null) {
                   9457:            return;
                   9458:         }
                   9459:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9460:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9461:         return;
                   9462:     }
                   9463: 
1.754     raeburn  9464:     '.$formatjs.'
1.597     wenzelju 9465: '));
                   9466:     $r->print('
1.648     bisitz   9467: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9468: 
1.492     albertel 9469: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9470: '.$default_form_data.
                   9471:   &Apache::lonhtmlcommon::start_pick_box().
                   9472:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9473:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9474:   &Apache::lonhtmlcommon::row_closure().
                   9475:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9476:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9477:   &Apache::lonhtmlcommon::row_closure().
                   9478:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9479:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9480:   &Apache::lonhtmlcommon::row_closure());
                   9481:     if ($formatoptions) {
                   9482:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9483:                   &Apache::lonhtmlcommon::row_closure());
                   9484:     }
                   9485:     $r->print(
1.565     raeburn  9486:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9487:   '<input type="file" name="upfile" size="50" />'.
                   9488:   &Apache::lonhtmlcommon::row_closure(1).
                   9489:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9490: 
1.492     albertel 9491: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9492: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9493: </form>
1.492     albertel 9494: ');
1.157     albertel 9495:     return '';
                   9496: }
                   9497: 
1.754     raeburn  9498: sub scantron_upload_dataformat {
                   9499:     my ($dom) = @_;
                   9500:     my ($formatoptions,$formattitle,$formatjs);
                   9501:     $formatjs = <<'END';
                   9502: function toggleScantab(form) {
                   9503:    return;
                   9504: }
                   9505: END
                   9506:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9507:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9508:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9509:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9510:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9511:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  9512:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   9513:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9514:                             my ($onclick,$formatextra,$singleline);
                   9515:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9516:                             my $count = 0;
                   9517:                             foreach my $line (@lines) {
                   9518:                                 next if ($line =~ /^#/);
                   9519:                                 $singleline = $line;
                   9520:                                 $count ++;
                   9521:                             }
                   9522:                             if ($count > 1) {
                   9523:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  9524:                                                '<span class="LC_nobreak">'.
1.776     raeburn  9525:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  9526:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  9527:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9528:                                 $formatjs = <<"END";
1.754     raeburn  9529: function toggleScantab(form) {
                   9530:     var divid = 'bubbletype';
                   9531:     if (document.getElementById(divid)) {
                   9532:         var radioname = 'fileformat';
                   9533:         var num = form.elements[radioname].length;
                   9534:         if (num) {
                   9535:             for (var i=0; i<num; i++) {
                   9536:                 if (form.elements[radioname][i].checked) {
                   9537:                     var chosen = form.elements[radioname][i].value;
                   9538:                     if (chosen == 'dat') {
                   9539:                         document.getElementById(divid).style.display = 'none';
                   9540:                     } else if (chosen == 'csv') {
1.757     raeburn  9541:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  9542:                     }
                   9543:                 }
                   9544:             }
                   9545:         }
                   9546:     }
                   9547:     return;
                   9548: }
                   9549: 
                   9550: END
1.756     raeburn  9551:                             } elsif ($count == 1) {
                   9552:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9553:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9554:                             }
                   9555:                             $formattitle = &mt('File format');
                   9556:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9557:                                              &mt('Plain Text (no delimiters)').
                   9558:                                              '</label>'.('&nbsp;'x2).
                   9559:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9560:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9561:                         }
                   9562:                     }
                   9563:                 }
                   9564:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  9565:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9566:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  9567:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  9568:                         $formatoptions = &scantron_scantab();
                   9569:                     }
1.754     raeburn  9570:                 }
                   9571:             }
                   9572:         }
                   9573:     }
                   9574:     return ($formatoptions,$formattitle,$formatjs);
                   9575: }
1.423     albertel 9576: 
1.157     albertel 9577: sub scantron_upload_scantron_data_save {
1.767     raeburn  9578:     my ($r,$symb) = @_;
1.182     albertel 9579:     my $doanotherupload=
                   9580: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9581: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9582: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9583: 	'</form>'."\n";
1.257     albertel 9584:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9585: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  9586: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   9587:         !&Apache::lonnet::allowed('usc',
                   9588:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      9589: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9590: 	unless ($symb) {
1.182     albertel 9591: 	    $r->print($doanotherupload);
                   9592: 	}
1.162     albertel 9593: 	return '';
                   9594:     }
1.257     albertel 9595:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9596:     my $uploadedfile;
1.710     bisitz   9597:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9598:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9599:         $r->print(
                   9600:             &Apache::lonhtmlcommon::confirm_success(
                   9601:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9602:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9603:     } else {
1.754     raeburn  9604:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9605:         my $parser;
                   9606:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9607:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9608:                 my $is_csv;
                   9609:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9610:                 if (@possibles > 1) {
                   9611:                     if ($env{'form.fileformat'} eq 'csv') {
                   9612:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9613:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9614:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9615:                                     $is_csv = 1;
                   9616:                                 }
1.754     raeburn  9617:                             }
                   9618:                         }
                   9619:                     }
                   9620:                 } elsif (@possibles == 1) {
                   9621:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9622:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9623:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9624:                                 $is_csv = 1;
                   9625:                             }
1.754     raeburn  9626:                         }
                   9627:                     }
                   9628:                 }
                   9629:                 if ($is_csv) {
                   9630:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9631:                 }
                   9632:             }
                   9633:         }
                   9634:         my $result =
                   9635:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9636:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9637:         if ($result =~ m{^/uploaded/}) {
                   9638:             $r->print(
                   9639:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9640:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9641:                         (length($env{'form.upfile'})-1),
                   9642:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9643:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  9644:             if ($uploadedfile =~ /^scantron_orig_/) {
                   9645:                 my $logname = $uploadedfile;
                   9646:                 $logname =~ s/^scantron_orig_//;
                   9647:                 if ($logname ne '') {
                   9648:                     my $now = time;
                   9649:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   9650:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9651:                 }
                   9652:             }
1.567     raeburn  9653:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  9654:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   9655:         } else {
                   9656:             $r->print(
                   9657:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9658:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9659:                           $result,
1.568     raeburn  9660: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9661: 	}
                   9662:     }
1.174     albertel 9663:     if ($symb) {
1.612     www      9664: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9665:     } else {
1.182     albertel 9666: 	$r->print($doanotherupload);
1.174     albertel 9667:     }
1.157     albertel 9668:     return '';
                   9669: }
                   9670: 
1.567     raeburn  9671: sub validate_uploaded_scantron_file {
1.770     raeburn  9672:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   9673: 
1.567     raeburn  9674:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9675:     my @lines;
                   9676:     if ($scanlines ne '-1') {
                   9677:         @lines=split("\n",$scanlines,-1);
                   9678:     }
1.770     raeburn  9679:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   9680:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   9681:     if ($context eq 'download') {
                   9682:         $priv = 'mgr';
                   9683:     } else {
                   9684:         $priv = 'usc';
                   9685:     }
                   9686:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   9687:             (($env{'request.course.id'}) &&
                   9688:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   9689:         if ($env{'request.course.sec'} ne '') {
                   9690:             unless (&Apache::lonnet::allowed($priv,
                   9691:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   9692:                 unless ($context eq 'download') {
                   9693:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   9694:                 }
                   9695:                 return $output;
                   9696:             }
                   9697:             ($checksec,@possibles)=&gradable_sections();
                   9698:         }
                   9699:     }
1.567     raeburn  9700:     if (@lines) {
                   9701:         my (%counts,$max_match_format);
1.710     bisitz   9702:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9703:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9704:         my %idmap = &username_to_idmap($classlist);
                   9705:         foreach my $key (keys(%idmap)) {
                   9706:             my $lckey = lc($key);
                   9707:             $idmap{$lckey} = $idmap{$key};
                   9708:         }
                   9709:         my %unique_formats;
1.754     raeburn  9710:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9711:         foreach my $line (@formatlines) {
                   9712:             chomp($line);
                   9713:             my @config = split(/:/,$line);
                   9714:             my $idstart = $config[5];
                   9715:             my $idlength = $config[6];
                   9716:             if (($idstart ne '') && ($idlength > 0)) {
                   9717:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9718:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9719:                 } else {
                   9720:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9721:                 }
                   9722:             }
                   9723:         }
                   9724:         foreach my $key (keys(%unique_formats)) {
                   9725:             my ($idstart,$idlength) = split(':',$key);
                   9726:             %{$counts{$key}} = (
                   9727:                                'found'   => 0,
                   9728:                                'total'   => 0,
1.770     raeburn  9729:                                'totalanysec' => 0,
                   9730:                                'othersec' => 0,
1.567     raeburn  9731:                               );
                   9732:             foreach my $line (@lines) {
                   9733:                 next if ($line =~ /^#/);
                   9734:                 next if ($line =~ /^[\s\cz]*$/);
                   9735:                 my $id = substr($line,$idstart-1,$idlength);
                   9736:                 $id = lc($id);
                   9737:                 if (exists($idmap{$id})) {
1.770     raeburn  9738:                     if ($checksec ne '') {
                   9739:                         $counts{$key}{'totalanysec'} ++;
                   9740:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9741:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9742:                             if ($stusec ne $checksec) {
                   9743:                                 if (@possibles) {
                   9744:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   9745:                                         $counts{$key}{'othersec'} ++;
                   9746:                                         next;
                   9747:                                     }
                   9748:                                 } else {
                   9749:                                     $counts{$key}{'othersec'} ++;
                   9750:                                     next;
                   9751:                                 }
                   9752:                             }
                   9753:                         }
                   9754:                     }
1.567     raeburn  9755:                     $counts{$key}{'found'} ++;
                   9756:                 }
                   9757:                 $counts{$key}{'total'} ++;
                   9758:             }
                   9759:             if ($counts{$key}{'total'}) {
                   9760:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9761:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9762:                     $max_match_pct = $percent_match;
                   9763:                     $max_match_format = $key;
1.710     bisitz   9764:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9765:                     $max_match_count = $counts{$key}{'total'};
                   9766:                 }
                   9767:             }
                   9768:         }
1.770     raeburn  9769:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  9770:             my $format_descs;
                   9771:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9772:             for (my $i=0; $i<$numwithformat; $i++) {
                   9773:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9774:                 if ($i<$numwithformat-2) {
                   9775:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9776:                 } elsif ($i==$numwithformat-2) {
                   9777:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9778:                 } elsif ($i==$numwithformat-1) {
                   9779:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9780:                 }
                   9781:             }
                   9782:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9783:             $output .= '<br />';
                   9784:             if ($found_match_count == $max_match_count) {
                   9785:                 # 100% matching entries
                   9786:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9787:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9788:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9789:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9790:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9791:                     ' in the file (for the format defined for [_3]).',
                   9792:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9793:             } else {
                   9794:                 # Not all entries matching? -> Show warning and additional info
                   9795:                 $output .=
                   9796:                     &Apache::lonhtmlcommon::confirm_success(
                   9797:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9798:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9799:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9800:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9801:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9802:                         ' in the file (for the format defined for [_3]).',
                   9803:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9804:                     '<p class="LC_info">'.
                   9805:                     &mt('A low percentage of matches results from one of the following:').
                   9806:                     '</p><ul>'.
                   9807:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9808:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9809:                                '<i>'.$cdom.'</i>').'</li>'.
                   9810:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9811:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9812:                     '</ul>';
                   9813:             }
1.770     raeburn  9814:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9815:                 if ($counts{$max_match_format}{'othersec'}) {
                   9816:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   9817:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   9818:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   9819:                     &js_escape(\$confirmdel);
                   9820:                     $output .= '<p class="LC_warning">'.
                   9821:                                &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',
                   9822:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   9823:                                '<br />'.
                   9824:                                &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>').
                   9825:                                '</p><p>'.
                   9826:                                &mt('If you prefer to delete the file now, use: [_1]').
                   9827:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   9828:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   9829:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   9830:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   9831:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   9832:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   9833:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   9834:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   9835:                                '</form></p>';
                   9836:                 }
                   9837:             }
1.567     raeburn  9838:         }
1.770     raeburn  9839:         if (($context eq 'download') && ($checksec ne '')) {
                   9840:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9841:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   9842:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   9843:             }
                   9844:         } 
                   9845:     } elsif ($context ne 'download') {
1.710     bisitz   9846:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9847:     }
                   9848:     return $output;
                   9849: }
                   9850: 
1.770     raeburn  9851: sub gradable_sections {
                   9852:     my $checksec = $env{'request.course.sec'};
                   9853:     my @oksecs;
                   9854:     if ($checksec) {
                   9855:         my %availablesecs = &sections_grade_privs();
                   9856:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   9857:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   9858:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   9859:                     push(@oksecs,$sec);
                   9860:                 }
                   9861:             }
                   9862:             if (grep(/^all$/,@oksecs)) {
                   9863:                 undef($checksec);
                   9864:             }
                   9865:         }
                   9866:     }
                   9867:     return($checksec,@oksecs);
                   9868: }
                   9869: 
                   9870: sub sections_grade_privs {
                   9871:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9872:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9873:     my %availablesecs = (
                   9874:                           mgr => [],
                   9875:                           vgr => [],
                   9876:                           usc => [],
                   9877:                         );
                   9878:     my $ccrole = 'cc';
                   9879:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   9880:         $ccrole = 'co';
                   9881:     }
                   9882:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   9883:                                                      'userroles',['active'],
                   9884:                                                      [$ccrole,'in','cr'],$cdom,1);
                   9885:     my $crsid = $cnum.':'.$cdom;
                   9886:     foreach my $item (keys(%crsroleshash)) {
                   9887:         next unless ($item =~ /^$crsid\:/);
                   9888:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   9889:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   9890:         if ($sec ne '') {
                   9891:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   9892:         }
                   9893:         if (($role eq $ccrole) || ($role eq 'in')) {
                   9894:             foreach my $priv ('mgr','vgr','usc') { 
                   9895:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9896:                     if ($sec eq '') {
                   9897:                         $availablesecs{$priv} = ['all'];
                   9898:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   9899:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9900:                             push(@{$availablesecs{$priv}},$sec);
                   9901:                         }
                   9902:                     }
                   9903:                 }
                   9904:             }
                   9905:         } elsif ($role =~ m{^cr/}) {
                   9906:             foreach my $priv ('mgr','vgr','usc') {
                   9907:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9908:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   9909:                         if ($sec eq '') {
                   9910:                             $availablesecs{$priv} = ['all'];
                   9911:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   9912:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9913:                                 push(@{$availablesecs{$priv}},$sec);
                   9914:                             }
                   9915:                         }
                   9916:                     }
                   9917:                 }
                   9918:             }
                   9919:         }
                   9920:     }
                   9921:     return %availablesecs;
                   9922: }
                   9923: 
                   9924: sub scantron_upload_delete {
                   9925:     my ($r,$symb) = @_;
                   9926:     my $filename = $env{'form.uploadedfile'};
                   9927:     if ($filename =~ /^scantron_orig_/) {
                   9928:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   9929:             &Apache::lonnet::allowed('usc',
                   9930:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   9931:             &Apache::lonnet::allowed('usc',
                   9932:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   9933:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   9934:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   9935:             if ($retrieval eq '-1') {
                   9936:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9937:                           &mt('File requested for deletion not found.'));
                   9938:             } else {
                   9939:                 $filename =~ s/^scantron_orig_//;
                   9940:                 if ($filename ne '') {
                   9941:                     my ($is_valid,$numleft);
                   9942:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9943:                     if (keys(%info)) {
                   9944:                         if (ref($info{$filename}) eq 'HASH') {
                   9945:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   9946:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9947:                                     $is_valid = 1;
                   9948:                                     delete($info{$filename}{$timestamp}); 
                   9949:                                 }
                   9950:                             }
                   9951:                             $numleft = scalar(keys(%{$info{$filename}}));
                   9952:                         }
                   9953:                     }
                   9954:                     if ($is_valid) {
                   9955:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   9956:                         if ($result eq 'ok') {
                   9957:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   9958:                             if ($numleft) {
                   9959:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9960:                             } else {
                   9961:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9962:                             }
                   9963:                         } else {
                   9964:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9965:                                       &mt('Result was [_1]',$result));
                   9966:                         }
                   9967:                     } else {
                   9968:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9969:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   9970:                     }
                   9971:                 } else {
                   9972:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9973:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9974:                 }
                   9975:             }
                   9976:         } else {
                   9977:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   9978:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   9979:         }
                   9980:     } else {
                   9981:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9982:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9983:     }
                   9984:     return;
                   9985: }
                   9986: 
1.202     albertel 9987: sub valid_file {
                   9988:     my ($requested_file)=@_;
                   9989:     foreach my $filename (sort(&scantron_filenames())) {
                   9990: 	if ($requested_file eq $filename) { return 1; }
                   9991:     }
                   9992:     return 0;
                   9993: }
                   9994: 
                   9995: sub scantron_download_scantron_data {
1.767     raeburn  9996:     my ($r,$symb) = @_;
1.608     www      9997:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9998:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9999:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10000:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 10001:     if (! &valid_file($file)) {
1.492     albertel 10002: 	$r->print('
1.202     albertel 10003: 	<p>
1.686     bisitz   10004: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 10005:         </p>
1.492     albertel 10006: ');
1.202     albertel 10007: 	return;
                   10008:     }
1.770     raeburn  10009:     my (%uploader,$is_owner,%counts,$percent);
                   10010:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   10011:     if (ref($uploader{$file}) eq 'HASH') {
                   10012:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   10013:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   10014:                 $is_owner = 1;
                   10015:                 last;
                   10016:             }
                   10017:         }
                   10018:     }
                   10019:     unless ($is_owner) {
                   10020:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   10021:         if ($counts{'totalanysec'}) {
                   10022:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   10023:             if ($percent_othersec >= 10) {
                   10024:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   10025:                 $r->print('<p class="LC_warning">'.
                   10026:                           &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).
                   10027:                           '</p>');
                   10028:                 return;
                   10029:             }
                   10030:         }
                   10031:     }
1.202     albertel 10032:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   10033:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   10034:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   10035:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   10036:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   10037:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 10038:     $r->print('
1.202     albertel 10039:     <p>
1.723     raeburn  10040: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 10041: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 10042:     </p>
                   10043:     <p>
1.492     albertel 10044: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   10045: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 10046:     </p>
                   10047:     <p>
1.492     albertel 10048: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   10049: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 10050:     </p>
1.492     albertel 10051: ');
1.202     albertel 10052:     return '';
                   10053: }
1.157     albertel 10054: 
1.523     raeburn  10055: sub checkscantron_results {
1.608     www      10056:     my ($r,$symb) = @_;
1.523     raeburn  10057:     if (!$symb) {return '';}
                   10058:     my $cid = $env{'request.course.id'};
1.755     raeburn  10059:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  10060:     my $numletts = scalar(keys(%lettdig));
                   10061:     my $cnum = $env{'course.'.$cid.'.num'};
                   10062:     my $cdom = $env{'course.'.$cid.'.domain'};
                   10063:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10064:     my %record;
                   10065:     my %scantron_config =
1.754     raeburn  10066:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  10067:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  10068:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  10069:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10070:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   10071:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10072:     unless (ref($navmap)) {
                   10073:         $r->print(&navmap_errormsg());
                   10074:         return '';
                   10075:     }
1.523     raeburn  10076:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10077:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10078:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  10079:     if (ref($map)) { 
                   10080:         $randomorder=$map->randomorder();
1.689     raeburn  10081:         $randompick=$map->randompick();
1.677     raeburn  10082:     }
1.557     raeburn  10083:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10084:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10085:     if ($nav_error) {
                   10086:         $r->print(&navmap_errormsg());
                   10087:         return '';
1.678     raeburn  10088:     }
1.673     raeburn  10089:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10090:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  10091:     my ($uname,$udom);
1.523     raeburn  10092:     my (%scandata,%lastname,%bylast);
                   10093:     $r->print('
                   10094: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   10095: 
                   10096:     my @delayqueue;
                   10097:     my %completedstudents;
                   10098: 
1.691     raeburn  10099:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10100:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  10101:     my ($username,$domain,$started);
1.649     raeburn  10102:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10103:     if ($nav_error) {
                   10104:         $r->print(&navmap_errormsg());
                   10105:         return '';
                   10106:     }
1.523     raeburn  10107: 
1.667     www      10108:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  10109:     my $start=&Time::HiRes::time();
                   10110:     my $i=-1;
                   10111: 
                   10112:     while ($i<$scanlines->{'count'}) {
                   10113:         ($username,$domain,$uname)=('','','');
                   10114:         $i++;
                   10115:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   10116:         if ($line=~/^[\s\cz]*$/) { next; }
                   10117:         if ($started) {
1.667     www      10118:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  10119:         }
                   10120:         $started=1;
                   10121:         my $scan_record=
                   10122:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   10123:                                                      $scan_data);
1.693     raeburn  10124:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10125:                                               \%idmap,$i)) {
1.523     raeburn  10126:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10127:                                 'Unable to find a student that matches',1);
                   10128:             next;
                   10129:         }
                   10130:         if (exists $completedstudents{$uname}) {
                   10131:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10132:                                 'Student '.$uname.' has multiple sheets',2);
                   10133:             next;
                   10134:         }
                   10135:         my $pid = $scan_record->{'scantron.ID'};
                   10136:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   10137:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  10138:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   10139:         my $user = $uname.':'.$usec;
1.523     raeburn  10140:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  10141: 
1.678     raeburn  10142:         my $scancode;
1.677     raeburn  10143:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10144:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10145:             $scancode = $scan_record->{'scantron.CODE'};
                   10146:         } else {
                   10147:             $scancode = '';
                   10148:         }
                   10149: 
                   10150:         my @mapresources = @resources;
1.691     raeburn  10151:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   10152:         my %respnumlookup=();
                   10153:         my %startline=();
1.689     raeburn  10154:         if ($randomorder || $randompick) {
1.678     raeburn  10155:             @mapresources =
1.691     raeburn  10156:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10157:                              \%orderedforcode);
                   10158:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   10159:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   10160:                                              \%grader_partids_by_symb,\%orderedforcode,
                   10161:                                              \%respnumlookup,\%startline);
                   10162:             if ($randompick && $total) {
                   10163:                 $lastpos = $total*$scantron_config{'Qlength'};
                   10164:             }
1.677     raeburn  10165:         }
1.691     raeburn  10166:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10167:         chomp($scandata{$pid});
                   10168:         $scandata{$pid} =~ s/\r$//;
                   10169: 
1.523     raeburn  10170:         my $counter = -1;
1.677     raeburn  10171:         foreach my $resource (@mapresources) {
1.557     raeburn  10172:             my $parts;
1.554     raeburn  10173:             my $ressymb = $resource->symb();
1.557     raeburn  10174:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10175:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10176:                 my $currcode;
                   10177:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10178:                     $currcode = $scancode;
                   10179:                 }
1.557     raeburn  10180:                 (my $analysis,$parts) =
1.672     raeburn  10181:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   10182:                                               $username,$domain,undef,
1.741     raeburn  10183:                                               $bubbles_per_row,$currcode);
1.557     raeburn  10184:             } else {
                   10185:                 $parts = $grader_partids_by_symb{$ressymb};
                   10186:             }
1.542     raeburn  10187:             ($counter,my $recording) =
                   10188:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  10189:                                          $scandata{$pid},$parts,
1.691     raeburn  10190:                                          \%scantron_config,\%lettdig,$numletts,
                   10191:                                          $randomorder,$randompick,
                   10192:                                          \%respnumlookup,\%startline);
1.542     raeburn  10193:             $record{$pid} .= $recording;
1.523     raeburn  10194:         }
                   10195:     }
                   10196:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   10197:     $r->print('<br />');
                   10198:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   10199:     $passed = 0;
                   10200:     $failed = 0;
                   10201:     $numstudents = 0;
                   10202:     foreach my $last (sort(keys(%bylast))) {
                   10203:         if (ref($bylast{$last}) eq 'ARRAY') {
                   10204:             foreach my $pid (sort(@{$bylast{$last}})) {
                   10205:                 my $showscandata = $scandata{$pid};
                   10206:                 my $showrecord = $record{$pid};
                   10207:                 $showscandata =~ s/\s/&nbsp;/g;
                   10208:                 $showrecord =~ s/\s/&nbsp;/g;
                   10209:                 if ($scandata{$pid} eq $record{$pid}) {
                   10210:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   10211:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      10212: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  10213: '</tr>'."\n".
                   10214: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10215: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  10216:                     $passed ++;
                   10217:                 } else {
                   10218:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      10219:                     $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  10220: '</tr>'."\n".
                   10221: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10222: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  10223: '</tr>'."\n";
                   10224:                     $failed ++;
                   10225:                 }
                   10226:                 $numstudents ++;
                   10227:             }
                   10228:         }
                   10229:     }
1.648     bisitz   10230:     $r->print(
                   10231:         '<p>'
                   10232:        .&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).',
                   10233:             '<b>',
                   10234:             $numstudents,
                   10235:             '</b>',
                   10236:             $env{'form.scantron_maxbubble'})
                   10237:        .'</p>'
                   10238:     );
1.682     raeburn  10239:     $r->print('<p>'
1.683     raeburn  10240:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  10241:              .'<br />'
                   10242:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10243:              .'</p>'
                   10244:     );
1.523     raeburn  10245:     if ($passed) {
1.572     www      10246:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10247:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10248:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10249:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10250:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10251:                  $okstudents."\n".
                   10252:                  &Apache::loncommon::end_data_table().'<br />');
                   10253:     }
                   10254:     if ($failed) {
1.572     www      10255:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10256:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10257:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10258:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10259:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10260:                  $badstudents."\n".
                   10261:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10262:                  &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  10263:     }
1.614     www      10264:     $r->print('</form><br />');
1.523     raeburn  10265:     return;
                   10266: }
                   10267: 
1.542     raeburn  10268: sub verify_scantron_grading {
1.554     raeburn  10269:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  10270:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10271:         $respnumlookup,$startline) = @_;
1.542     raeburn  10272:     my ($record,%expected,%startpos);
                   10273:     return ($counter,$record) if (!ref($resource));
                   10274:     return ($counter,$record) if (!$resource->is_problem());
                   10275:     my $symb = $resource->symb();
1.554     raeburn  10276:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10277:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10278:         $counter ++;
                   10279:         $expected{$part_id} = 0;
1.691     raeburn  10280:         my $respnum = $counter;
                   10281:         if ($randomorder || $randompick) {
                   10282:             $respnum = $respnumlookup->{$counter};
                   10283:             $startpos{$part_id} = $startline->{$counter} + 1;
                   10284:         } else {
                   10285:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10286:         }
                   10287:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10288:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10289:             foreach my $item (@sub_lines) {
                   10290:                 $expected{$part_id} += $item;
                   10291:             }
                   10292:         } else {
1.691     raeburn  10293:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10294:         }
                   10295:     }
                   10296:     if ($symb) {
                   10297:         my %recorded;
                   10298:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10299:         if ($returnhash{'version'}) {
                   10300:             my %lasthash=();
                   10301:             my $version;
                   10302:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10303:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10304:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10305:                 }
                   10306:             }
                   10307:             foreach my $key (keys(%lasthash)) {
                   10308:                 if ($key =~ /\.scantron$/) {
                   10309:                     my $value = &unescape($lasthash{$key});
                   10310:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10311:                     if ($value eq '') {
                   10312:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10313:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10314:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10315:                             }
                   10316:                         }
                   10317:                     } else {
                   10318:                         my @tocheck;
                   10319:                         my @items = split(//,$value);
                   10320:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10321:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10322:                             if (@items < $expected{$part_id}) {
                   10323:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10324:                                 my @singles = split(//,$fragment);
                   10325:                                 foreach my $pos (@singles) {
                   10326:                                     if ($pos eq ' ') {
                   10327:                                         push(@tocheck,$pos);
                   10328:                                     } else {
                   10329:                                         my $next = shift(@items);
                   10330:                                         push(@tocheck,$next);
                   10331:                                     }
                   10332:                                 }
                   10333:                             } else {
                   10334:                                 @tocheck = @items;
                   10335:                             }
                   10336:                             foreach my $letter (@tocheck) {
                   10337:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10338:                                     if ($letter !~ /^[A-J]$/) {
                   10339:                                         $letter = $scantron_config->{'Qoff'};
                   10340:                                     }
                   10341:                                     $recorded{$part_id} .= $letter;
                   10342:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10343:                                     my $digit;
                   10344:                                     if ($letter !~ /^[A-J]$/) {
                   10345:                                         $digit = $scantron_config->{'Qoff'};
                   10346:                                     } else {
                   10347:                                         $digit = $lettdig->{$letter};
                   10348:                                     }
                   10349:                                     $recorded{$part_id} .= $digit;
                   10350:                                 }
                   10351:                             }
                   10352:                         } else {
                   10353:                             @tocheck = @items;
                   10354:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10355:                                 my $curr_sub = shift(@tocheck);
                   10356:                                 my $digit;
                   10357:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10358:                                     $digit = $lettdig->{$curr_sub}-1;
                   10359:                                 }
                   10360:                                 if ($curr_sub eq 'J') {
                   10361:                                     $digit += scalar($numletts);
                   10362:                                 }
                   10363:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10364:                                     if ($j == $digit) {
                   10365:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10366:                                     } else {
                   10367:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10368:                                     }
                   10369:                                 }
                   10370:                             }
                   10371:                         }
                   10372:                     }
                   10373:                 }
                   10374:             }
                   10375:         }
1.554     raeburn  10376:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10377:             if ($recorded{$part_id} eq '') {
                   10378:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10379:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10380:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10381:                     }
                   10382:                 }
                   10383:             }
                   10384:             $record .= $recorded{$part_id};
                   10385:         }
                   10386:     }
                   10387:     return ($counter,$record);
                   10388: }
                   10389: 
1.75      albertel 10390: #-------- end of section for handling grading scantron forms -------
                   10391: #
                   10392: #-------------------------------------------------------------------
                   10393: 
1.72      ng       10394: #-------------------------- Menu interface -------------------------
                   10395: #
1.614     www      10396: #--- Href with symb and command ---
                   10397: 
                   10398: sub href_symb_cmd {
                   10399:     my ($symb,$cmd)=@_;
1.669     raeburn  10400:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       10401: }
                   10402: 
1.443     banghart 10403: sub grading_menu {
1.608     www      10404:     my ($request,$symb) = @_;
1.443     banghart 10405:     if (!$symb) {return '';}
                   10406: 
                   10407:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      10408:                   'command'=>'individual');
1.538     schulted 10409:     
1.598     www      10410:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10411: 
                   10412:     $fields{'command'}='ungraded';
                   10413:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10414: 
                   10415:     $fields{'command'}='table';
                   10416:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10417: 
                   10418:     $fields{'command'}='all_for_one';
                   10419:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10420: 
1.621     www      10421:     $fields{'command'}='downloadfilesselect';
                   10422:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10423: 
1.443     banghart 10424:     $fields{'command'} = 'csvform';
1.538     schulted 10425:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10426:     
1.443     banghart 10427:     $fields{'command'} = 'processclicker';
1.538     schulted 10428:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10429:     
1.443     banghart 10430:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10431:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      10432: 
                   10433:     $fields{'command'} = 'initialverifyreceipt';
                   10434:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  10435: 
                   10436:     my %permissions;
                   10437:     if ($perm{'mgr'}) {
                   10438:         $permissions{'either'} = 'F';
                   10439:         $permissions{'mgr'} = 'F';
                   10440:     }
                   10441:     if ($perm{'vgr'}) {
                   10442:         $permissions{'either'} = 'F';
                   10443:         $permissions{'vgr'} = 'F';
                   10444:     }
                   10445: 
1.598     www      10446:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10447:             items =>[
1.598     www      10448:                         {	linktext => 'Select individual students to grade',
                   10449:                     		url => $url1a,
1.781     raeburn  10450:                     		permission => $permissions{'either'},
1.636     wenzelju 10451:                     		icon => 'grade_students.png',
1.598     www      10452:                     		linktitle => 'Grade current resource for a selection of students.'
                   10453:                         }, 
1.764     raeburn  10454:                         {       linktext => 'Grade ungraded submissions',
1.598     www      10455:                                 url => $url1b,
1.781     raeburn  10456:                                 permission => $permissions{'either'},
1.636     wenzelju 10457:                                 icon => 'ungrade_sub.png',
1.598     www      10458:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 10459:                         },
1.598     www      10460: 
                   10461:                         {       linktext => 'Grading table',
                   10462:                                 url => $url1c,
1.781     raeburn  10463:                                 permission => $permissions{'either'},
1.636     wenzelju 10464:                                 icon => 'grading_table.png',
1.598     www      10465:                                 linktitle => 'Grade current resource for all students.'
                   10466:                         },
1.615     www      10467:                         {       linktext => 'Grade page/folder for one student',
1.598     www      10468:                                 url => $url1d,
1.781     raeburn  10469:                                 permission => $permissions{'either'},
1.636     wenzelju 10470:                                 icon => 'grade_PageFolder.png',
1.598     www      10471:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      10472:                         },
                   10473:                         {       linktext => 'Download submissions',
                   10474:                                 url => $url1e,
1.781     raeburn  10475:                                 permission => $permissions{'either'},
1.636     wenzelju 10476:                                 icon => 'download_sub.png',
1.621     www      10477:                                 linktitle => 'Download all students submissions.'
1.598     www      10478:                         }]},
                   10479:                          { categorytitle=>'Automated Grading',
                   10480:                items =>[
                   10481: 
1.538     schulted 10482:                 	    {	linktext => 'Upload Scores',
                   10483:                     		url => $url2,
1.780     raeburn  10484:                     		permission => $permissions{'mgr'},
1.538     schulted 10485:                     		icon => 'uploadscores.png',
                   10486:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10487:                 	    },
                   10488:                 	    {	linktext => 'Process Clicker',
                   10489:                     		url => $url3,
1.780     raeburn  10490:                     		permission => $permissions{'mgr'},
1.538     schulted 10491:                     		icon => 'addClickerInfoFile.png',
                   10492:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10493:                 	    },
1.587     raeburn  10494:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10495:                     		url => $url4,
1.780     raeburn  10496:                     		permission => $permissions{'mgr'},
1.636     wenzelju 10497:                     		icon => 'bubblesheet.png',
1.648     bisitz   10498:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      10499:                 	    },
1.616     www      10500:                             {   linktext => 'Verify Receipt Number',
1.602     www      10501:                                 url => $url5,
1.780     raeburn  10502:                                 permission => $permissions{'either'},
1.636     wenzelju 10503:                                 icon => 'receipt_number.png',
1.602     www      10504:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10505:                             }
                   10506: 
1.538     schulted 10507:                     ]
                   10508:             });
                   10509: 
1.443     banghart 10510:     # Create the menu
                   10511:     my $Str;
1.445     banghart 10512:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10513:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      10514:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 10515: 
1.602     www      10516:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10517:     return $Str;    
                   10518: }
                   10519: 
1.598     www      10520: sub ungraded {
                   10521:     my ($request)=@_;
                   10522:     &submit_options($request);
                   10523: }
                   10524: 
1.599     www      10525: sub submit_options_sequence {
1.608     www      10526:     my ($request,$symb) = @_;
1.599     www      10527:     if (!$symb) {return '';}
1.600     www      10528:     &commonJSfunctions($request);
                   10529:     my $result;
1.599     www      10530: 
1.600     www      10531:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10532:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      10533:     $result.=&selectfield(0).
1.601     www      10534:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      10535:             <div>
                   10536:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10537:             </div>
                   10538:         </div>
                   10539:   </form>';
                   10540:     return $result;
                   10541: }
                   10542: 
                   10543: sub submit_options_table {
1.608     www      10544:     my ($request,$symb) = @_;
1.600     www      10545:     if (!$symb) {return '';}
1.599     www      10546:     &commonJSfunctions($request);
1.746     raeburn  10547:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      10548:     my $result;
                   10549: 
                   10550:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10551:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      10552: 
1.745     raeburn  10553:     $result.=&selectfield(1,$is_tool).
1.601     www      10554:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      10555:             <div>
                   10556:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10557:             </div>
                   10558:         </div>
                   10559:   </form>';
                   10560:     return $result;
                   10561: }
1.443     banghart 10562: 
1.621     www      10563: sub submit_options_download {
                   10564:     my ($request,$symb) = @_;
                   10565:     if (!$symb) {return '';}
                   10566: 
1.773     raeburn  10567:     my $res_error;
                   10568:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10569:         &response_type($symb,\$res_error);
                   10570:     if ($res_error) {
                   10571:         $request->print(&mt('An error occurred retrieving response types'));
                   10572:         return;
                   10573:     }
                   10574:     unless ($numessay) {
                   10575:         $request->print(&mt('No essayresponse items found'));
                   10576:         return;
                   10577:     }
                   10578:     my $table;
                   10579:     if (ref($partlist) eq 'ARRAY') {
                   10580:         if (scalar(@$partlist) > 1 ) {
                   10581:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   10582:         }
                   10583:     }
                   10584: 
1.746     raeburn  10585:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      10586:     &commonJSfunctions($request);
                   10587: 
                   10588:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  10589:                $table."\n".
                   10590:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      10591:     $result.='
                   10592: <h2>
1.750     raeburn  10593:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  10594: </h2>'.&selectfield(1,$is_tool).'
1.621     www      10595:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   10596:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10597:             </div>
                   10598:           </div>
1.600     www      10599: 
                   10600: 
1.621     www      10601:   </form>';
                   10602:     return $result;
                   10603: }
                   10604: 
1.443     banghart 10605: #--- Displays the submissions first page -------
                   10606: sub submit_options {
1.608     www      10607:     my ($request,$symb) = @_;
1.72      ng       10608:     if (!$symb) {return '';}
                   10609: 
1.746     raeburn  10610:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       10611:     &commonJSfunctions($request);
1.473     albertel 10612:     my $result;
1.533     bisitz   10613: 
1.72      ng       10614:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10615: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  10616:     $result.=&selectfield(1,$is_tool).'
1.601     www      10617:                 <input type="hidden" name="command" value="submission" /> 
                   10618: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10619:             </div>
                   10620:           </div>
                   10621:   </form>';
                   10622:     return $result;
                   10623: }
1.533     bisitz   10624: 
1.601     www      10625: sub selectfield {
1.745     raeburn  10626:    my ($full,$is_tool)=@_;
                   10627:    my %options;
                   10628:    if ($is_tool) {
                   10629:        %options =
                   10630:            (&transtatus_options,
                   10631:             'select_form_order' => ['yes','incorrect','all']);
                   10632:    } else {
                   10633:        %options = 
                   10634:            (&substatus_options,
                   10635:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10636:    }
1.782     raeburn  10637: 
                   10638:   #
                   10639:   # PrepareClasslist() needs to be called to avoid getting a sections list
                   10640:   # for a different course from the @Sections global in lonstatistics.pm, 
                   10641:   # populated by an earlier request.
                   10642:   #
                   10643:    &Apache::lonstatistics::PrepareClasslist();
                   10644: 
1.601     www      10645:    my $result='<div class="LC_columnSection">
1.537     harmsja  10646:   
1.533     bisitz   10647:     <fieldset>
                   10648:       <legend>
                   10649:        '.&mt('Sections').'
                   10650:       </legend>
1.601     www      10651:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10652:     </fieldset>
1.537     harmsja  10653:   
1.533     bisitz   10654:     <fieldset>
                   10655:       <legend>
                   10656:         '.&mt('Groups').'
                   10657:       </legend>
                   10658:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10659:     </fieldset>
1.537     harmsja  10660:   
1.533     bisitz   10661:     <fieldset>
                   10662:       <legend>
                   10663:         '.&mt('Access Status').'
                   10664:       </legend>
1.601     www      10665:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10666:     </fieldset>';
                   10667:     if ($full) {
1.745     raeburn  10668:         my $heading = &mt('Submission Status');
                   10669:         if ($is_tool) {
                   10670:             $heading = &mt('Transaction Status');
                   10671:         }
                   10672:         $result.='
1.533     bisitz   10673:     <fieldset>
                   10674:       <legend>
1.745     raeburn  10675:         '.$heading.'
1.601     www      10676:       </legend>'.
1.635     raeburn  10677:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      10678:    '</fieldset>';
                   10679:     }
                   10680:     $result.='</div><br />';
1.44      ng       10681:     return $result;
1.2       albertel 10682: }
                   10683: 
1.738     raeburn  10684: sub substatus_options {
                   10685:     return &Apache::lonlocal::texthash(
                   10686:                                       'yes'       => 'with submissions',
                   10687:                                       'queued'    => 'in grading queue',
                   10688:                                       'graded'    => 'with ungraded submissions',
                   10689:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10690:                                       'all'       => 'with any status',
                   10691:                                       );
1.738     raeburn  10692: }
                   10693: 
1.745     raeburn  10694: sub transtatus_options {
                   10695:     return &Apache::lonlocal::texthash(
                   10696:                                        'yes'       => 'with score transactions',
                   10697:                                        'incorrect' => 'with less than full credit',
                   10698:                                        'all'       => 'with any status',
                   10699:                                       );
                   10700: }
                   10701: 
1.285     albertel 10702: sub reset_perm {
                   10703:     undef(%perm);
                   10704: }
                   10705: 
                   10706: sub init_perm {
                   10707:     &reset_perm();
1.770     raeburn  10708:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 10709: 
                   10710: 	my $scope = $env{'request.course.id'};
                   10711: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10712: 
                   10713: 	    $scope .= '/'.$env{'request.course.sec'};
                   10714: 	    if ( $perm{$test_perm}=
                   10715: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10716: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10717: 	    } else {
                   10718: 		delete($perm{$test_perm});
                   10719: 	    }
1.285     albertel 10720: 	}
                   10721:     }
                   10722: }
                   10723: 
1.674     raeburn  10724: sub init_old_essays {
                   10725:     my ($symb,$apath,$adom,$aname) = @_;
                   10726:     if ($symb ne '') {
                   10727:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10728:         if (keys(%essays) > 0) {
                   10729:             $old_essays{$symb} = \%essays;
                   10730:         }
                   10731:     }
                   10732:     return;
                   10733: }
                   10734: 
                   10735: sub reset_old_essays {
                   10736:     undef(%old_essays);
                   10737: }
                   10738: 
1.400     www      10739: sub gather_clicker_ids {
1.408     albertel 10740:     my %clicker_ids;
1.400     www      10741: 
                   10742:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10743: 
                   10744:     # Set up a couple variables.
1.407     albertel 10745:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10746:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10747:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10748: 
1.407     albertel 10749:     foreach my $student (keys(%$classlist)) {
1.438     www      10750:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10751:         my $username = $classlist->{$student}->[$username_idx];
                   10752:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10753:         my $clickers =
1.408     albertel 10754: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10755:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10756:             $id=~s/^[\#0]+//;
1.421     www      10757:             $id=~s/[\-\:]//g;
1.407     albertel 10758:             if (exists($clicker_ids{$id})) {
1.408     albertel 10759: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10760:             } else {
1.408     albertel 10761: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10762:             }
                   10763:         }
                   10764:     }
1.407     albertel 10765:     return %clicker_ids;
1.400     www      10766: }
                   10767: 
1.402     www      10768: sub gather_adv_clicker_ids {
1.408     albertel 10769:     my %clicker_ids;
1.402     www      10770:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10771:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10772:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10773:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10774:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10775:             my ($puname,$pudom)=split(/\:/,$person);
                   10776:             my $clickers =
1.408     albertel 10777: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10778:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10779: 		$id=~s/^[\#0]+//;
1.421     www      10780:                 $id=~s/[\-\:]//g;
1.408     albertel 10781: 		if (exists($clicker_ids{$id})) {
                   10782: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10783: 		} else {
                   10784: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10785: 		}
1.405     www      10786:             }
1.402     www      10787:         }
                   10788:     }
1.407     albertel 10789:     return %clicker_ids;
1.402     www      10790: }
                   10791: 
1.413     www      10792: sub clicker_grading_parameters {
                   10793:     return ('gradingmechanism' => 'scalar',
                   10794:             'upfiletype' => 'scalar',
                   10795:             'specificid' => 'scalar',
                   10796:             'pcorrect' => 'scalar',
                   10797:             'pincorrect' => 'scalar');
                   10798: }
                   10799: 
1.400     www      10800: sub process_clicker {
1.608     www      10801:     my ($r,$symb)=@_;
1.400     www      10802:     if (!$symb) {return '';}
                   10803:     my $result=&checkforfile_js();
1.632     www      10804:     $result.=&Apache::loncommon::start_data_table().
                   10805:              &Apache::loncommon::start_data_table_header_row().
                   10806:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10807:              &Apache::loncommon::end_data_table_header_row().
                   10808:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10809: # Attempt to restore parameters from last session, set defaults if not present
                   10810:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10811:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10812:                                                  \%Saveable_Parameters);
                   10813:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10814:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10815:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10816:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10817: 
                   10818:     my %checked;
1.521     www      10819:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10820:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10821:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10822:        }
                   10823:     }
                   10824: 
1.632     www      10825:     my $upload=&mt("Evaluate File");
1.400     www      10826:     my $type=&mt("Type");
1.402     www      10827:     my $attendance=&mt("Award points just for participation");
                   10828:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10829:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10830:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10831:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10832:     my $pcorrect=&mt("Percentage points for correct solution");
                   10833:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10834:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10835: 						   {'iclicker' => 'i>clicker',
1.666     www      10836:                                                     'interwrite' => 'interwrite PRS',
                   10837:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10838:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10839:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10840: function sanitycheck() {
                   10841: // Accept only integer percentages
                   10842:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10843:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10844: // Find out grading choice
                   10845:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10846:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10847:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10848:       }
                   10849:    }
                   10850: // By default, new choice equals user selection
                   10851:    newgradingchoice=gradingchoice;
                   10852: // Not good to give more points for false answers than correct ones
                   10853:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10854:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10855:    }
                   10856: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10857:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10858:       document.forms.gradesupload.pcorrect.value=100;
                   10859:       document.forms.gradesupload.pincorrect.value=100;
                   10860:    }
                   10861: // If the values are different, cannot be attendance only
                   10862:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10863:        (gradingchoice=='attendance')) {
                   10864:        newgradingchoice='personnel';
                   10865:    }
                   10866: // Change grading choice to new one
                   10867:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10868:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10869:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10870:       } else {
                   10871:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10872:       }
                   10873:    }
                   10874: // Remember the old state
                   10875:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10876: }
1.597     wenzelju 10877: ENDUPFORM
                   10878:     $result.= <<ENDUPFORM;
1.400     www      10879: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10880: <input type="hidden" name="symb" value="$symb" />
                   10881: <input type="hidden" name="command" value="processclickerfile" />
                   10882: <input type="file" name="upfile" size="50" />
                   10883: <br /><label>$type: $selectform</label>
1.632     www      10884: ENDUPFORM
                   10885:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10886:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10887:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10888: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10889: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10890: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10891: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10892: <br />&nbsp;&nbsp;&nbsp;
                   10893: <input type="text" name="givenanswer" size="50" />
1.413     www      10894: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10895: ENDGRADINGFORM
1.766     raeburn  10896:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      10897:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10898:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10899: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10900: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  10901: </form>
1.632     www      10902: ENDPERCFORM
                   10903:     $result.='</td>'.
                   10904:              &Apache::loncommon::end_data_table_row().
                   10905:              &Apache::loncommon::end_data_table();
1.400     www      10906:     return $result;
                   10907: }
                   10908: 
                   10909: sub process_clicker_file {
1.766     raeburn  10910:     my ($r,$symb) = @_;
1.400     www      10911:     if (!$symb) {return '';}
1.413     www      10912: 
                   10913:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10914:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10915:                                               \%Saveable_Parameters);
1.598     www      10916:     my $result='';
1.404     www      10917:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10918: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10919: 	return $result;
1.404     www      10920:     }
1.522     www      10921:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10922:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10923:         return $result;
1.521     www      10924:     }
1.522     www      10925:     my $foundgiven=0;
1.521     www      10926:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10927:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10928:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10929:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10930:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10931:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10932:         $foundgiven=$#answers+1;
1.521     www      10933:     }
1.407     albertel 10934:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10935:     my %correct_ids;
1.404     www      10936:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10937: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10938:     }
                   10939:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10940: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10941: 	   $correct_id=~tr/a-z/A-Z/;
                   10942: 	   $correct_id=~s/\s//gs;
                   10943: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10944:            $correct_id=~s/[\-\:]//g;
1.414     www      10945:            if ($correct_id) {
                   10946: 	      $correct_ids{$correct_id}='specified';
                   10947:            }
                   10948:         }
1.400     www      10949:     }
1.404     www      10950:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10951: 	$result.=&mt('Score based on attendance only');
1.521     www      10952:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10953:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10954:     } else {
1.408     albertel 10955: 	my $number=0;
1.411     www      10956: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10957: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10958: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10959: 	    if ($correct_ids{$id} eq 'specified') {
                   10960: 		$result.=&mt('specified');
                   10961: 	    } else {
                   10962: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10963: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10964: 	    }
                   10965: 	    $number++;
                   10966: 	}
1.411     www      10967:         $result.="</p>\n";
1.710     bisitz   10968:         if ($number==0) {
                   10969:             $result .=
                   10970:                  &Apache::lonhtmlcommon::confirm_success(
                   10971:                      &mt('No IDs found to determine correct answer'),1);
                   10972:             return $result;
                   10973:         }
1.404     www      10974:     }
1.405     www      10975:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10976:         $result .=
                   10977:             &Apache::lonhtmlcommon::confirm_success(
                   10978:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10979:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10980:         return $result;
1.405     www      10981:     }
1.760     raeburn  10982:     my $mimetype;
                   10983:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10984:         my $mm = new File::MMagic;
                   10985:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10986:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10987:             $result.= '<p>'.
                   10988:                 &Apache::lonhtmlcommon::confirm_success(
                   10989:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   10990:             return $result;
                   10991:         }
                   10992:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10993:         $result .= '<p>'.
                   10994:             &Apache::lonhtmlcommon::confirm_success(
                   10995:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   10996:         return $result;
                   10997:     }
1.410     www      10998: 
                   10999: # Were able to get all the info needed, now analyze the file
                   11000: 
1.411     www      11001:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 11002:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      11003:     $result.=&Apache::loncommon::start_data_table().
                   11004:              &Apache::loncommon::start_data_table_header_row().
                   11005:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   11006:              &Apache::loncommon::end_data_table_header_row().
                   11007:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   11008: <td>
1.410     www      11009: <form method="post" action="/adm/grades" name="clickeranalysis">
                   11010: <input type="hidden" name="symb" value="$symb" />
                   11011: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      11012: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   11013: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   11014: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      11015: ENDHEADER
1.522     www      11016:     if ($env{'form.gradingmechanism'} eq 'given') {
                   11017:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   11018:     } 
1.408     albertel 11019:     my %responses;
                   11020:     my @questiontitles;
1.405     www      11021:     my $errormsg='';
                   11022:     my $number=0;
                   11023:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  11024:         if ($mimetype eq 'text/plain') {
                   11025:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   11026:         } elsif ($mimetype eq 'text/html') {
                   11027:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   11028:         }
                   11029:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      11030:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  11031:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      11032:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   11033:     }
1.411     www      11034:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   11035:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   11036:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   11037:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   11038:              '<br />';
1.522     www      11039:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   11040:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      11041:        return $result;
1.522     www      11042:     } 
1.414     www      11043: # Remember Question Titles
                   11044: # FIXME: Possibly need delimiter other than ":"
                   11045:     for (my $i=0;$i<$number;$i++) {
                   11046:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   11047:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   11048:     }
1.411     www      11049:     my $correct_count=0;
                   11050:     my $student_count=0;
                   11051:     my $unknown_count=0;
1.414     www      11052: # Match answers with usernames
                   11053: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 11054:     foreach my $id (keys(%responses)) {
1.410     www      11055:        if ($correct_ids{$id}) {
1.414     www      11056:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      11057:           $correct_count++;
1.410     www      11058:        } elsif ($clicker_ids{$id}) {
1.437     www      11059:           if ($clicker_ids{$id}=~/\,/) {
                   11060: # More than one user with the same clicker!
1.632     www      11061:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11062:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11063:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      11064:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11065:                            "<select name='multi".$id."'>";
                   11066:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   11067:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   11068:              }
                   11069:              $result.='</select>';
                   11070:              $unknown_count++;
                   11071:           } else {
                   11072: # Good: found one and only one user with the right clicker
                   11073:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   11074:              $student_count++;
                   11075:           }
1.410     www      11076:        } else {
1.632     www      11077:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11078:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11079:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      11080:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11081:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   11082:                    "\n".&mt("Domain").": ".
                   11083:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  11084:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      11085:           $unknown_count++;
1.410     www      11086:        }
1.405     www      11087:     }
1.412     www      11088:     $result.='<hr />'.
                   11089:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      11090:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      11091:        if ($correct_count==0) {
1.696     bisitz   11092:           $errormsg.="Found no correct answers for grading!";
1.412     www      11093:        } elsif ($correct_count>1) {
1.414     www      11094:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      11095:        }
                   11096:     }
1.428     www      11097:     if ($number<1) {
                   11098:        $errormsg.="Found no questions.";
                   11099:     }
1.412     www      11100:     if ($errormsg) {
                   11101:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   11102:     } else {
                   11103:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   11104:     }
1.632     www      11105:     $result.='</form></td>'.
                   11106:              &Apache::loncommon::end_data_table_row().
                   11107:              &Apache::loncommon::end_data_table();
1.614     www      11108:     return $result;
1.400     www      11109: }
                   11110: 
1.405     www      11111: sub iclicker_eval {
1.406     www      11112:     my ($questiontitles,$responses)=@_;
1.405     www      11113:     my $number=0;
                   11114:     my $errormsg='';
                   11115:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      11116:         my %components=&Apache::loncommon::record_sep($line);
                   11117:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 11118: 	if ($entries[0] eq 'Question') {
                   11119: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   11120: 		$$questiontitles[$number]=$entries[$i];
                   11121: 		$number++;
                   11122: 	    }
                   11123: 	}
                   11124: 	if ($entries[0]=~/^\#/) {
                   11125: 	    my $id=$entries[0];
                   11126: 	    my @idresponses;
                   11127: 	    $id=~s/^[\#0]+//;
                   11128: 	    for (my $i=0;$i<$number;$i++) {
                   11129: 		my $idx=3+$i*6;
1.644     www      11130:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 11131: 		push(@idresponses,$entries[$idx]);
                   11132: 	    }
                   11133: 	    $$responses{$id}=join(',',@idresponses);
                   11134: 	}
1.405     www      11135:     }
                   11136:     return ($errormsg,$number);
                   11137: }
                   11138: 
1.760     raeburn  11139: sub iclickerxml_eval {
                   11140:     my ($questiontitles,$responses)=@_;
                   11141:     my $number=0;
                   11142:     my $errormsg='';
                   11143:     my @state;
                   11144:     my %respbyid;
                   11145:     my $p = HTML::Parser->new
                   11146:     (
                   11147:         xml_mode => 1,
                   11148:         start_h =>
                   11149:             [sub {
                   11150:                  my ($tagname,$attr) = @_;
                   11151:                  push(@state,$tagname);
                   11152:                  if ("@state" eq "ssn p") {
                   11153:                      my $title = $attr->{qn};
                   11154:                      $title =~ s/(^\s+|\s+$)//g;
                   11155:                      $questiontitles->[$number]=$title;
                   11156:                  } elsif ("@state" eq "ssn p v") {
                   11157:                      my $id = $attr->{id};
                   11158:                      my $entry = $attr->{ans};
                   11159:                      $id=~s/^[\#0]+//;
                   11160:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   11161:                      $respbyid{$id}[$number] = $entry;
                   11162:                  }
                   11163:             }, "tagname, attr"],
                   11164:          end_h =>
                   11165:                [sub {
                   11166:                    my ($tagname) = @_;
                   11167:                    if ("@state" eq "ssn p") {
                   11168:                        $number++;
                   11169:                    }
                   11170:                    pop(@state);
                   11171:                 }, "tagname"],
                   11172:     );
                   11173: 
                   11174:     $p->parse($env{'form.upfile'});
                   11175:     $p->eof;
                   11176:     foreach my $id (keys(%respbyid)) {
                   11177:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   11178:     }
                   11179:     return ($errormsg,$number);
                   11180: }
                   11181: 
1.419     www      11182: sub interwrite_eval {
                   11183:     my ($questiontitles,$responses)=@_;
                   11184:     my $number=0;
                   11185:     my $errormsg='';
1.420     www      11186:     my $skipline=1;
                   11187:     my $questionnumber=0;
                   11188:     my %idresponses=();
1.419     www      11189:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11190:         my %components=&Apache::loncommon::record_sep($line);
                   11191:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      11192:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   11193:         if ($entries[1] eq 'Response') { $skipline=1; }
                   11194:         next if $skipline;
                   11195:         if ($entries[0]!=$questionnumber) {
                   11196:            $questionnumber=$entries[0];
                   11197:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   11198:            $number++;
1.419     www      11199:         }
1.420     www      11200:         my $id=$entries[4];
                   11201:         $id=~s/^[\#0]+//;
1.421     www      11202:         $id=~s/^v\d*\://i;
                   11203:         $id=~s/[\-\:]//g;
1.420     www      11204:         $idresponses{$id}[$number]=$entries[6];
                   11205:     }
1.524     raeburn  11206:     foreach my $id (keys(%idresponses)) {
1.420     www      11207:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   11208:        $$responses{$id}=~s/^\s*\,//;
1.419     www      11209:     }
                   11210:     return ($errormsg,$number);
                   11211: }
                   11212: 
1.666     www      11213: sub turning_eval {
                   11214:     my ($questiontitles,$responses)=@_;
                   11215:     my $number=0;
                   11216:     my $errormsg='';
                   11217:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11218:         my %components=&Apache::loncommon::record_sep($line);
                   11219:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   11220:         if ($#entries>$number) { $number=$#entries; }
                   11221:         my $id=$entries[0];
                   11222:         my @idresponses;
                   11223:         $id=~s/^[\#0]+//;
                   11224:         unless ($id) { next; }
                   11225:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   11226:             $entries[$idx]=~s/\,/\;/g;
                   11227:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   11228:             push(@idresponses,$entries[$idx]);
                   11229:         }
                   11230:         $$responses{$id}=join(',',@idresponses);
                   11231:     }
                   11232:     for (my $i=1; $i<=$number; $i++) {
                   11233:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   11234:     }
                   11235:     return ($errormsg,$number);
                   11236: }
                   11237: 
                   11238: 
1.414     www      11239: sub assign_clicker_grades {
1.766     raeburn  11240:     my ($r,$symb) = @_;
1.414     www      11241:     if (!$symb) {return '';}
1.416     www      11242: # See which part we are saving to
1.582     raeburn  11243:     my $res_error;
                   11244:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   11245:     if ($res_error) {
                   11246:         return &navmap_errormsg();
                   11247:     }
1.416     www      11248: # FIXME: This should probably look for the first handgradeable part
                   11249:     my $part=$$partlist[0];
                   11250: # Start screen output
1.766     raeburn  11251:     my $result = &Apache::loncommon::start_data_table().
                   11252:                  &Apache::loncommon::start_data_table_header_row().
                   11253:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   11254:                  &Apache::loncommon::end_data_table_header_row().
                   11255:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11256: # Get correct result
                   11257: # FIXME: Possibly need delimiter other than ":"
                   11258:     my @correct=();
1.415     www      11259:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11260:     my $number=$env{'form.number'};
                   11261:     if ($gradingmechanism ne 'attendance') {
1.414     www      11262:        foreach my $key (keys(%env)) {
                   11263:           if ($key=~/^form\.correct\:/) {
                   11264:              my @input=split(/\,/,$env{$key});
                   11265:              for (my $i=0;$i<=$#input;$i++) {
                   11266:                  if (($correct[$i]) && ($input[$i]) &&
                   11267:                      ($correct[$i] ne $input[$i])) {
                   11268:                     $result.='<br /><span class="LC_warning">'.
                   11269:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11270:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      11271:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11272:                     $correct[$i]=$input[$i];
                   11273:                  }
                   11274:              }
                   11275:           }
                   11276:        }
1.415     www      11277:        for (my $i=0;$i<$number;$i++) {
1.644     www      11278:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11279:              $result.='<br /><span class="LC_error">'.
                   11280:                       &mt('No correct result given for question "[_1]"!',
                   11281:                           $env{'form.question:'.$i}).'</span>';
                   11282:           }
                   11283:        }
1.644     www      11284:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11285:     }
                   11286: # Start grading
1.415     www      11287:     my $pcorrect=$env{'form.pcorrect'};
                   11288:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11289:     my $storecount=0;
1.632     www      11290:     my %users=();
1.415     www      11291:     foreach my $key (keys(%env)) {
1.420     www      11292:        my $user='';
1.415     www      11293:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11294:           $user=$1;
                   11295:        }
                   11296:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11297:           my $id=$1;
                   11298:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11299:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11300:           } elsif ($env{'form.multi'.$id}) {
                   11301:              $user=$env{'form.multi'.$id};
1.420     www      11302:           }
                   11303:        }
1.632     www      11304:        if ($user) {
                   11305:           if ($users{$user}) {
                   11306:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   11307:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      11308:                       '</span><br />';
                   11309:           }
                   11310:           $users{$user}=1; 
1.415     www      11311:           my @answer=split(/\,/,$env{$key});
                   11312:           my $sum=0;
1.522     www      11313:           my $realnumber=$number;
1.415     www      11314:           for (my $i=0;$i<$number;$i++) {
1.576     www      11315:              if  ($correct[$i] eq '-') {
                   11316:                 $realnumber--;
1.766     raeburn  11317:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11318:                 if ($gradingmechanism eq 'attendance') {
                   11319:                    $sum+=$pcorrect;
1.576     www      11320:                 } elsif ($correct[$i] eq '*') {
1.522     www      11321:                    $sum+=$pcorrect;
1.415     www      11322:                 } else {
1.644     www      11323: # We actually grade if correct or not
                   11324:                    my $increment=$pincorrect;
                   11325: # Special case: numerical answer "0"
                   11326:                    if ($correct[$i] eq '0') {
                   11327:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11328:                          $increment=$pcorrect;
                   11329:                       }
                   11330: # General numerical answer, both evaluate to something non-zero
                   11331:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11332:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11333:                          $increment=$pcorrect;
                   11334:                       }
                   11335: # Must be just alphanumeric
                   11336:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11337:                       $increment=$pcorrect;
1.415     www      11338:                    }
1.644     www      11339:                    $sum+=$increment;
1.415     www      11340:                 }
                   11341:              }
                   11342:           }
1.522     www      11343:           my $ave=$sum/(100*$realnumber);
1.416     www      11344: # Store
                   11345:           my ($username,$domain)=split(/\:/,$user);
                   11346:           my %grades=();
                   11347:           $grades{"resource.$part.solved"}='correct_by_override';
                   11348:           $grades{"resource.$part.awarded"}=$ave;
                   11349:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11350:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11351:                                                  $env{'request.course.id'},
                   11352:                                                  $domain,$username);
                   11353:           if ($returncode ne 'ok') {
                   11354:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11355:           } else {
                   11356:              $storecount++;
                   11357:           }
1.415     www      11358:        }
                   11359:     }
                   11360: # We are done
1.549     hauer    11361:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      11362:              '</td>'.
                   11363:              &Apache::loncommon::end_data_table_row().
                   11364:              &Apache::loncommon::end_data_table();
1.614     www      11365:     return $result;
1.414     www      11366: }
                   11367: 
1.582     raeburn  11368: sub navmap_errormsg {
                   11369:     return '<div class="LC_error">'.
                   11370:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11371:            &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  11372:            '</div>';
                   11373: }
1.607     droeschl 11374: 
1.609     www      11375: sub startpage {
1.777     raeburn  11376:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  11377:     my %args;
                   11378:     if ($onload) {
                   11379:          my %loaditems = (
                   11380:                         'onload' => $onload,
                   11381:                       );
                   11382:          $args{'add_entries'} = \%loaditems;
                   11383:     }
1.671     raeburn  11384:     if ($nomenu) {
1.754     raeburn  11385:         $args{'only_body'} = 1; 
1.777     raeburn  11386:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  11387:     } else {
                   11388:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.754     raeburn  11389:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  11390:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  11391:         if ($env{'request.course.id'}) {
                   11392:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   11393:         }
1.671     raeburn  11394:     }
1.613     www      11395:     unless ($nodisplayflag) {
1.773     raeburn  11396:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      11397:     }
1.607     droeschl 11398: }
1.582     raeburn  11399: 
1.622     www      11400: sub select_problem {
                   11401:     my ($r)=@_;
1.632     www      11402:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  11403:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      11404:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11405:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11406: }
                   11407: 
1.1       albertel 11408: sub handler {
1.41      ng       11409:     my $request=$_[0];
1.434     albertel 11410:     &reset_caches();
1.646     raeburn  11411:     if ($request->header_only) {
                   11412:         &Apache::loncommon::content_type($request,'text/html');
                   11413:         $request->send_http_header;
                   11414:         return OK;
                   11415:     }
                   11416:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   11417: 
1.664     raeburn  11418: # see what command we need to execute
                   11419: 
                   11420:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11421:     my $command=$commands[0];
                   11422: 
1.646     raeburn  11423:     &init_perm();
                   11424:     if (!$env{'request.course.id'}) {
1.664     raeburn  11425:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11426:                 ($command =~ /^scantronupload/)) {
                   11427:             # Not in a course.
                   11428:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11429:             return HTTP_NOT_ACCEPTABLE;
                   11430:         }
1.646     raeburn  11431:     } elsif (!%perm) {
                   11432:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  11433:         return OK;
1.41      ng       11434:     }
1.646     raeburn  11435:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       11436:     $request->send_http_header;
1.646     raeburn  11437: 
1.160     albertel 11438:     if ($#commands > 0) {
                   11439: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11440:     }
1.608     www      11441: 
                   11442: # see what the symb is
                   11443: 
                   11444:     my $symb=$env{'form.symb'};
                   11445:     unless ($symb) {
                   11446:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11447:        $symb=&Apache::lonnet::symbread($url);
                   11448:     }
1.646     raeburn  11449:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      11450: 
1.513     foxr     11451:     $ssi_error = 0;
1.637     www      11452:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      11453: #
1.637     www      11454: # Not called from a resource, but inside a course
1.601     www      11455: #    
1.622     www      11456:         &startpage($request,undef,[],1,1);
                   11457:         &select_problem($request);
1.41      ng       11458:     } else {
1.104     albertel 11459: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  11460:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  11461:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11462:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11463:                     &choose_task_version_form($symb,$env{'form.student'},
                   11464:                                               $env{'form.userdom'});
                   11465:             }
1.773     raeburn  11466:             my $divforres;
                   11467:             if ($env{'form.student'} eq '') {
                   11468:                 $js .= &part_selector_js();
                   11469:                 $onload = "toggleParts('gradesub');";
                   11470:             } else {
                   11471:                 $divforres = 1;
                   11472:             }
1.778     raeburn  11473:             my $head_extra = $js;
                   11474:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11475:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11476:                 if ($csslinks) {
                   11477:                     $head_extra .= "\n$csslinks";
                   11478:                 }
                   11479:             }
1.777     raeburn  11480:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   11481:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  11482:             if ($versionform) {
1.775     raeburn  11483:                 if ($divforres) {
                   11484:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   11485:                 }
1.671     raeburn  11486:                 $request->print($versionform);
                   11487:             }
1.773     raeburn  11488: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  11489:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11490:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11491:                 &choose_task_version_form($symb,$env{'form.student'},
                   11492:                                           $env{'form.userdom'},
                   11493:                                           $env{'form.inhibitmenu'});
1.778     raeburn  11494:             my $head_extra = $js;
                   11495:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11496:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11497:                 if ($csslinks) {
                   11498:                     $head_extra .= "\n$csslinks";
                   11499:                 }
                   11500:             }
1.777     raeburn  11501:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   11502:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  11503:             if ($versionform) {
                   11504:                 $request->print($versionform);
                   11505:             }
                   11506:             $request->print('<br clear="all" />');
                   11507:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 11508: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      11509:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11510:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      11511: 	    &pickStudentPage($request,$symb);
1.103     albertel 11512: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  11513:             my $csslinks;
                   11514:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11515:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  11516:             }
1.615     www      11517:             &startpage($request,$symb,
                   11518:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11519:                                        {href=>'',text=>'Select student'},
1.777     raeburn  11520:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      11521: 	    &displayPage($request,$symb);
1.104     albertel 11522: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      11523:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11524:                                        {href=>'',text=>'Select student'},
                   11525:                                        {href=>'',text=>'Grade student'},
                   11526:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      11527: 	    &updateGradeByPage($request,$symb);
1.104     albertel 11528: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  11529:             my $csslinks;
                   11530:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11531:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11532:             }
1.619     www      11533:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  11534:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      11535: 	    &processGroup($request,$symb);
1.104     albertel 11536: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      11537:             &startpage($request,$symb);
                   11538: 	    $request->print(&grading_menu($request,$symb));
1.598     www      11539: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      11540:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      11541: 	    $request->print(&submit_options($request,$symb));
1.598     www      11542:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  11543:             my $js = &part_selector_js();
                   11544:             my $onload = "toggleParts('gradesub');";
                   11545:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11546:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      11547:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      11548:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      11549:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      11550:             $request->print(&submit_options_table($request,$symb));
1.598     www      11551:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      11552:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      11553:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 11554: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      11555:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      11556: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 11557: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      11558:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11559:                                        {href=>'',text=>'Store grades'}]);
1.608     www      11560: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 11561: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      11562:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11563:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11564:                                                                              text=>"Modify grades"},
                   11565:                                        {href=>'', text=>"Store grades"}]);
1.608     www      11566: 	    $request->print(&editgrades($request,$symb));
1.602     www      11567:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      11568:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      11569:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 11570: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      11571:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11572:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      11573: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      11574:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      11575:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      11576:             $request->print(&process_clicker($request,$symb));
1.400     www      11577:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      11578:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11579:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      11580:             $request->print(&process_clicker_file($request,$symb));
1.414     www      11581:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      11582:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11583:                                        {href=>'', text=>'Process clicker file'},
                   11584:                                        {href=>'', text=>'Store grades'}]);
1.608     www      11585:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 11586: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      11587:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11588: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 11589: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      11590:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11591: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 11592: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      11593:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11594: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 11595: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 11596: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      11597:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11598: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       11599: 	    } else {
1.257     albertel 11600: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11601: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       11602: 		} else {
1.257     albertel 11603: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       11604: 		}
1.627     www      11605:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11606: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       11607: 	    }
1.246     albertel 11608: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      11609:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11610: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 11611: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  11612:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11613:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      11614: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 11615:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      11616:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11617:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 11618: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      11619:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11620: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 11621: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      11622:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11623: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 11624:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  11625:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  11626:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11627:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      11628:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 11629:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  11630:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      11631:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11632:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  11633:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      11634:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11635:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  11636:         } elsif ($command eq 'scantronupload_delete' &&
                   11637:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   11638:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11639:             &scantron_upload_delete($request,$symb);
1.523     raeburn  11640:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      11641:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      11642:             $request->print(&checkscantron_results($request,$symb));
                   11643:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  11644:             my $js = &part_selector_js();
                   11645:             my $onload = "toggleParts('gradingMenu');";
                   11646:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11647:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      11648:             $request->print(&submit_options_download($request,$symb));
                   11649:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11650:             &startpage($request,$symb,
                   11651:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  11652:     {href=>'', text=>'Download submitted files'}],
                   11653:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  11654:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      11655:             &submit_download_link($request,$symb);
1.106     albertel 11656: 	} elsif ($command) {
1.620     www      11657:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   11658: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 11659: 	}
1.2       albertel 11660:     }
1.513     foxr     11661:     if ($ssi_error) {
                   11662: 	&ssi_print_error($request);
                   11663:     }
1.671     raeburn  11664:     if ($env{'form.inhibitmenu'}) {
                   11665:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  11666:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  11667:         &Apache::lonquickgrades::endGradeScreen($request);
                   11668:     }
1.434     albertel 11669:     &reset_caches();
1.646     raeburn  11670:     return OK;
1.44      ng       11671: }
                   11672: 
1.1       albertel 11673: 1;
                   11674: 
1.13      albertel 11675: __END__;
1.531     jms      11676: 
                   11677: 
                   11678: =head1 NAME
                   11679: 
                   11680: Apache::grades
                   11681: 
                   11682: =head1 SYNOPSIS
                   11683: 
                   11684: Handles the viewing of grades.
                   11685: 
                   11686: This is part of the LearningOnline Network with CAPA project
                   11687: described at http://www.lon-capa.org.
                   11688: 
                   11689: =head1 OVERVIEW
                   11690: 
                   11691: Do an ssi with retries:
1.715     bisitz   11692: While I'd love to factor out this with the version in lonprintout,
1.531     jms      11693: 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
                   11694: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11695: 
                   11696: At least the logic that drives this has been pulled out into loncommon.
                   11697: 
                   11698: 
                   11699: 
                   11700: ssi_with_retries - Does the server side include of a resource.
                   11701:                      if the ssi call returns an error we'll retry it up to
                   11702:                      the number of times requested by the caller.
1.715     bisitz   11703:                      If we still have a problem, no text is appended to the
1.531     jms      11704:                      output and we set some global variables.
                   11705:                      to indicate to the caller an SSI error occurred.  
                   11706:                      All of this is supposed to deal with the issues described
1.715     bisitz   11707:                      in LON-CAPA BZ 5631 see:
1.531     jms      11708:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11709:                      by informing the user that this happened.
                   11710: 
                   11711: Parameters:
                   11712:   resource   - The resource to include.  This is passed directly, without
                   11713:                interpretation to lonnet::ssi.
                   11714:   form       - The form hash parameters that guide the interpretation of the resource
                   11715:                
                   11716:   retries    - Number of retries allowed before giving up completely.
                   11717: Returns:
                   11718:   On success, returns the rendered resource identified by the resource parameter.
                   11719: Side Effects:
                   11720:   The following global variables can be set:
                   11721:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11722:                               It is up to the caller to initialize this to false
                   11723:                               if desired.
                   11724:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11725:                               of the resource that could not be rendered by the ssi
                   11726:                               call.
                   11727:    ssi_error_message   - The error string fetched from the ssi response
                   11728:                               in the event of an error.
                   11729: 
                   11730: 
                   11731: =head1 HANDLER SUBROUTINE
                   11732: 
                   11733: ssi_with_retries()
                   11734: 
                   11735: =head1 SUBROUTINES
                   11736: 
                   11737: =over
                   11738: 
1.671     raeburn  11739: =head1 Routines to display previous version of a Task for a specific student
                   11740: 
                   11741: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   11742: can receive another opportunity. Access to tasks is slot-based. If a slot
                   11743: requires a proctor to check-in the student, a new version of the Task will
                   11744: be created when the student is checked in to the new opportunity.
                   11745: 
                   11746: If a particular student has tried two or more versions of a particular task,
                   11747: the submission screen provides a user with vgr privileges (e.g., a Course
                   11748: Coordinator) the ability to display a previous version worked on by the
                   11749: student.  By default, the current version is displayed. If a previous version
                   11750: has been selected for display, submission data are only shown that pertain
                   11751: to that particular version, and the interface to submit grades is not shown.
                   11752: 
                   11753: =over 4
                   11754: 
                   11755: =item show_previous_task_version()
                   11756: 
                   11757: Displays a specified version of a student's Task, as the student sees it.
                   11758: 
                   11759: Inputs: 2
                   11760:         request - request object
                   11761:         symb    - unique symb for current instance of resource
                   11762: 
                   11763: Output: None.
                   11764: 
                   11765: Side Effects: calls &show_problem() to print version of Task, with
                   11766:               version contained in form item: $env{'form.previousversion'}
                   11767: 
                   11768: =item choose_task_version_form()
                   11769: 
                   11770: Displays a web form used to select which version of a student's view of a
                   11771: Task should be displayed.  Either launches a pop-up window, or replaces
                   11772: content in existing pop-up, or replaces page in main window.
                   11773: 
                   11774: Inputs: 4
                   11775:         symb    - unique symb for current instance of resource
                   11776:         uname   - username of student
                   11777:         udom    - domain of student
                   11778:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11779:                   breadcrumbs etc., are displayed
                   11780: 
                   11781: Output: 4
                   11782:         current   - student's current version
                   11783:         displayed - student's version being displayed
                   11784:         result    - scalar containing HTML for web form used to switch to
                   11785:                     a different version (or a link to close window, if pop-up).
                   11786:         js        - javascript for processing selection in versions web form
                   11787: 
                   11788: Side Effects: None.
                   11789: 
                   11790: =item previous_display_javascript()
                   11791: 
                   11792: Inputs: 2
                   11793:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11794:                   breadcrumbs etc., are displayed.
                   11795:         current - student's current version number.
                   11796: 
                   11797: Output: 1
                   11798:         js      - javascript for processing selection in versions web form.
                   11799: 
                   11800: Side Effects: None.
                   11801: 
                   11802: =back
                   11803: 
                   11804: =head1 Routines to process bubblesheet data.
                   11805: 
                   11806: =over 4
                   11807: 
1.531     jms      11808: =item scantron_get_correction() : 
                   11809: 
                   11810:    Builds the interface screen to interact with the operator to fix a
                   11811:    specific error condition in a specific scanline
                   11812: 
                   11813:  Arguments:
                   11814:     $r           - Apache request object
                   11815:     $i           - number of the current scanline
                   11816:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  11817:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11818:     $line        - full contents of the current scanline
                   11819:     $error       - error condition, valid values are
                   11820:                    'incorrectCODE', 'duplicateCODE',
                   11821:                    'doublebubble', 'missingbubble',
                   11822:                    'duplicateID', 'incorrectID'
                   11823:     $arg         - extra information needed
                   11824:        For errors:
                   11825:          - duplicateID   - paper number that this studentID was seen before on
                   11826:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11827:                            seen on before
                   11828:          - incorrectCODE - current incorrect CODE 
                   11829:          - doublebubble  - array ref of the bubble lines that have double
                   11830:                            bubble errors
                   11831:          - missingbubble - array ref of the bubble lines that have missing
                   11832:                            bubble errors
                   11833: 
1.691     raeburn  11834:    $randomorder - True if exam folder has randomorder set
                   11835:    $randompick  - True if exam folder has randompick set
                   11836:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11837:                      for current line to question number used for same question
                   11838:                      in "Master Seqence" (as seen by Course Coordinator).
                   11839:    $startline   - Reference to hash where key is question number (0 is first)
                   11840:                   and value is number of first bubble line for current student
                   11841:                   or code-based randompick and/or randomorder.
                   11842: 
                   11843: 
                   11844: 
1.531     jms      11845: =item  scantron_get_maxbubble() : 
                   11846: 
1.582     raeburn  11847:    Arguments:
                   11848:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11849:                       failure to retrieve a navmap object.
                   11850:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11851:        calling routine should trap the error condition and display the warning
                   11852:        found in &navmap_errormsg().
                   11853: 
1.649     raeburn  11854:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11855: 
1.531     jms      11856:    Returns the maximum number of bubble lines that are expected to
                   11857:    occur. Does this by walking the selected sequence rendering the
                   11858:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11859:    for what the current value of the problem counter is.
                   11860: 
                   11861:    Caches the results to $env{'form.scantron_maxbubble'},
                   11862:    $env{'form.scantron.bubble_lines.n'}, 
                   11863:    $env{'form.scantron.first_bubble_line.n'} and
                   11864:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11865:    which are the total number of bubble lines, the number of bubble
1.531     jms      11866:    lines for response n and number of the first bubble line for response n,
                   11867:    and a comma separated list of numbers of bubble lines for sub-questions
                   11868:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11869: 
                   11870: 
                   11871: =item  scantron_validate_missingbubbles() : 
                   11872: 
                   11873:    Validates all scanlines in the selected file to not have any
                   11874:     answers that don't have bubbles that have not been verified
                   11875:     to be bubble free.
                   11876: 
                   11877: =item  scantron_process_students() : 
                   11878: 
1.659     raeburn  11879:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11880: 
                   11881:    The parsed scanline hash is added to %env 
                   11882: 
                   11883:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11884:    foreach resource , with the form data of
                   11885: 
                   11886: 	'submitted'     =>'scantron' 
                   11887: 	'grade_target'  =>'grade',
                   11888: 	'grade_username'=> username of student
                   11889: 	'grade_domain'  => domain of student
                   11890: 	'grade_courseid'=> of course
                   11891: 	'grade_symb'    => symb of resource to grade
                   11892: 
                   11893:     This triggers a grading pass. The problem grading code takes care
                   11894:     of converting the bubbled letter information (now in %env) into a
                   11895:     valid submission.
                   11896: 
                   11897: =item  scantron_upload_scantron_data() :
                   11898: 
1.659     raeburn  11899:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11900: 
                   11901: =item  scantron_upload_scantron_data_save() : 
                   11902: 
                   11903:    Adds a provided bubble information data file to the course if user
1.770     raeburn  11904:    has the correct privileges to do so.
                   11905: 
                   11906: = item scantron_upload_delete() :
                   11907: 
                   11908:    Deletes a previously uploaded bubble information data file, if user
                   11909:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      11910: 
                   11911: =item  valid_file() :
                   11912: 
                   11913:    Validates that the requested bubble data file exists in the course.
                   11914: 
                   11915: =item  scantron_download_scantron_data() : 
                   11916: 
                   11917:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11918:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11919:    course.
                   11920: 
                   11921: =item  scantron_validate_ID() : 
                   11922: 
                   11923:    Validates all scanlines in the selected file to not have any
1.556     weissno  11924:    invalid or underspecified student/employee IDs
1.531     jms      11925: 
1.582     raeburn  11926: =item navmap_errormsg() :
                   11927: 
                   11928:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11929:    Should be called whenever the request to instantiate a navmap object fails.
                   11930: 
                   11931: =back
1.582     raeburn  11932: 
1.531     jms      11933: =back
                   11934: 
                   11935: =cut

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