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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.787   ! raeburn     4: # $Id: grades.pm,v 1.786 2021/12/17 15:16:51 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'};
1.786     raeburn  3187:     my ($res_error,%queueable);
                   3188:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3189:     if ($res_error) {
                   3190:         $request->print(&navmap_errormsg());
                   3191:         return;
                   3192:     } else {
                   3193:         foreach my $part (@{$partlist}) {
                   3194:             if (ref($responseType->{$part}) eq 'HASH') {
                   3195:                 foreach my $id (keys(%{$responseType->{$part}})) {
                   3196:                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   3197:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   3198:                         $queueable{$part} = 1;
                   3199:                         last;
                   3200:                     }
                   3201:                 }
                   3202:             }
                   3203:         }
                   3204:     }
1.301     albertel 3205: 
1.44      ng       3206:     if ($button eq 'Save & Next') {
                   3207: 	my $ctr = 0;
                   3208: 	while ($ctr < $ngrade) {
1.257     albertel 3209: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  3210: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
1.786     raeburn  3211:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
1.71      ng       3212: 	    if ($errorflag eq 'no_score') {
                   3213: 		$ctr++;
                   3214: 		next;
                   3215: 	    }
1.104     albertel 3216: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3217: 		$request->print(
                   3218:                     '<span class="LC_error">'
                   3219:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3220:                    .'</span>');
1.104     albertel 3221: 		$ctr++;
                   3222: 		next;
                   3223: 	    }
1.726     raeburn  3224:             if ($numhidden) {
                   3225:                 $request->print(
                   3226:                     '<span class="LC_info">'
                   3227:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3228:                    .'</span><br />');
                   3229:             }
1.257     albertel 3230: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3231: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3232: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3233:             my ($feedurl,$showsymb) =
                   3234: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3235: 	    my $messagetail;
1.62      albertel 3236: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3237: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3238: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3239: 		$subject.=' ['.$restitle.']';
1.44      ng       3240: 		my (@msgnum) = split(/,/,$includemsg);
                   3241: 		foreach (@msgnum) {
1.257     albertel 3242: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3243: 		}
1.80      ng       3244: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3245: 		if ($env{'form.withgrades'.$ctr}) {
                   3246: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3247: 		    $messagetail = " for <a href=\"".
1.605     www      3248: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3249: 		}
                   3250: 		$msgstatus = 
                   3251:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3252: 						     $message.$messagetail,
1.418     albertel 3253:                                                      undef,$feedurl,undef,
1.386     raeburn  3254:                                                      undef,undef,$showsymb,
                   3255:                                                      $restitle);
1.574     bisitz   3256: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3257: 				$msgstatus.'<br />');
1.44      ng       3258: 	    }
1.257     albertel 3259: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3260: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3261: 		foreach my $collabstr (@collabstrs) {
                   3262: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3263: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3264: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3265: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.786     raeburn  3266: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 3267: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3268: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3269: 			    next;
1.418     albertel 3270: 			} elsif ($message ne '') {
                   3271: 			    my ($baseurl,$showsymb) = 
                   3272: 				&get_feedurl_and_symb($symb,$collaborator,
                   3273: 						      $udom);
                   3274: 			    if ($env{'form.withgrades'.$ctr}) {
                   3275: 				$messagetail = " for <a href=\"".
1.605     www      3276:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3277: 			    }
1.418     albertel 3278: 			    $msgstatus = 
                   3279: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3280: 			}
1.44      ng       3281: 		    }
                   3282: 		}
                   3283: 	    }
                   3284: 	    $ctr++;
                   3285: 	}
                   3286:     }
                   3287: 
1.773     raeburn  3288:     my %keyhash = ();
                   3289:     if ($numessay) {
1.119     ng       3290: 	# Keywords sorted in alphabatical order
1.257     albertel 3291: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3292: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  3293: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3294: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3295: 	$env{'form.keywords'} = join(' ',@keywords);
                   3296: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3297: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3298: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3299: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3300: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  3301:     }
1.119     ng       3302: 
1.773     raeburn  3303:     if ($env{'form.compmsg'}) {
1.119     ng       3304: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3305: 	# New messages are saved in env for the next student.
1.119     ng       3306: 	# All messages are saved in nohist_handgrade.db
                   3307: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3308: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3309: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3310: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3311: 		$idx++;
                   3312: 	    }
                   3313: 	    $ctr++;
1.41      ng       3314: 	}
1.119     ng       3315: 	$ctr = 0;
                   3316: 	while ($ctr < $ngrade) {
1.257     albertel 3317: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  3318: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3319: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3320: 	        $idx++;
1.119     ng       3321: 	    }
                   3322: 	    $ctr++;
1.41      ng       3323: 	}
1.257     albertel 3324: 	$env{'form.savemsgN'} = --$idx;
                   3325: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       3326:     }
1.773     raeburn  3327:     if (($numessay) || ($env{'form.compmsg'})) {
                   3328:         my $putresult = &Apache::lonnet::put
                   3329:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   3330:     }
                   3331: 
1.44      ng       3332:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3333:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3334:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3335: 	my ($ctr,$total) = (0,0);
                   3336: 	while ($ctr < $ngrade) {
1.257     albertel 3337: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3338: 	    $ctr++;
                   3339: 	}
1.257     albertel 3340: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3341: 	$ctr = 0;
                   3342: 	while ($ctr < $total) {
1.257     albertel 3343: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3344: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3345: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3346: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3347: 	    $ctr++;
                   3348: 	}
                   3349: 	return '';
                   3350:     }
1.36      ng       3351: 
1.44      ng       3352:     # Get the next/previous one or group of students
1.257     albertel 3353:     my $firststu = $env{'form.unamedom0'};
                   3354:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3355:     my $ctr = 2;
1.41      ng       3356:     while ($laststu eq '') {
1.257     albertel 3357: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3358: 	$ctr++;
                   3359: 	$laststu = $firststu if ($ctr > $ngrade);
                   3360:     }
1.44      ng       3361: 
1.41      ng       3362:     my (@parsedlist,@nextlist);
                   3363:     my ($nextflg) = 0;
1.524     raeburn  3364:     foreach my $item (sort 
1.294     albertel 3365: 	     {
                   3366: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3367: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3368: 		 }
                   3369: 		 return $a cmp $b;
                   3370: 	     } (keys(%$fullname))) {
1.41      ng       3371: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3372: 	    push(@parsedlist,$item);
1.41      ng       3373: 	}
1.524     raeburn  3374: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3375: 	if ($button eq 'Previous') {
1.524     raeburn  3376: 	    last if ($item eq $firststu);
                   3377: 	    push(@parsedlist,$item);
1.41      ng       3378: 	}
                   3379:     }
                   3380:     $ctr = 0;
                   3381:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3382:     foreach my $student (@parsedlist) {
1.257     albertel 3383: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3384: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3385: 	
                   3386: 	if ($submitonly eq 'queued') {
                   3387: 	    my %queue_status = 
                   3388: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3389: 							$udom,$uname);
                   3390: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3391: 	}
                   3392: 
1.156     albertel 3393: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3394: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3395: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3396: 	    my $submitted = 0;
1.248     albertel 3397: 	    my $ungraded = 0;
                   3398: 	    my $incorrect = 0;
1.524     raeburn  3399: 	    foreach my $item (keys(%status)) {
                   3400: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3401: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3402: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3403: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3404: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3405: 		    $submitted = 0;
                   3406: 		}
1.41      ng       3407: 	    }
1.156     albertel 3408: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3409: 				     $submitonly eq 'incorrect' ||
                   3410: 				     $submitonly eq 'graded'));
1.248     albertel 3411: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3412: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3413: 	}
1.524     raeburn  3414: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3415: 	last if ($ctr == $ntstu);
1.41      ng       3416: 	$ctr++;
                   3417:     }
1.36      ng       3418: 
1.41      ng       3419:     $ctr = 0;
                   3420:     my $total = scalar(@nextlist)-1;
1.39      ng       3421: 
1.524     raeburn  3422:     foreach (sort(@nextlist)) {
1.41      ng       3423: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3424: 	$env{'form.student'}  = $uname;
                   3425: 	$env{'form.userdom'}  = $udom;
                   3426: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3427: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3428: 	$ctr++;
                   3429:     }
                   3430:     if ($total < 0) {
1.653     raeburn  3431: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3432: 	$request->print($the_end);
                   3433:     }
                   3434:     return '';
1.38      ng       3435: }
1.36      ng       3436: 
1.44      ng       3437: #---- Save the score and award for each student, if changed
1.38      ng       3438: sub saveHandGrade {
1.786     raeburn  3439:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
1.342     banghart 3440:     my @version_parts;
1.104     albertel 3441:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3442: 					   $env{'request.course.id'});
1.104     albertel 3443:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3444:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3445:     my @parts_graded;
1.77      ng       3446:     my %newrecord  = ();
1.726     raeburn  3447:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3448:     my %aggregate = ();
                   3449:     my $aggregateflag = 0;
1.726     raeburn  3450:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3451:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3452:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3453:         $totchg += $numchgs;
                   3454:     }
1.301     albertel 3455:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3456:     foreach my $new_part (@parts) {
1.337     banghart 3457: 	#collaborator ($submi may vary for different parts
1.259     banghart 3458: 	if ($submitter && $new_part ne $part) { next; }
                   3459: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3460: 	if ($dropMenu eq 'excused') {
1.259     banghart 3461: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3462: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3463: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3464: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3465: 		}
1.364     banghart 3466: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3467: 	    }
1.125     ng       3468: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3469: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3470: 	    foreach my $key (keys(%record)) {
1.259     banghart 3471: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3472: 	    }
1.259     banghart 3473: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3474: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3475:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3476: 
                   3477:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3478: 					       [$new_part]);
                   3479:             my $aggtries =$totaltries;
1.269     raeburn  3480:             if ($last_resets{$new_part}) {
1.270     albertel 3481:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3482: 					   $new_part);
1.269     raeburn  3483:             }
1.270     albertel 3484: 
                   3485:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3486:             if ($aggtries > 0) {
1.327     albertel 3487:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3488:                 $aggregateflag = 1;
                   3489:             }
1.125     ng       3490: 	} elsif ($dropMenu eq '') {
1.259     banghart 3491: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3492: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3493: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3494: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3495: 		next;
                   3496: 	    }
1.259     banghart 3497: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3498: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3499: 	    my $partial= $pts/$wgt;
1.259     banghart 3500: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3501: 		#do not update score for part if not changed.
1.346     banghart 3502:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3503: 		next;
1.251     banghart 3504: 	    } else {
1.524     raeburn  3505: 	        push(@parts_graded,$new_part);
1.153     albertel 3506: 	    }
1.259     banghart 3507: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3508: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3509: 	    }
1.259     banghart 3510: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3511: 	    if ($partial == 0) {
1.153     albertel 3512: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3513: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3514: 		}
1.41      ng       3515: 	    } else {
1.153     albertel 3516: 		if ($record{$reckey} ne 'correct_by_override') {
                   3517: 		    $newrecord{$reckey} = 'correct_by_override';
                   3518: 		}
                   3519: 	    }	    
                   3520: 	    if ($submitter && 
1.259     banghart 3521: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3522: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3523: 	    }
1.259     banghart 3524: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3525: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3526: 	}
1.259     banghart 3527: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3528: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3529: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3530: 	        $dropMenu eq 'reset status')
                   3531: 	   {
1.524     raeburn  3532: 	    push(@version_parts,$new_part);
1.259     banghart 3533: 	}
1.41      ng       3534:     }
1.301     albertel 3535:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3536:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3537: 
1.344     albertel 3538:     if (%newrecord) {
                   3539:         if (@version_parts) {
1.364     banghart 3540:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3541:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3542: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3543: 	    foreach my $new_part (@version_parts) {
                   3544: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3545: 				$new_part,\%newrecord);
                   3546: 	    }
1.259     banghart 3547:         }
1.44      ng       3548: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3549: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3550: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.786     raeburn  3551: 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       3552:     }
1.269     raeburn  3553:     if ($aggregateflag) {
                   3554:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3555: 			      $cdom,$cnum);
1.269     raeburn  3556:     }
1.726     raeburn  3557:     return ('',$pts,$wgt,$totchg);
                   3558: }
                   3559: 
                   3560: sub makehidden {
1.728     raeburn  3561:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3562:     return unless (ref($record) eq 'HASH');
                   3563:     my %modified;
                   3564:     my $numchanged = 0;
                   3565:     if (exists($record->{$version.':keys'})) {
                   3566:         my $partsregexp = $parts;
                   3567:         $partsregexp =~ s/,/|/g;
                   3568:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3569:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3570:                  my $item = $1;
                   3571:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3572:                      $modified{$key} = $record->{$version.':'.$key};
                   3573:                  }
                   3574:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3575:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3576:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3577:                 $modified{$key} = $record->{$version.':'.$key};
                   3578:             }
                   3579:         }
                   3580:         if (keys(%modified)) {
                   3581:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3582:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3583:                 $numchanged ++;
                   3584:             }
                   3585:         }
                   3586:     }
                   3587:     return $numchanged;
1.36      ng       3588: }
1.322     albertel 3589: 
1.380     albertel 3590: sub check_and_remove_from_queue {
1.786     raeburn  3591:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 3592:     my @ungraded_parts;
                   3593:     foreach my $part (@{$parts}) {
                   3594: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3595: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3596: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3597: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3598: 		) {
1.786     raeburn  3599:             if ($queueable->{$part}) {
                   3600: 	        push(@ungraded_parts, $part);
                   3601:             }
1.380     albertel 3602: 	}
                   3603:     }
                   3604:     if ( !@ungraded_parts ) {
                   3605: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3606: 					       $cnum,$domain,$stuname);
                   3607:     }
                   3608: }
                   3609: 
1.337     banghart 3610: sub handback_files {
                   3611:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3612:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3613:     my $res_error;
                   3614:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3615:     if ($res_error) {
                   3616:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3617:         return;
                   3618:     }
1.654     raeburn  3619:     my @handedback;
                   3620:     my $file_msg;
1.375     albertel 3621:     my @part_response_id = &flatten_responseType($responseType);
                   3622:     foreach my $part_response_id (@part_response_id) {
                   3623:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3624: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3625:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3626:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3627:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3628:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3629:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3630:                     my ($directory,$answer_file) = 
1.654     raeburn  3631:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3632:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3633: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3634: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3635:                     my $getpropath = 1;
1.773     raeburn  3636:                     my ($dir_list,$listerror) =
1.662     raeburn  3637:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3638:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3639: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3640:                     # fix filename
1.355     banghart 3641:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3642:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3643:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3644:             	                                $save_file_name);
1.337     banghart 3645:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3646:                         $request->print('<br /><span class="LC_error">'.
                   3647:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3648:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3649:                                         '</span>');
1.356     banghart 3650:                     } else {
1.360     banghart 3651:                         # mark the file as read only
1.654     raeburn  3652:                         push(@handedback,$save_file_name);
1.367     albertel 3653: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3654: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3655: 			}
                   3656:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3657: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3658:                     }
1.686     bisitz   3659:                     $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 3660:                 }
                   3661:             }
                   3662:         }
1.654     raeburn  3663:     }
                   3664:     if (@handedback > 0) {
                   3665:         $request->print('<br />');
                   3666:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3667:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3668:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3669:         my ($subject,$message);
                   3670:         if (scalar(@handedback) == 1) {
                   3671:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3672:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3673:         } else {
                   3674:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3675:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3676:         }
                   3677:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3678:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3679:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3680:         my ($feedurl,$showsymb) =
                   3681:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3682:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3683:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3684:         my $msgstatus =
                   3685:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3686:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3687:                  $restitle);
                   3688:         if ($msgstatus) {
                   3689:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3690:         }
                   3691:     }
1.338     banghart 3692:     return;
1.337     banghart 3693: }
                   3694: 
1.418     albertel 3695: sub get_feedurl_and_symb {
                   3696:     my ($symb,$uname,$udom) = @_;
                   3697:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3698:     $url = &Apache::lonnet::clutter($url);
                   3699:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3700: 					$symb,$udom,$uname);
                   3701:     if ($encrypturl =~ /^yes$/i) {
                   3702: 	&Apache::lonenc::encrypted(\$url,1);
                   3703: 	&Apache::lonenc::encrypted(\$symb,1);
                   3704:     }
                   3705:     return ($url,$symb);
                   3706: }
                   3707: 
1.313     banghart 3708: sub get_submitted_files {
                   3709:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3710:     my @files;
                   3711:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3712:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3713:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3714:     	    push(@files,$file_url.$file);
                   3715:         }
                   3716:     }
                   3717:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3718:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3719:     }
                   3720:     return (\@files);
                   3721: }
1.322     albertel 3722: 
1.269     raeburn  3723: # ----------- Provides number of tries since last reset.
                   3724: sub get_num_tries {
                   3725:     my ($record,$last_reset,$part) = @_;
                   3726:     my $timestamp = '';
                   3727:     my $num_tries = 0;
                   3728:     if ($$record{'version'}) {
                   3729:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3730:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3731:                 $timestamp = $$record{$version.':timestamp'};
                   3732:                 if ($timestamp > $last_reset) {
                   3733:                     $num_tries ++;
                   3734:                 } else {
                   3735:                     last;
                   3736:                 }
                   3737:             }
                   3738:         }
                   3739:     }
                   3740:     return $num_tries;
                   3741: }
                   3742: 
                   3743: # ----------- Determine decrements required in aggregate totals 
                   3744: sub decrement_aggs {
                   3745:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3746:     my %decrement = (
                   3747:                         attempts => 0,
                   3748:                         users => 0,
                   3749:                         correct => 0
                   3750:                     );
                   3751:     $decrement{'attempts'} = $aggtries;
                   3752:     if ($solvedstatus =~ /^correct/) {
                   3753:         $decrement{'correct'} = 1;
                   3754:     }
                   3755:     if ($aggtries == $totaltries) {
                   3756:         $decrement{'users'} = 1;
                   3757:     }
1.524     raeburn  3758:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3759:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3760:     }
                   3761:     return;
                   3762: }
                   3763: 
                   3764: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3765: sub get_last_resets {
1.270     albertel 3766:     my ($symb,$courseid,$partids) =@_;
                   3767:     my %last_resets;
1.269     raeburn  3768:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3769:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3770:     my @keys;
                   3771:     foreach my $part (@{$partids}) {
                   3772: 	push(@keys,"$symb\0$part\0resettime");
                   3773:     }
                   3774:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3775: 				     $cdom,$cname);
                   3776:     foreach my $part (@{$partids}) {
                   3777: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3778:     }
1.270     albertel 3779:     return %last_resets;
1.269     raeburn  3780: }
                   3781: 
1.251     banghart 3782: # ----------- Handles creating versions for portfolio files as answers
                   3783: sub version_portfiles {
1.343     banghart 3784:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3785:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3786:     my @returned_keys;
1.255     banghart 3787:     my $parts = join('|', @$parts_graded);
1.277     albertel 3788:     foreach my $key (keys(%$record)) {
1.259     banghart 3789:         my $new_portfiles;
1.263     banghart 3790:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3791:             my @versioned_portfiles;
1.367     albertel 3792:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3793:             if (@portfiles) {
                   3794:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3795:                                                       \@versioned_portfiles);
1.252     banghart 3796:             }
1.343     banghart 3797:             $$record{$key} = join(',',@versioned_portfiles);
                   3798:             push(@returned_keys,$key);
1.251     banghart 3799:         }
                   3800:     } 
1.343     banghart 3801:     return (@returned_keys);   
1.305     banghart 3802: }
                   3803: 
1.44      ng       3804: #--------------------------------------------------------------------------------------
                   3805: #
                   3806: #-------------------------- Next few routines handles grading by section or whole class
                   3807: #
                   3808: #--- Javascript to handle grading by section or whole class
1.42      ng       3809: sub viewgrades_js {
                   3810:     my ($request) = shift;
                   3811: 
1.539     riegler  3812:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3813:     &js_escape(\$alertmsg);
1.597     wenzelju 3814:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3815:    function writePoint(partid,weight,point) {
1.125     ng       3816: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3817: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3818: 	if (point == "textval") {
1.125     ng       3819: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3820: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3821: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3822: 		var resetbox = false;
                   3823: 		for (var i=0; i<radioButton.length; i++) {
                   3824: 		    if (radioButton[i].checked) {
                   3825: 			textbox.value = i;
                   3826: 			resetbox = true;
                   3827: 		    }
                   3828: 		}
                   3829: 		if (!resetbox) {
                   3830: 		    textbox.value = "";
                   3831: 		}
                   3832: 		return;
                   3833: 	    }
1.109     matthew  3834: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3835: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3836: 				   ") greater than the weight for the part. Accept?");
                   3837: 		if (resp == false) {
                   3838: 		    textbox.value = "";
                   3839: 		    return;
                   3840: 		}
                   3841: 	    }
1.42      ng       3842: 	    for (var i=0; i<radioButton.length; i++) {
                   3843: 		radioButton[i].checked=false;
1.109     matthew  3844: 		if (parseFloat(point) == i) {
1.42      ng       3845: 		    radioButton[i].checked=true;
                   3846: 		}
                   3847: 	    }
1.41      ng       3848: 
1.42      ng       3849: 	} else {
1.125     ng       3850: 	    textbox.value = parseFloat(point);
1.42      ng       3851: 	}
1.41      ng       3852: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3853: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3854: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3855: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3856: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3857: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3858: 	    if (saveval != "correct") {
                   3859: 		scorename.value = point;
1.43      ng       3860: 		if (selname[0].selected != true) {
                   3861: 		    selname[0].selected = true;
                   3862: 		}
1.42      ng       3863: 	    }
                   3864: 	}
1.125     ng       3865: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3866:     }
                   3867: 
                   3868:     function writeRadText(partid,weight) {
1.125     ng       3869: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3870: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3871:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3872: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3873: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3874: 	    for (var i=0; i<radioButton.length; i++) {
                   3875: 		radioButton[i].checked=false;
                   3876: 
                   3877: 	    }
                   3878: 	    textbox.value = "";
                   3879: 
                   3880: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3881: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3882: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3883: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3884: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3885: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3886: 		if ((saveval != "correct") || override) {
1.42      ng       3887: 		    scorename.value = "";
1.125     ng       3888: 		    if (selval[1].selected) {
                   3889: 			selname[1].selected = true;
                   3890: 		    } else {
                   3891: 			selname[2].selected = true;
                   3892: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3893: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3894: 		    }
1.42      ng       3895: 		}
                   3896: 	    }
1.43      ng       3897: 	} else {
                   3898: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3899: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3900: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3901: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3902: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3903: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3904: 		if ((saveval != "correct") || override) {
1.125     ng       3905: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3906: 		    selname[0].selected = true;
                   3907: 		}
                   3908: 	    }
                   3909: 	}	    
1.42      ng       3910:     }
                   3911: 
                   3912:     function changeSelect(partid,user) {
1.125     ng       3913: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3914: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3915: 	var point  = textbox.value;
1.125     ng       3916: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3917: 
1.109     matthew  3918: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3919: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3920: 	    textbox.value = "";
                   3921: 	    return;
                   3922: 	}
1.109     matthew  3923: 	if (parseFloat(point) > parseFloat(weight)) {
                   3924: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3925: 			       ") greater than the weight of the part. Accept?");
                   3926: 	    if (resp == false) {
                   3927: 		textbox.value = "";
                   3928: 		return;
                   3929: 	    }
                   3930: 	}
1.42      ng       3931: 	selval[0].selected = true;
                   3932:     }
                   3933: 
                   3934:     function changeOneScore(partid,user) {
1.125     ng       3935: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3936: 	if (selval[1].selected || selval[2].selected) {
                   3937: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3938: 	    if (selval[2].selected) {
                   3939: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3940: 	    }
1.269     raeburn  3941:         }
1.42      ng       3942:     }
                   3943: 
                   3944:     function resetEntry(numpart) {
                   3945: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3946: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3947: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3948: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3949: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3950: 	    for (var i=0; i<radioButton.length; i++) {
                   3951: 		radioButton[i].checked=false;
                   3952: 
                   3953: 	    }
                   3954: 	    textbox.value = "";
                   3955: 	    selval[0].selected = true;
                   3956: 
                   3957: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3958: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3959: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3960: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3961: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3962: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3963: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3964: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3965: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3966: 		if (saveselval == "excused") {
1.43      ng       3967: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3968: 		} else {
1.43      ng       3969: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3970: 		}
                   3971: 	    }
1.41      ng       3972: 	}
1.42      ng       3973:     }
                   3974: 
1.41      ng       3975: VIEWJAVASCRIPT
1.42      ng       3976: }
                   3977: 
1.44      ng       3978: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3979: sub viewgrades {
1.608     www      3980:     my ($request,$symb) = @_;
1.745     raeburn  3981:     my ($is_tool,$toolsymb);
                   3982:     if ($symb =~ /ext\.tool$/) {
                   3983:         $is_tool = 1;
                   3984:         $toolsymb = $symb;
                   3985:     }
1.42      ng       3986:     &viewgrades_js($request);
1.41      ng       3987: 
1.168     albertel 3988:     #need to make sure we have the correct data for later EXT calls, 
                   3989:     #thus invalidate the cache
                   3990:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3991:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3992:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3993:     &Apache::lonnet::clear_EXT_cache_status();
                   3994: 
1.398     albertel 3995:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3996: 
                   3997:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3998:     $result.=&jscriptNform($symb);
1.41      ng       3999: 
1.44      ng       4000:     #beginning of class grading form
1.442     banghart 4001:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       4002:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 4003: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       4004: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 4005: 	&build_section_inputs().
1.442     banghart 4006: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       4007: 
1.738     raeburn  4008:     #retrieve selected groups
                   4009:     my (@groups,$group_display);
                   4010:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   4011:     if (grep(/^all$/,@groups)) {
                   4012:         @groups = ('all');
                   4013:     } elsif (grep(/^none$/,@groups)) {
                   4014:         @groups = ('none');
                   4015:     } elsif (@groups > 0) {
                   4016:         $group_display = join(', ',@groups);
                   4017:     }
                   4018: 
                   4019:     my ($common_header,$specific_header,@sections,$section_display);
1.780     raeburn  4020:     if ($env{'request.course.sec'} ne '') {
                   4021:         @sections = ($env{'request.course.sec'});
                   4022:     } else {
                   4023:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   4024:     }
                   4025: 
                   4026: # Check if Save button should be usable
                   4027:     my $disabled = ' disabled="disabled"';
                   4028:     if ($perm{'mgr'}) {
                   4029:         if (grep(/^all$/,@sections)) {
                   4030:             undef($disabled);
                   4031:         } else {
                   4032:             foreach my $sec (@sections) {
                   4033:                 if (&canmodify($sec)) {
                   4034:                     undef($disabled);
                   4035:                     last;
                   4036:                 }
                   4037:             }
                   4038:         }
                   4039:     }
1.738     raeburn  4040:     if (grep(/^all$/,@sections)) {
                   4041:         @sections = ('all');
                   4042:         if ($group_display) {
                   4043:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4044:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4045:         } elsif (grep(/^none$/,@groups)) {
                   4046:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4047:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4048:         } else {
                   4049: 	    $common_header = &mt('Assign Common Grade to Class');
                   4050:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4051:         }
                   4052:     } elsif (grep(/^none$/,@sections)) {
                   4053:         @sections = ('none');
                   4054:         if ($group_display) {
                   4055:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4056:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4057:         } elsif (grep(/^none$/,@groups)) {
                   4058:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4059:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4060:         } else {
                   4061:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4062: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4063:         }
                   4064:     } else {
                   4065:         $section_display = join (", ",@sections);
                   4066:         if ($group_display) {
                   4067:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4068:                                  $section_display,$group_display);
                   4069:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4070:                                    $section_display,$group_display);
                   4071:         } elsif (grep(/^none$/,@groups)) {
                   4072:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4073:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4074:         } else {
                   4075:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4076: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4077:         }
                   4078:     }
                   4079:     my %submit_types = &substatus_options();
                   4080:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4081: 
                   4082:     if ($env{'form.submitonly'} eq 'all') {
                   4083:         $result.= '<h3>'.$common_header.'</h3>';
                   4084:     } else {
1.745     raeburn  4085:         my $text;
                   4086:         if ($is_tool) {
                   4087:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4088:         } else {
                   4089:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4090:         }
                   4091:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 4092:     }
1.738     raeburn  4093:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4094:     #radio buttons/text box for assigning points for a section or class.
                   4095:     #handles different parts of a problem
1.582     raeburn  4096:     my $res_error;
                   4097:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4098:     if ($res_error) {
                   4099:         return &navmap_errormsg();
                   4100:     }
1.42      ng       4101:     my %weight = ();
                   4102:     my $ctsparts = 0;
1.45      ng       4103:     my %seen = ();
1.745     raeburn  4104:     my @part_response_id;
                   4105:     if ($is_tool) {
                   4106:         @part_response_id = ([0,'']);
                   4107:     } else {
                   4108:         @part_response_id = &flatten_responseType($responseType);
                   4109:     }
1.375     albertel 4110:     foreach my $part_response_id (@part_response_id) {
                   4111:     	my ($partid,$respid) = @{ $part_response_id };
                   4112: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4113: 	next if $seen{$partid};
                   4114: 	$seen{$partid}++;
1.42      ng       4115: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4116: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4117: 
1.324     albertel 4118: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4119: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4120: 	my $ctr = 0;
1.42      ng       4121: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4122: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4123: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4124: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4125: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4126: 	    $ctr++;
                   4127: 	}
1.485     albertel 4128: 	$radio.='</tr></table>';
                   4129: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4130: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4131: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4132: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   4133:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4134:             '<select name="SELVAL_'.$partid.'" '.
                   4135:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   4136:                 $weight{$partid}.')"> '.
1.401     albertel 4137: 	    '<option selected="selected"> </option>'.
1.485     albertel 4138: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4139: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4140: 	    '</select></td>'.
                   4141:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4142: 	$line.='<input type="hidden" name="partid_'.
                   4143: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4144: 	$line.='<input type="hidden" name="weight_'.
                   4145: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4146: 
                   4147: 	$result.=
                   4148: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4149: 	    '<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 4150: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4151: 	$ctsparts++;
1.41      ng       4152:     }
1.474     albertel 4153:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4154: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4155:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4156: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4157: 
1.44      ng       4158:     #table listing all the students in a section/class
                   4159:     #header of table
1.738     raeburn  4160:     if ($env{'form.submitonly'} eq 'all') {
                   4161:         $result.= '<h3>'.$specific_header.'</h3>';
                   4162:     } else {
1.745     raeburn  4163:         my $text;
                   4164:         if ($is_tool) {
                   4165:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4166:         } else {
                   4167:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4168:         }
                   4169:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  4170:     }
                   4171:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4172: 	      &Apache::loncommon::start_data_table_header_row().
                   4173: 	      '<th>'.&mt('No.').'</th>'.
                   4174: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4175:     my $partserror;
                   4176:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4177:     if ($partserror) {
                   4178:         return &navmap_errormsg();
                   4179:     }
1.324     albertel 4180:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4181:     my @partids = ();
1.41      ng       4182:     foreach my $part (@parts) {
1.745     raeburn  4183: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  4184:         my $narrowtext = &mt('Tries');
                   4185: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  4186: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 4187: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4188:         push(@partids,$partid);
1.628     www      4189: #
                   4190: # FIXME: Looks like $display looks at English text
                   4191: #
1.324     albertel 4192: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4193: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4194: 	    $result.='<th>'.
1.697     bisitz   4195: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   4196: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4197: 	    next;
1.485     albertel 4198: 	    
1.207     albertel 4199: 	} else {
1.485     albertel 4200: 	    if ($display =~ /Problem Status/) {
                   4201: 		my $grade_status_mt = &mt('Grade Status');
                   4202: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4203: 	    }
                   4204: 	    my $part_mt = &mt('Part:');
                   4205: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4206: 	}
1.485     albertel 4207: 
1.474     albertel 4208: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4209:     }
1.474     albertel 4210:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4211: 
1.270     albertel 4212:     my %last_resets = 
                   4213: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4214: 
1.41      ng       4215:     #get info for each student
1.44      ng       4216:     #list all the students - with points and grade status
1.738     raeburn  4217:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4218:     my $ctr = 0;
1.294     albertel 4219:     foreach (sort 
                   4220: 	     {
                   4221: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4222: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4223: 		 }
                   4224: 		 return $a cmp $b;
                   4225: 	     } (keys(%$fullname))) {
1.324     albertel 4226: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  4227: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4228:     }
1.474     albertel 4229:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4230:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.780     raeburn  4231:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   4232: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4233:     if ($ctr == 0) {
1.442     banghart 4234:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4235:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4236:                 '<span class="LC_warning">';
                   4237:         if ($env{'form.submitonly'} eq 'all') {
                   4238:             if (grep(/^all$/,@sections)) {
                   4239:                 if (grep(/^all$/,@groups)) {
                   4240:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4241:                                    $stu_status);
                   4242:                 } elsif (grep(/^none$/,@groups)) {
                   4243:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4244:                                    $stu_status); 
                   4245:                 } else {
                   4246:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4247:                                    $group_display,$stu_status);
                   4248:                 }
                   4249:             } elsif (grep(/^none$/,@sections)) {
                   4250:                 if (grep(/^all$/,@groups)) {
                   4251:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4252:                                    $stu_status);
                   4253:                 } elsif (grep(/^none$/,@groups)) {
                   4254:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4255:                                    $stu_status);
                   4256:                 } else {
                   4257:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4258:                                    $group_display,$stu_status);
                   4259:                 }
                   4260:             } else {
                   4261:                 if (grep(/^all$/,@groups)) {
                   4262:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4263:                                    $section_display,$stu_status);
                   4264:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4265:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4266:                                    $section_display,$stu_status);
                   4267:                 } else {
                   4268:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4269:                                    $section_display,$group_display,$stu_status);
                   4270:                 }
                   4271:             }
                   4272:         } else {
                   4273:             if (grep(/^all$/,@sections)) {
                   4274:                 if (grep(/^all$/,@groups)) {
                   4275:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4276:                                    $stu_status,$submission_status);
                   4277:                 } elsif (grep(/^none$/,@groups)) {
                   4278:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4279:                                    $stu_status,$submission_status);
                   4280:                 } else {
                   4281:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4282:                                    $group_display,$stu_status,$submission_status);
                   4283:                 }
                   4284:             } elsif (grep(/^none$/,@sections)) {
                   4285:                 if (grep(/^all$/,@groups)) {
                   4286:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4287:                                    $stu_status,$submission_status);
                   4288:                 } elsif (grep(/^none$/,@groups)) {
                   4289:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4290:                                    $stu_status,$submission_status);
                   4291:                 } else {
                   4292:                     $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.',
                   4293:                                    $group_display,$stu_status,$submission_status);
                   4294:                 }
                   4295:             } else {
                   4296:                 if (grep(/^all$/,@groups)) {
                   4297: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4298: 	                           $section_display,$stu_status,$submission_status);
                   4299:                 } elsif (grep(/^none$/,@groups)) {
                   4300:                     $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.',
                   4301:                                    $section_display,$stu_status,$submission_status);
                   4302:                 } else {
                   4303:                     $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.',
                   4304:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4305:                 }
                   4306:             }
                   4307:         }
                   4308: 	$result .= '</span><br />';
1.96      albertel 4309:     }
1.41      ng       4310:     return $result;
                   4311: }
                   4312: 
1.738     raeburn  4313: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4314: sub viewstudentgrade {
1.745     raeburn  4315:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4316:     my ($uname,$udom) = split(/:/,$student);
                   4317:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4318:     my $submitonly = $env{'form.submitonly'};
                   4319:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4320:         my %partstatus = ();
                   4321:         if (ref($parts) eq 'ARRAY') {
                   4322:             foreach my $apart (@{$parts}) {
                   4323:                 my ($part,$type) = &split_part_type($apart);
                   4324:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4325:                 $status = 'nothing' if ($status eq '');
                   4326:                 $partstatus{$part}      = $status;
                   4327:                 my $subkey = "resource.$part.submitted_by";
                   4328:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4329:             }
                   4330:             my $submitted = 0;
                   4331:             my $graded = 0;
                   4332:             my $incorrect = 0;
                   4333:             foreach my $key (keys(%partstatus)) {
                   4334:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4335:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4336:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4337: 
                   4338:                 my $partid = (split(/\./,$key))[1];
                   4339:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4340:                     $submitted = 0;
                   4341:                 }
                   4342:             }
                   4343:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4344:                                        $submitonly eq 'incorrect' ||
                   4345:                                        $submitonly eq 'graded'));
                   4346:             return if (!$graded && ($submitonly eq 'graded'));
                   4347:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4348:         }
                   4349:     }
                   4350:     if ($submitonly eq 'queued') {
                   4351:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4352:         my %queue_status =
                   4353:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4354:                                                     $udom,$uname);
                   4355:         return if (!defined($queue_status{'gradingqueue'}));
                   4356:     }
                   4357:     $$ctr++;
                   4358:     my %aggregates = ();
1.474     albertel 4359:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4360: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4361: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4362: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4363: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4364: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4365:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4366:     foreach my $apart (@$parts) {
                   4367: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4368: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4369:         $result.='<td align="center">';
1.269     raeburn  4370:         my ($aggtries,$totaltries);
                   4371:         unless (exists($aggregates{$part})) {
1.270     albertel 4372: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4373: 	    $aggtries = $totaltries;
1.269     raeburn  4374:             if ($$last_resets{$part}) {  
1.270     albertel 4375:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4376: 					   $part);
                   4377:             }
1.269     raeburn  4378:             $result.='<input type="hidden" name="'.
                   4379:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4380:             $result.='<input type="hidden" name="'.
                   4381:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4382:             $aggregates{$part} = 1;
                   4383:         }
1.41      ng       4384: 	if ($type eq 'awarded') {
1.320     albertel 4385: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4386: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4387: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4388: 	    $result.='<input type="text" name="'.
1.89      albertel 4389: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4390:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4391: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4392: 	} elsif ($type eq 'solved') {
                   4393: 	    my ($status,$foo)=split(/_/,$score,2);
                   4394: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4395: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4396: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4397: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4398: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4399:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4400: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4401: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4402: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4403: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4404: 	} else {
                   4405: 	    $result.='<input type="hidden" name="'.
                   4406: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4407: 		    "\n";
1.233     albertel 4408: 	    $result.='<input type="text" name="'.
1.122     ng       4409: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4410: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4411: 	}
                   4412:     }
1.474     albertel 4413:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4414:     return $result;
1.38      ng       4415: }
                   4416: 
1.44      ng       4417: #--- change scores for all the students in a section/class
                   4418: #    record does not get update if unchanged
1.38      ng       4419: sub editgrades {
1.608     www      4420:     my ($request,$symb) = @_;
1.745     raeburn  4421:     my $toolsymb;
                   4422:     if ($symb =~ /ext\.tool$/) {
                   4423:         $toolsymb = $symb;
                   4424:     }
1.41      ng       4425: 
1.433     banghart 4426:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4427:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  4428:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4429: 
1.477     albertel 4430:     my $result= &Apache::loncommon::start_data_table().
                   4431: 	&Apache::loncommon::start_data_table_header_row().
                   4432: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4433: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4434:     my %scoreptr = (
                   4435: 		    'correct'  =>'correct_by_override',
                   4436: 		    'incorrect'=>'incorrect_by_override',
                   4437: 		    'excused'  =>'excused',
                   4438: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4439:                     'credited' =>'credit_attempted',
1.43      ng       4440: 		    'nothing'  => '',
                   4441: 		    );
1.257     albertel 4442:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4443: 
1.44      ng       4444:     my (@partid);
                   4445:     my %weight = ();
1.54      albertel 4446:     my %columns = ();
1.44      ng       4447:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4448: 
1.582     raeburn  4449:     my $partserror;
                   4450:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4451:     if ($partserror) {
                   4452:         return &navmap_errormsg();
                   4453:     }
1.54      albertel 4454:     my $header;
1.257     albertel 4455:     while ($ctr < $env{'form.totalparts'}) {
                   4456: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4457: 	push(@partid,$partid);
1.257     albertel 4458: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4459: 	$ctr++;
1.54      albertel 4460:     }
1.324     albertel 4461:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4462:     my $totcolspan = 0;
1.54      albertel 4463:     foreach my $partid (@partid) {
1.478     albertel 4464: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4465: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4466: 	$columns{$partid}=2;
                   4467: 	foreach my $stores (@parts) {
                   4468: 	    my ($part,$type) = &split_part_type($stores);
                   4469: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4470: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4471: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4472: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4473:             my $narrowtext = &mt('Tries');
                   4474: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4475: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4476: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4477: 	    $columns{$partid}+=2;
                   4478: 	}
1.748     raeburn  4479:         $totcolspan += $columns{$partid};
1.54      albertel 4480:     }
                   4481:     foreach my $partid (@partid) {
1.324     albertel 4482: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4483: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4484: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4485: 	    '</th>';
1.54      albertel 4486: 
1.44      ng       4487:     }
1.477     albertel 4488:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4489: 	&Apache::loncommon::start_data_table_header_row().
                   4490: 	$header.
                   4491: 	&Apache::loncommon::end_data_table_header_row();
                   4492:     my @noupdate;
1.126     ng       4493:     my ($updateCtr,$noupdateCtr) = (1,1);
1.786     raeburn  4494:     my ($got_types,%queueable);
1.257     albertel 4495:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4496: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4497: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4498: 	my %newrecord;
                   4499: 	my $updateflag = 0;
1.108     albertel 4500: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4501: 	my $canmodify = &canmodify($usec);
                   4502: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4503: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4504: 	if (!$canmodify) {
1.477     albertel 4505: 	    push(@noupdate,
1.748     raeburn  4506: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4507: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4508: 	    next;
                   4509: 	}
1.269     raeburn  4510:         my %aggregate = ();
                   4511:         my $aggregateflag = 0;
1.281     albertel 4512: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4513: 	foreach (@partid) {
1.257     albertel 4514: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4515: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4516: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4517: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4518: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4519: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4520: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4521: 	    my $score;
                   4522: 	    if ($partial eq '') {
1.257     albertel 4523: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4524: 	    } elsif ($partial > 0) {
                   4525: 		$score = 'correct_by_override';
                   4526: 	    } elsif ($partial == 0) {
                   4527: 		$score = 'incorrect_by_override';
                   4528: 	    }
1.257     albertel 4529: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4530: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4531: 
1.292     albertel 4532: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4533: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4534: 	    if ($dropMenu eq 'reset status' &&
                   4535: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4536: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4537: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4538: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4539: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4540: 		$updateflag = 1;
1.269     raeburn  4541:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4542:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4543:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4544:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4545:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4546:                     $aggregateflag = 1;
                   4547:                 }
1.139     albertel 4548: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4549: 		$updateflag = 1;
                   4550: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4551: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4552: 		$rec_update++;
1.125     ng       4553: 	    }
                   4554: 
1.93      albertel 4555: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4556: 		'<td align="center">'.$awarded.
                   4557: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4558: 
1.54      albertel 4559: 
                   4560: 	    my $partid=$_;
                   4561: 	    foreach my $stores (@parts) {
                   4562: 		my ($part,$type) = &split_part_type($stores);
                   4563: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4564: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4565: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4566: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4567: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4568: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4569: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4570: 		    $updateflag=1;
                   4571: 		}
1.93      albertel 4572: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4573: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4574: 	    }
1.44      ng       4575: 	}
1.477     albertel 4576: 	$line.="\n";
1.301     albertel 4577: 
                   4578: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4579: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4580: 
1.44      ng       4581: 	if ($updateflag) {
                   4582: 	    $count++;
1.257     albertel 4583: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4584: 				    $udom,$uname);
1.301     albertel 4585: 
                   4586: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4587: 					      $cnum,$udom,$uname)) {
                   4588: 		# need to figure out if should be in queue.
                   4589: 		my %record =  
                   4590: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4591: 					     $udom,$uname);
                   4592: 		my $all_graded = 1;
                   4593: 		my $none_graded = 1;
1.786     raeburn  4594:                 unless ($got_types) {
                   4595:                     my $error;
                   4596:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   4597:                     unless ($error) {
                   4598:                         foreach my $part (@parts) {
                   4599:                             if (ref($resptype->{$part}) eq 'HASH') {
                   4600:                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   4601:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   4602:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   4603:                                         $queueable{$part} = 1;
                   4604:                                         last;
                   4605:                                     }
                   4606:                                 }
                   4607:                             }
                   4608:                         }
                   4609:                     }
                   4610:                     $got_types = 1;
                   4611:                 }
1.301     albertel 4612: 		foreach my $part (@parts) {
1.786     raeburn  4613:                     if ($queueable{$part}) {
                   4614: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4615: 			    $all_graded = 0;
                   4616: 		        } else {
                   4617: 			    $none_graded = 0;
                   4618: 		        }
1.301     albertel 4619: 		    }
1.786     raeburn  4620:                 }
1.301     albertel 4621: 		if ($all_graded || $none_graded) {
                   4622: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4623: 							   $symb,$cdom,$cnum,
                   4624: 							   $udom,$uname);
                   4625: 		}
                   4626: 	    }
                   4627: 
1.477     albertel 4628: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4629: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4630: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4631: 	    $updateCtr++;
1.93      albertel 4632: 	} else {
1.477     albertel 4633: 	    push(@noupdate,
                   4634: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4635: 	    $noupdateCtr++;
1.44      ng       4636: 	}
1.269     raeburn  4637:         if ($aggregateflag) {
                   4638:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4639: 				  $cdom,$cnum);
1.269     raeburn  4640:         }
1.93      albertel 4641:     }
1.477     albertel 4642:     if (@noupdate) {
1.748     raeburn  4643:         my $numcols=$totcolspan+2;
1.477     albertel 4644: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4645: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4646: 	    &mt('No Changes Occurred For the Students Below').
                   4647: 	    '</td>'.
1.477     albertel 4648: 	    &Apache::loncommon::end_data_table_row();
                   4649: 	foreach my $line (@noupdate) {
                   4650: 	    $result.=
                   4651: 		&Apache::loncommon::start_data_table_row().
                   4652: 		$line.
                   4653: 		&Apache::loncommon::end_data_table_row();
                   4654: 	}
1.44      ng       4655:     }
1.614     www      4656:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4657:     my $msg = '<p><b>'.
                   4658: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4659: 	    $rec_update,$count).'</b><br />'.
                   4660: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4661: 	'</b></p>';
1.44      ng       4662:     return $title.$msg.$result;
1.5       albertel 4663: }
1.54      albertel 4664: 
                   4665: sub split_part_type {
                   4666:     my ($partstr) = @_;
                   4667:     my ($temp,@allparts)=split(/_/,$partstr);
                   4668:     my $type=pop(@allparts);
1.439     albertel 4669:     my $part=join('_',@allparts);
1.54      albertel 4670:     return ($part,$type);
                   4671: }
                   4672: 
1.44      ng       4673: #------------- end of section for handling grading by section/class ---------
                   4674: #
                   4675: #----------------------------------------------------------------------------
                   4676: 
1.5       albertel 4677: 
1.44      ng       4678: #----------------------------------------------------------------------------
                   4679: #
                   4680: #-------------------------- Next few routines handles grading by csv upload
                   4681: #
                   4682: #--- Javascript to handle csv upload
1.27      albertel 4683: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4684:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4685:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4686:   &js_escape(\$error1);
                   4687:   &js_escape(\$error2);
1.27      albertel 4688:   return(<<ENDPICK);
                   4689:   function verify(vf) {
                   4690:     var foundsomething=0;
                   4691:     var founduname=0;
1.243     albertel 4692:     var foundID=0;
1.743     raeburn  4693:     var foundclicker=0;
1.27      albertel 4694:     for (i=0;i<=vf.nfields.value;i++) {
                   4695:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4696:       if (i==0 && tw!=0) { foundID=1; }
                   4697:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4698:       if (i==2 && tw!=0) { foundclicker=1; }
                   4699:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4700:     }
1.743     raeburn  4701:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4702: 	alert('$error1');
                   4703: 	return;
1.27      albertel 4704:     }
                   4705:     if (foundsomething==0) {
1.246     albertel 4706: 	alert('$error2');
                   4707: 	return;
1.27      albertel 4708:     }
                   4709:     vf.submit();
                   4710:   }
                   4711:   function flip(vf,tf) {
                   4712:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4713:     var i;
                   4714:     for (i=0;i<=vf.nfields.value;i++) {
                   4715:       //can not pick the same destination field for both name and domain
                   4716:       if (((i ==0)||(i ==1)) && 
                   4717:           ((tf==0)||(tf==1)) && 
                   4718:           (i!=tf) &&
                   4719:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4720:         eval('vf.f'+i+'.selectedIndex=0;')
                   4721:       }
                   4722:     }
                   4723:   }
                   4724: ENDPICK
                   4725: }
                   4726: 
                   4727: sub csvupload_javascript_forward_associate {
1.743     raeburn  4728:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4729:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4730:   &js_escape(\$error1);
                   4731:   &js_escape(\$error2);
1.27      albertel 4732:   return(<<ENDPICK);
                   4733:   function verify(vf) {
                   4734:     var foundsomething=0;
                   4735:     var founduname=0;
1.243     albertel 4736:     var foundID=0;
1.743     raeburn  4737:     var foundclicker=0;
1.27      albertel 4738:     for (i=0;i<=vf.nfields.value;i++) {
                   4739:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4740:       if (tw==1) { foundID=1; }
                   4741:       if (tw==2) { founduname=1; }
1.745     raeburn  4742:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4743:       if (tw>4) { foundsomething=1; }
1.27      albertel 4744:     }
1.743     raeburn  4745:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4746: 	alert('$error1');
                   4747: 	return;
1.27      albertel 4748:     }
                   4749:     if (foundsomething==0) {
1.246     albertel 4750: 	alert('$error2');
                   4751: 	return;
1.27      albertel 4752:     }
                   4753:     vf.submit();
                   4754:   }
                   4755:   function flip(vf,tf) {
                   4756:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4757:     var i;
                   4758:     //can not pick the same destination field twice
                   4759:     for (i=0;i<=vf.nfields.value;i++) {
                   4760:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4761:         eval('vf.f'+i+'.selectedIndex=0;')
                   4762:       }
                   4763:     }
                   4764:   }
                   4765: ENDPICK
                   4766: }
                   4767: 
1.26      albertel 4768: sub csvuploadmap_header {
1.324     albertel 4769:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4770:     my $javascript;
1.257     albertel 4771:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4772: 	$javascript=&csvupload_javascript_reverse_associate();
                   4773:     } else {
                   4774: 	$javascript=&csvupload_javascript_forward_associate();
                   4775:     }
1.45      ng       4776: 
1.418     albertel 4777:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4778:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4779:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4780:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4781:     my $reverse=&mt("Reverse Association");
1.41      ng       4782:     $request->print(<<ENDPICK);
1.632     www      4783: <br />
                   4784: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4785: <input type="hidden" name="associate"  value="" />
                   4786: <input type="hidden" name="phase"      value="three" />
                   4787: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4788: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4789: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4790: <input type="hidden" name="upfile_associate" 
1.257     albertel 4791:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4792: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4793: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4794: <hr />
                   4795: ENDPICK
1.597     wenzelju 4796:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4797:     return '';
1.26      albertel 4798: 
                   4799: }
                   4800: 
                   4801: sub csvupload_fields {
1.582     raeburn  4802:     my ($symb,$errorref) = @_;
1.745     raeburn  4803:     my $toolsymb;
                   4804:     if ($symb =~ /ext\.tool$/) {
                   4805:         $toolsymb = $symb;
                   4806:     }
1.582     raeburn  4807:     my (@parts) = &getpartlist($symb,$errorref);
                   4808:     if (ref($errorref)) {
                   4809:         if ($$errorref) {
                   4810:             return;
                   4811:         }
                   4812:     }
                   4813: 
1.556     weissno  4814:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4815: 		['username','Student Username'],
1.743     raeburn  4816: 		['clicker','Clicker ID'],
1.243     albertel 4817: 		['domain','Student Domain']);
1.324     albertel 4818:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4819:     foreach my $part (sort(@parts)) {
                   4820: 	my @datum;
1.745     raeburn  4821: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4822: 	my $name=$part;
1.745     raeburn  4823: 	if (!$display) { $display = $name; }
1.41      ng       4824: 	@datum=($name,$display);
1.244     albertel 4825: 	if ($name=~/^stores_(.*)_awarded/) {
                   4826: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4827: 	}
1.41      ng       4828: 	push(@fields,\@datum);
                   4829:     }
                   4830:     return (@fields);
1.26      albertel 4831: }
                   4832: 
                   4833: sub csvuploadmap_footer {
1.41      ng       4834:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4835:     my $buttontext = &mt('Assign Grades');
1.41      ng       4836:     $request->print(<<ENDPICK);
1.26      albertel 4837: </table>
                   4838: <input type="hidden" name="nfields" value="$i" />
                   4839: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4840: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4841: </form>
                   4842: ENDPICK
                   4843: }
                   4844: 
1.283     albertel 4845: sub checkforfile_js {
1.638     www      4846:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4847:     &js_escape(\$alertmsg);
1.597     wenzelju 4848:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4849:     function checkUpload(formname) {
                   4850: 	if (formname.upfile.value == "") {
1.539     riegler  4851: 	    alert("$alertmsg");
1.86      ng       4852: 	    return false;
                   4853: 	}
                   4854: 	formname.submit();
                   4855:     }
                   4856: CSVFORMJS
1.283     albertel 4857:     return $result;
                   4858: }
                   4859: 
                   4860: sub upcsvScores_form {
1.608     www      4861:     my ($request,$symb) = @_;
1.283     albertel 4862:     if (!$symb) {return '';}
                   4863:     my $result=&checkforfile_js();
1.632     www      4864:     $result.=&Apache::loncommon::start_data_table().
                   4865:              &Apache::loncommon::start_data_table_header_row().
                   4866:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4867:              &Apache::loncommon::end_data_table_header_row().
                   4868:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4869:     my $upload=&mt("Upload Scores");
1.86      ng       4870:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4871:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4872:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4873:     $result.=<<ENDUPFORM;
1.106     albertel 4874: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4875: <input type="hidden" name="symb" value="$symb" />
                   4876: <input type="hidden" name="command" value="csvuploadmap" />
                   4877: $upfile_select
1.589     bisitz   4878: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4879: </form>
                   4880: ENDUPFORM
1.370     www      4881:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4882:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4883:              '</td>'.
                   4884:             &Apache::loncommon::end_data_table_row().
                   4885:             &Apache::loncommon::end_data_table();
1.86      ng       4886:     return $result;
                   4887: }
                   4888: 
                   4889: 
1.26      albertel 4890: sub csvuploadmap {
1.768     raeburn  4891:     my ($request,$symb) = @_;
1.41      ng       4892:     if (!$symb) {return '';}
1.72      ng       4893: 
1.41      ng       4894:     my $datatoken;
1.257     albertel 4895:     if (!$env{'form.datatoken'}) {
1.41      ng       4896: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4897:     } else {
1.742     raeburn  4898: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4899:         if ($datatoken ne '') {
                   4900: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4901:         }
1.26      albertel 4902:     }
1.41      ng       4903:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4904:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4905:     my ($i,$keyfields);
                   4906:     if (@records) {
1.582     raeburn  4907:         my $fieldserror;
                   4908: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4909:         if ($fieldserror) {
                   4910:             $request->print(&navmap_errormsg());
                   4911:             return;
                   4912:         }
1.257     albertel 4913: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4914: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4915: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4916: 							  \@fields);
                   4917: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4918: 	    chop($keyfields);
                   4919: 	} else {
                   4920: 	    unshift(@fields,['none','']);
                   4921: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4922: 							    \@fields);
1.311     banghart 4923:             foreach my $rec (@records) {
                   4924:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4925:                 if (%temp) {
                   4926:                     $keyfields=join(',',sort(keys(%temp)));
                   4927:                     last;
                   4928:                 }
                   4929:             }
1.41      ng       4930: 	}
                   4931:     }
                   4932:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4933: 
1.41      ng       4934:     return '';
1.27      albertel 4935: }
                   4936: 
1.246     albertel 4937: sub csvuploadoptions {
1.608     www      4938:     my ($request,$symb)= @_;
1.632     www      4939:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4940:     $request->print(<<ENDPICK);
                   4941: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4942: <input type="hidden" name="command"    value="csvuploadassign" />
                   4943: <p>
                   4944: <label>
                   4945:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4946:    $overwrite
1.246     albertel 4947: </label>
                   4948: </p>
                   4949: ENDPICK
                   4950:     my %fields=&get_fields();
                   4951:     if (!defined($fields{'domain'})) {
1.257     albertel 4952: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4953: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4954:     }
1.257     albertel 4955:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4956: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4957: 	my $cleankey=$1;
                   4958: 	if ($cleankey eq 'command') { next; }
                   4959: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4960: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4961:     }
                   4962:     # FIXME do a check for any duplicated user ids...
                   4963:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4964:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4965: <hr /></form>'."\n");
1.246     albertel 4966:     return '';
                   4967: }
                   4968: 
                   4969: sub get_fields {
                   4970:     my %fields;
1.257     albertel 4971:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4972:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4973: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4974: 	    if ($env{'form.f'.$i} ne 'none') {
                   4975: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4976: 	    }
                   4977: 	} else {
1.257     albertel 4978: 	    if ($env{'form.f'.$i} ne 'none') {
                   4979: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4980: 	    }
                   4981: 	}
1.27      albertel 4982:     }
1.246     albertel 4983:     return %fields;
                   4984: }
                   4985: 
                   4986: sub csvuploadassign {
1.766     raeburn  4987:     my ($request,$symb) = @_;
1.246     albertel 4988:     if (!$symb) {return '';}
1.345     bowersj2 4989:     my $error_msg = '';
1.742     raeburn  4990:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4991:     if ($datatoken ne '') { 
                   4992:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4993:     }
1.246     albertel 4994:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4995:     my %fields=&get_fields();
1.257     albertel 4996:     my $courseid=$env{'request.course.id'};
1.97      albertel 4997:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4998:     my @notallowed;
1.41      ng       4999:     my @skipped;
1.657     raeburn  5000:     my @warnings;
1.41      ng       5001:     my $countdone=0;
                   5002:     foreach my $grade (@gradedata) {
                   5003: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 5004: 	my $domain;
                   5005: 	if ($entries{$fields{'domain'}}) {
                   5006: 	    $domain=$entries{$fields{'domain'}};
                   5007: 	} else {
1.257     albertel 5008: 	    $domain=$env{'form.default_domain'};
1.246     albertel 5009: 	}
1.243     albertel 5010: 	$domain=~s/\s//g;
1.41      ng       5011: 	my $username=$entries{$fields{'username'}};
1.160     albertel 5012: 	$username=~s/\s//g;
1.243     albertel 5013: 	if (!$username) {
                   5014: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 5015: 	    $id=~s/\s//g;
1.737     raeburn  5016:             if ($id ne '') {
                   5017: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   5018: 	        $username=$ids{$id};
                   5019:             } else {
                   5020:                 if ($entries{$fields{'clicker'}}) {
                   5021:                     my $clicker = $entries{$fields{'clicker'}};
                   5022:                     $clicker=~s/\s//g;
                   5023:                     if ($clicker ne '') {
                   5024:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   5025:                         if ($clickers{$clicker} ne '') {  
                   5026:                             my $match = 0;
                   5027:                             my @inclass;
                   5028:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   5029:                                 if (exists($$classlist{"$poss:$domain"})) {
                   5030:                                     $username = $poss;
                   5031:                                     push(@inclass,$poss);
                   5032:                                     $match ++;
                   5033:                                     
                   5034:                                 }
                   5035:                             }
                   5036:                             if ($match > 1) {
                   5037:                                 undef($username); 
                   5038:                                 $request->print('<p class="LC_warning">'.
                   5039:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   5040:                                                 $clicker,join(', ',@inclass)).'</p>');
                   5041:                             }
                   5042:                         }
                   5043:                     }
                   5044:                 }
                   5045:             }
1.243     albertel 5046: 	}
1.41      ng       5047: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 5048: 	    my $id=$entries{$fields{'ID'}};
                   5049: 	    $id=~s/\s//g;
1.737     raeburn  5050:             my $clicker = $entries{$fields{'clicker'}};
                   5051:             $clicker=~s/\s//g;
                   5052:             if ($clicker) {
                   5053:                 push(@skipped,"$clicker:$domain");
                   5054: 	    } elsif ($id) {
1.247     albertel 5055: 		push(@skipped,"$id:$domain");
                   5056: 	    } else {
                   5057: 		push(@skipped,"$username:$domain");
                   5058: 	    }
1.41      ng       5059: 	    next;
                   5060: 	}
1.108     albertel 5061: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 5062: 	if (!&canmodify($usec)) {
                   5063: 	    push(@notallowed,"$username:$domain");
                   5064: 	    next;
                   5065: 	}
1.244     albertel 5066: 	my %points;
1.41      ng       5067: 	my %grades;
                   5068: 	foreach my $dest (keys(%fields)) {
1.244     albertel 5069: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   5070: 		$dest eq 'domain') { next; }
                   5071: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   5072: 	    if ($dest=~/stores_(.*)_points/) {
                   5073: 		my $part=$1;
                   5074: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   5075: 					      $symb,$domain,$username);
1.345     bowersj2 5076:                 if ($wgt) {
                   5077:                     $entries{$fields{$dest}}=~s/\s//g;
                   5078:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5079:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5080:                                           : 'correct_by_override';
1.638     www      5081:                     if ($pcr>1) {
1.657     raeburn  5082:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      5083:                     }
1.345     bowersj2 5084:                     $grades{"resource.$part.awarded"}=$pcr;
                   5085:                     $grades{"resource.$part.solved"}=$award;
                   5086:                     $points{$part}=1;
                   5087:                 } else {
                   5088:                     $error_msg = "<br />" .
                   5089:                         &mt("Some point values were assigned"
                   5090:                             ." for problems with a weight "
                   5091:                             ."of zero. These values were "
                   5092:                             ."ignored.");
                   5093:                 }
1.244     albertel 5094: 	    } else {
                   5095: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5096: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5097: 		my $store_key=$dest;
                   5098: 		$store_key=~s/^stores/resource/;
                   5099: 		$store_key=~s/_/\./g;
                   5100: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5101: 	    }
1.41      ng       5102: 	}
1.766     raeburn  5103: 	if (! %grades) {
1.508     www      5104:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5105:         } else {
                   5106: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5107: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5108: 					   $env{'request.course.id'},
                   5109: 					   $domain,$username);
1.508     www      5110: 	   if ($result eq 'ok') {
1.627     www      5111: # Successfully stored
1.508     www      5112: 	      $request->print('.');
1.627     www      5113: # Remove from grading queue
                   5114:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5115:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5116:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5117:                                              $domain,$username);
                   5118:               $countdone++;
                   5119:            } else {
1.508     www      5120: 	      $request->print("<p><span class=\"LC_error\">".
                   5121:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5122:                                   "$username:$domain",$result)."</span></p>");
                   5123: 	   }
                   5124: 	   $request->rflush();
                   5125:         }
1.41      ng       5126:     }
1.570     www      5127:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  5128:     if (@warnings) {
                   5129:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5130:         $request->print(join(', ',@warnings));
                   5131:     }
1.41      ng       5132:     if (@skipped) {
1.571     www      5133: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5134:         $request->print(join(', ',@skipped));
1.106     albertel 5135:     }
                   5136:     if (@notallowed) {
1.571     www      5137: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5138: 	$request->print(join(', ',@notallowed));
1.41      ng       5139:     }
1.106     albertel 5140:     $request->print("<br />\n");
1.345     bowersj2 5141:     return $error_msg;
1.26      albertel 5142: }
1.44      ng       5143: #------------- end of section for handling csv file upload ---------
                   5144: #
                   5145: #-------------------------------------------------------------------
                   5146: #
1.122     ng       5147: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5148: #
                   5149: #--- Select a page/sequence and a student to grade
1.68      ng       5150: sub pickStudentPage {
1.608     www      5151:     my ($request,$symb) = @_;
1.68      ng       5152: 
1.539     riegler  5153:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  5154:     &js_escape(\$alertmsg);
1.597     wenzelju 5155:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5156: 
                   5157: function checkPickOne(formname) {
1.76      ng       5158:     if (radioSelection(formname.student) == null) {
1.539     riegler  5159: 	alert("$alertmsg");
1.68      ng       5160: 	return;
                   5161:     }
1.125     ng       5162:     ptr = pullDownSelection(formname.selectpage);
                   5163:     formname.page.value = formname["page"+ptr].value;
                   5164:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5165:     formname.submit();
                   5166: }
                   5167: 
                   5168: LISTJAVASCRIPT
1.118     ng       5169:     &commonJSfunctions($request);
1.608     www      5170: 
1.257     albertel 5171:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5172:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5173:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  5174:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5175: 
1.398     albertel 5176:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5177: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5178: 
1.80      ng       5179:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5180:     my $map_error;
                   5181:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5182:     if ($map_error) {
                   5183:         $request->print(&navmap_errormsg());
                   5184:         return; 
                   5185:     }
1.137     albertel 5186:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5187: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5188: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   5189: 
                   5190:     # Collection of hidden fields
1.70      ng       5191:     my $ctr=0;
1.68      ng       5192:     foreach (@$titles) {
1.700     bisitz   5193:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5194:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5195:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5196:         $ctr++;
1.68      ng       5197:     }
1.700     bisitz   5198:     $result.='<input type="hidden" name="page" />'."\n".
                   5199:         '<input type="hidden" name="title" />'."\n";
                   5200: 
                   5201:     $result.=&build_section_inputs();
                   5202:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5203:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   5204: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   5205: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 5206: 
1.700     bisitz   5207:     # Show grading options
                   5208:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5209:     my $select = '<select name="selectpage">'."\n";
1.70      ng       5210:     $ctr=0;
                   5211:     foreach (@$titles) {
                   5212: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   5213: 	$select.='<option value="'.$ctr.'"'.
                   5214: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5215: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       5216: 	$ctr++;
                   5217:     }
1.700     bisitz   5218:     $select.= '</select>';
1.68      ng       5219: 
1.700     bisitz   5220:     $result.=
                   5221:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5222:        .$select
                   5223:        .&Apache::lonhtmlcommon::row_closure();
                   5224: 
                   5225:     $result.=
                   5226:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5227:        .'<label><input type="radio" name="vProb" value="no"'
                   5228:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5229:        .'<label><input type="radio" name="vProb" value="yes" />'
                   5230:            .&mt('yes').'</label>'."\n"
                   5231:        .&Apache::lonhtmlcommon::row_closure();
                   5232: 
                   5233:     $result.=
                   5234:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5235:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5236:            .&mt('none').' </label>'."\n"
                   5237:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5238:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5239:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5240:            .&mt('all submissions with details').' </label>'
                   5241:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 5242:     
1.700     bisitz   5243:     $result.=
                   5244:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5245:        .'<input type="text" name="CODE" value="" />'
                   5246:        .&Apache::lonhtmlcommon::row_closure(1)
                   5247:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5248: 
1.700     bisitz   5249:     # Show list of students to select for grading
                   5250:     $result.='<br /><input type="button" '.
1.589     bisitz   5251:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5252: 
1.68      ng       5253:     $request->print($result);
                   5254: 
1.485     albertel 5255:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5256: 	&Apache::loncommon::start_data_table().
                   5257: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5258: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5259: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5260: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5261: 	'<th>'.&nameUserString('header').'</th>'.
                   5262: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5263:  
1.761     raeburn  5264:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5265:     my $ptr = 1;
1.294     albertel 5266:     foreach my $student (sort 
                   5267: 			 {
                   5268: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5269: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5270: 			     }
                   5271: 			     return $a cmp $b;
                   5272: 			 } (keys(%$fullname))) {
1.68      ng       5273: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5274: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5275:                                   : '</td>');
1.126     ng       5276: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5277: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5278: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5279: 	$studentTable.=
                   5280: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5281:                          : '');
1.68      ng       5282: 	$ptr++;
                   5283:     }
1.484     albertel 5284:     if ($ptr%2 == 0) {
                   5285: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5286: 	    &Apache::loncommon::end_data_table_row();
                   5287:     }
                   5288:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5289:     $studentTable.='<input type="button" '.
1.589     bisitz   5290:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5291: 
                   5292:     $request->print($studentTable);
                   5293: 
                   5294:     return '';
                   5295: }
                   5296: 
                   5297: sub getSymbMap {
1.582     raeburn  5298:     my ($map_error) = @_;
1.132     bowersj2 5299:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5300:     unless (ref($navmap)) {
                   5301:         if (ref($map_error)) {
                   5302:             $$map_error = 'navmap';
                   5303:         }
                   5304:         return;
                   5305:     }
1.68      ng       5306:     my %symbx = ();
                   5307:     my @titles = ();
1.117     bowersj2 5308:     my $minder = 0;
                   5309: 
                   5310:     # Gather every sequence that has problems.
1.240     albertel 5311:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5312: 					       1,0,1);
1.117     bowersj2 5313:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5314: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5315: 	    my $title = $minder.'.'.
                   5316: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5317: 	    push(@titles, $title); # minder in case two titles are identical
                   5318: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5319: 	    $minder++;
1.241     albertel 5320: 	}
1.68      ng       5321:     }
                   5322:     return \@titles,\%symbx;
                   5323: }
                   5324: 
1.72      ng       5325: #
                   5326: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5327: sub displayPage {
1.608     www      5328:     my ($request,$symb) = @_;
1.257     albertel 5329:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5330:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5331:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5332:     my $pageTitle = $env{'form.page'};
1.103     albertel 5333:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5334:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5335:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5336: 
                   5337:     #need to make sure we have the correct data for later EXT calls, 
                   5338:     #thus invalidate the cache
                   5339:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5340:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5341:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5342:     &Apache::lonnet::clear_EXT_cache_status();
                   5343: 
1.103     albertel 5344:     if (!&canview($usec)) {
1.712     bisitz   5345:         $request->print(
                   5346:             '<span class="LC_warning">'.
                   5347:             &mt('Unable to view requested student. ([_1])',
                   5348:                     $env{'form.student'}).
                   5349:             '</span>');
                   5350:         return;
1.103     albertel 5351:     }
1.398     albertel 5352:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5353:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5354: 	'</h3>'."\n";
1.500     albertel 5355:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5356:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5357: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5358:     } else {
                   5359: 	delete($env{'form.CODE'});
                   5360:     }
1.71      ng       5361:     &sub_page_js($request);
                   5362:     $request->print($result);
                   5363: 
1.132     bowersj2 5364:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5365:     unless (ref($navmap)) {
                   5366:         $request->print(&navmap_errormsg());
                   5367:         return;
                   5368:     }
1.257     albertel 5369:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5370:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5371:     if (!$map) {
1.485     albertel 5372: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5373: 	return; 
                   5374:     }
1.68      ng       5375:     my $iterator = $navmap->getIterator($map->map_start(),
                   5376: 					$map->map_finish());
                   5377: 
1.71      ng       5378:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5379: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5380: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5381: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5382: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5383: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5384: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5385: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5386: 
1.382     albertel 5387:     if (defined($env{'form.CODE'})) {
                   5388: 	$studentTable.=
                   5389: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5390:     }
1.381     albertel 5391:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5392: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5393: 
1.594     bisitz   5394:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5395:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5396:         '</span>'."\n".
1.484     albertel 5397: 	&Apache::loncommon::start_data_table().
                   5398: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5399: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5400: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5401: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5402: 
1.329     albertel 5403:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5404:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5405:     $iterator->next(); # skip the first BEGIN_MAP
                   5406:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5407:     while ($depth > 0) {
1.68      ng       5408:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5409:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5410: 
1.745     raeburn  5411:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5412: 	    my $parts = $curRes->parts();
1.68      ng       5413:             my $title = $curRes->compTitle();
1.71      ng       5414: 	    my $symbx = $curRes->symb();
1.746     raeburn  5415:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5416: 	    $studentTable.=
                   5417: 		&Apache::loncommon::start_data_table_row().
                   5418: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5419: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5420: 		                        : '<br />('.&mt('[_1]parts',
                   5421: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5422: 		 ).
                   5423: 		 '</td>';
1.71      ng       5424: 	    $studentTable.='<td valign="top">';
1.382     albertel 5425: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5426:             if ($is_tool) {
                   5427:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5428:             } else {
1.745     raeburn  5429: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5430: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5431: 					         undef,'both',\%form);
                   5432: 	        } else {
                   5433: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5434: 		    $companswer =~ s|<form(.*?)>||g;
                   5435: 		    $companswer =~ s|</form>||g;
                   5436: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5437: #		        $companswer =~ s/$1/ /ms;
                   5438: #		        $request->print('match='.$1."<br />\n");
                   5439: #		    }
                   5440: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5441: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5442: 		}
1.71      ng       5443: 	    }
                   5444: 
1.257     albertel 5445: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5446: 
1.257     albertel 5447: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5448: 		if ($record{'version'} eq '') {
1.745     raeburn  5449:                     my $msg = &mt('No recorded submission for this problem.');
                   5450:                     if ($is_tool) {
                   5451:                         $msg = &mt('No recorded transactions for this external tool');
                   5452:                     }
                   5453: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5454: 		} else {
1.116     ng       5455: 		    my %responseType = ();
                   5456: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5457: 			my @responseIds =$curRes->responseIds($partid);
                   5458: 			my @responseType =$curRes->responseType($partid);
                   5459: 			my %responseIds;
                   5460: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5461: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5462: 			}
                   5463: 			$responseType{$partid} = \%responseIds;
1.116     ng       5464: 		    }
1.148     albertel 5465: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5466: 		}
1.257     albertel 5467: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5468: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5469:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5470: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5471: 									$env{'request.course.id'},
1.726     raeburn  5472: 									'','.submission',undef,
                   5473:                                                                         $usec,$identifier);
1.71      ng       5474:  
                   5475: 	    }
1.103     albertel 5476: 	    if (&canmodify($usec)) {
1.585     bisitz   5477:             $studentTable.=&gradeBox_start();
1.103     albertel 5478: 		foreach my $partid (@{$parts}) {
                   5479: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5480: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5481: 		    $question++;
                   5482: 		}
1.585     bisitz   5483:             $studentTable.=&gradeBox_end();
1.196     albertel 5484: 		$prob++;
1.71      ng       5485: 	    }
                   5486: 	    $studentTable.='</td></tr>';
1.68      ng       5487: 
1.103     albertel 5488: 	}
1.68      ng       5489:         $curRes = $iterator->next();
                   5490:     }
1.780     raeburn  5491:     my $disabled;
                   5492:     unless (&canmodify($usec)) {
                   5493:         $disabled = ' disabled="disabled"';
                   5494:     }
1.68      ng       5495: 
1.589     bisitz   5496:     $studentTable.=
                   5497:         '</table>'."\n".
1.780     raeburn  5498:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5499:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5500:         '</form>'."\n";
1.71      ng       5501:     $request->print($studentTable);
                   5502: 
                   5503:     return '';
1.119     ng       5504: }
                   5505: 
                   5506: sub displaySubByDates {
1.148     albertel 5507:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5508:     my $isCODE=0;
1.335     albertel 5509:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5510:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5511:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5512:     my $studentTable=&Apache::loncommon::start_data_table().
                   5513: 	&Apache::loncommon::start_data_table_header_row().
                   5514: 	'<th>'.&mt('Date/Time').'</th>'.
                   5515: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5516:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5517: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5518: 	'<th>'.&mt('Status').'</th>'.
                   5519: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5520:     my ($version);
                   5521:     my %mark;
1.148     albertel 5522:     my %orders;
1.119     ng       5523:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5524:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5525:         if ($is_tool) {
                   5526:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5527:         } else {
                   5528:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5529:         }
1.147     albertel 5530:     }
1.335     albertel 5531: 
                   5532:     my $interaction;
1.525     raeburn  5533:     my $no_increment = 1;
1.735     raeburn  5534:     my (%lastrndseed,%lasttype);
1.119     ng       5535:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5536: 	my $timestamp = 
                   5537: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5538: 	if (exists($$record{$version.':resource.0.version'})) {
                   5539: 	    $interaction = $$record{$version.':resource.0.version'};
                   5540: 	}
1.671     raeburn  5541:         if ($isTask && $env{'form.previousversion'}) {
                   5542:             next unless ($interaction == $env{'form.previousversion'});
                   5543:         }
1.335     albertel 5544: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5545: 		             : "$version:resource");
1.467     albertel 5546: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5547: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5548: 	if ($isCODE) {
                   5549: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5550: 	}
1.671     raeburn  5551:         if ($isTask) {
                   5552:             $studentTable.='<td>'.$interaction.'</td>';
                   5553:         }
1.119     ng       5554: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5555: 	my @displaySub = ();
                   5556: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5557:             my ($hidden,$type);
                   5558:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5559:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5560:                 $hidden = 1;
                   5561:             }
1.749     raeburn  5562:             my @matchKey;
                   5563:             if ($isTask) {
1.769     raeburn  5564:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  5565:             } elsif ($is_tool) {
1.769     raeburn  5566:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  5567:             } else {
1.769     raeburn  5568:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  5569:             }
1.122     ng       5570: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5571: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5572: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5573: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5574: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5575:                     if ($is_tool) {
                   5576:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5577:                     } else {
1.749     raeburn  5578: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5579: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5580:                         $displaySub[0].='<span class="LC_nobreak">';
                   5581:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5582:                                        .' <span class="LC_internal_info">'
                   5583:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5584:                                        .'</span>'
                   5585:                                        .' <b>';
                   5586:                         if ($hidden) {
                   5587:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5588:                         } else {
                   5589:                             my ($trial,$rndseed,$newvariation);
                   5590:                             if ($type eq 'randomizetry') {
                   5591:                                 $trial = $$record{"$where.$partid.tries"};
                   5592:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5593:                             }
                   5594: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5595: 			        $displaySub[0].=&mt('Trial not counted');
                   5596: 		            } else {
                   5597: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5598: 					        $$record{"$where.$partid.tries"});
                   5599:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5600:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5601:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5602:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5603:                                     }
1.640     raeburn  5604:                                 }
1.749     raeburn  5605:                                 $lastrndseed{$partid} = $rndseed;
                   5606:                                 $lasttype{$partid} = $type;
                   5607: 		            }
                   5608: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5609:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5610: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5611: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5612: 			        $orders{$partid}->{$responseId}=
                   5613: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5614:                                                $no_increment,$type,$trial,$rndseed);
                   5615: 		            }
                   5616: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5617: 		            $displaySub[0].='&nbsp; '.
                   5618: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5619:                         }
1.596     raeburn  5620:                     }
1.147     albertel 5621: 		}
                   5622: 	    }
1.335     albertel 5623: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5624: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5625: 				    $$record{"$where.$partid.checkedin"},
                   5626: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5627: 					'<br />';
1.335     albertel 5628: 	    }
                   5629: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5630: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5631: 		    lc($$record{"$where.$partid.award"}).' '.
                   5632: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5633: 		    '<br />';
1.749     raeburn  5634: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5635: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5636: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5637: 		}
1.147     albertel 5638: 	    }
1.335     albertel 5639: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5640: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5641: 		unless ($is_tool) {
                   5642: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5643: 		}
1.335     albertel 5644: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5645: 		$displaySub[2].=
1.749     raeburn  5646: 		    $$record{"$version:resource.$partid.regrader"};
                   5647:                 unless ($is_tool) {
                   5648: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5649:                 }
1.147     albertel 5650: 	    }
                   5651: 	}
                   5652: 	# needed because old essay regrader has not parts info
                   5653: 	if (exists $$record{"$version:resource.regrader"}) {
                   5654: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5655: 	}
                   5656: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5657: 	if ($displaySub[2]) {
1.467     albertel 5658: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5659: 	}
1.467     albertel 5660: 	$studentTable.='&nbsp;</td>'.
                   5661: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5662:     }
1.467     albertel 5663:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5664:     return $studentTable;
1.71      ng       5665: }
                   5666: 
                   5667: sub updateGradeByPage {
1.608     www      5668:     my ($request,$symb) = @_;
1.71      ng       5669: 
1.257     albertel 5670:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5671:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5672:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5673:     my $pageTitle = $env{'form.page'};
1.103     albertel 5674:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5675:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5676:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5677:     if (!&canmodify($usec)) {
1.526     raeburn  5678: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5679: 	return;
                   5680:     }
1.398     albertel 5681:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5682:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5683: 	'</h3>'."\n";
1.70      ng       5684: 
1.68      ng       5685:     $request->print($result);
                   5686: 
1.582     raeburn  5687: 
1.132     bowersj2 5688:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5689:     unless (ref($navmap)) {
                   5690:         $request->print(&navmap_errormsg());
                   5691:         return;
                   5692:     }
1.257     albertel 5693:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5694:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5695:     if (!$map) {
1.527     raeburn  5696: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5697: 	return; 
                   5698:     }
1.71      ng       5699:     my $iterator = $navmap->getIterator($map->map_start(),
                   5700: 					$map->map_finish());
1.70      ng       5701: 
1.484     albertel 5702:     my $studentTable=
                   5703: 	&Apache::loncommon::start_data_table().
                   5704: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5705: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5706: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5707: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5708: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5709: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5710: 
                   5711:     $iterator->next(); # skip the first BEGIN_MAP
                   5712:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5713:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5714:     while ($depth > 0) {
1.71      ng       5715:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5716:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5717: 
1.385     albertel 5718:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5719: 	    my $parts = $curRes->parts();
1.71      ng       5720:             my $title = $curRes->compTitle();
                   5721: 	    my $symbx = $curRes->symb();
1.484     albertel 5722: 	    $studentTable.=
                   5723: 		&Apache::loncommon::start_data_table_row().
                   5724: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5725: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5726:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5727: 		.')').'</td>';
1.71      ng       5728: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5729: 
                   5730: 	    my %newrecord=();
                   5731: 	    my @displayPts=();
1.269     raeburn  5732:             my %aggregate = ();
                   5733:             my $aggregateflag = 0;
1.787   ! raeburn  5734:             my %queueable;
1.726     raeburn  5735:             if ($env{'form.HIDE'.$prob}) {
                   5736:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5737:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5738:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5739:                 $hideflag += $numchgs;
                   5740:             }
1.71      ng       5741: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5742: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5743: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.787   ! raeburn  5744:                 my @types = $curRes->responseType($partid);
1.786     raeburn  5745:                 if (grep(/^essay$/,@types)) {
                   5746:                     $queueable{$partid} = 1;
                   5747:                 } else {
1.787   ! raeburn  5748:                     my @ids = $curRes->responseIds($partid);
1.786     raeburn  5749:                     for (my $i=0; $i < scalar(@ids); $i++) {
1.787   ! raeburn  5750:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
1.786     raeburn  5751:                                                           '.handgrade',$symb);
                   5752:                         if (lc($hndgrd) eq 'yes') {
                   5753:                             $queueable{$partid} = 1;
                   5754:                             last;
                   5755:                         }
                   5756:                     }
                   5757:                 }
1.257     albertel 5758: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5759: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5760: 		my $partial = $newpts/$wgt;
                   5761: 		my $score;
                   5762: 		if ($partial > 0) {
                   5763: 		    $score = 'correct_by_override';
1.125     ng       5764: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5765: 		    $score = 'incorrect_by_override';
                   5766: 		}
1.257     albertel 5767: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5768: 		if ($dropMenu eq 'excused') {
1.71      ng       5769: 		    $partial = '';
                   5770: 		    $score = 'excused';
1.125     ng       5771: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5772: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5773: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5774: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5775: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5776: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5777: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5778: 		    $changeflag++;
                   5779: 		    $newpts = '';
1.269     raeburn  5780:                     
                   5781:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5782:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5783:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5784:                     if ($aggtries > 0) {
                   5785:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5786:                         $aggregateflag = 1;
                   5787:                     }
1.71      ng       5788: 		}
1.324     albertel 5789: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5790: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5791: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5792: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5793: 		    '&nbsp;<br />';
1.526     raeburn  5794: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5795: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5796: 		    '&nbsp;<br />';
1.71      ng       5797: 		$question++;
1.380     albertel 5798: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5799: 
1.71      ng       5800: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5801: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5802: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5803: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5804: 
                   5805: 		$changeflag++;
                   5806: 	    }
                   5807: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5808: 		my %record = 
                   5809: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5810: 					     $udom,$uname);
                   5811: 
                   5812: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5813: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5814: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5815: 		    $newrecord{'resource.CODE'} = '';
                   5816: 		}
1.257     albertel 5817: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5818: 					$udom,$uname);
1.382     albertel 5819: 		%record = &Apache::lonnet::restore($symbx,
                   5820: 						   $env{'request.course.id'},
                   5821: 						   $udom,$uname);
1.380     albertel 5822: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.786     raeburn  5823: 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       5824: 	    }
1.380     albertel 5825: 	    
1.269     raeburn  5826:             if ($aggregateflag) {
                   5827:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5828:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5829:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5830:             }
1.125     ng       5831: 
1.71      ng       5832: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5833: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5834: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5835: 
1.196     albertel 5836: 	    $prob++;
1.68      ng       5837: 	}
1.71      ng       5838:         $curRes = $iterator->next();
1.68      ng       5839:     }
1.98      albertel 5840: 
1.484     albertel 5841:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5842:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5843: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5844: 		  $changeflag).'<br />');
                   5845:     my $hidemsg=($hideflag == 0 ? '' :
                   5846:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5847:                      $hideflag).'<br />');
                   5848:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5849: 
1.70      ng       5850:     return '';
                   5851: }
                   5852: 
1.72      ng       5853: #-------- end of section for handling grading by page/sequence ---------
                   5854: #
                   5855: #-------------------------------------------------------------------
                   5856: 
1.581     www      5857: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5858: #
                   5859: #------ start of section for handling grading by page/sequence ---------
                   5860: 
1.423     albertel 5861: =pod
                   5862: 
                   5863: =head1 Bubble sheet grading routines
                   5864: 
1.424     albertel 5865:   For this documentation:
                   5866: 
                   5867:    'scanline' refers to the full line of characters
                   5868:    from the file that we are parsing that represents one entire sheet
                   5869: 
                   5870:    'bubble line' refers to the data
1.659     raeburn  5871:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5872: 
                   5873: 
1.659     raeburn  5874: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5875: into a course. When a user wants to grade, they select a
1.659     raeburn  5876: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5877: one of the predefined configurations for what each scanline looks
                   5878: like.
                   5879: 
                   5880: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5881: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5882: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5883: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5884: invalid student/employee ID
1.424     albertel 5885: 
                   5886: If the CODE option is used that determines the randomization of the
1.556     weissno  5887: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5888: username:domain.
                   5889: 
                   5890: During the validation phase the instructor can choose to skip scanlines. 
                   5891: 
1.659     raeburn  5892: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5893: 
                   5894:   scantron_original_filename (unmodified original file)
                   5895:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5896:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5897: 
                   5898: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5899: correction information that isn't representable in the bubblesheet
1.424     albertel 5900: file (see &scantron_getfile() for more information)
                   5901: 
                   5902: After all scanlines are either valid, marked as valid or skipped, then
                   5903: foreach line foreach problem in the picked sequence, an ssi request is
                   5904: made that simulates a user submitting their selected letter(s) against
                   5905: the homework problem.
1.423     albertel 5906: 
                   5907: =over 4
                   5908: 
                   5909: 
                   5910: 
                   5911: =item defaultFormData
                   5912: 
                   5913:   Returns html hidden inputs used to hold context/default values.
                   5914: 
                   5915:  Arguments:
                   5916:   $symb - $symb of the current resource 
                   5917: 
                   5918: =cut
1.422     foxr     5919: 
1.81      albertel 5920: sub defaultFormData {
1.324     albertel 5921:     my ($symb)=@_;
1.766     raeburn  5922:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5923: }
                   5924: 
1.447     foxr     5925: 
1.423     albertel 5926: =pod 
                   5927: 
                   5928: =item getSequenceDropDown
                   5929: 
                   5930:    Return html dropdown of possible sequences to grade
                   5931:  
                   5932:  Arguments:
1.582     raeburn  5933:    $symb - $symb of the current resource
                   5934:    $map_error - ref to scalar which will container error if
                   5935:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5936: 
                   5937: =cut
1.422     foxr     5938: 
1.75      albertel 5939: sub getSequenceDropDown {
1.582     raeburn  5940:     my ($symb,$map_error)=@_;
1.75      albertel 5941:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5942:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5943:     if (ref($map_error)) {
                   5944:         return if ($$map_error);
                   5945:     }
1.137     albertel 5946:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5947:     my $ctr=0;
                   5948:     foreach (@$titles) {
                   5949: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5950: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5951: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5952: 	    '>'.$showtitle.'</option>'."\n";
                   5953: 	$ctr++;
                   5954:     }
                   5955:     $result.= '</select>';
                   5956:     return $result;
                   5957: }
                   5958: 
1.495     albertel 5959: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5960:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5961: 
                   5962: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5963: 
1.509     raeburn  5964: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5965:                                    # matchresponse or rankresponse, where 
                   5966:                                    # an individual response can have multiple 
                   5967:                                    # lines
1.503     raeburn  5968: 
                   5969: my %responsetype_per_response;     # responsetype for each response
                   5970: 
1.691     raeburn  5971: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5972:                                    # numbered response. Needed when randomorder
                   5973:                                    # or randompick are in use. Key is ID, value 
                   5974:                                    # is response number.
                   5975: 
1.495     albertel 5976: # Save and restore the bubble lines array to the form env.
                   5977: 
                   5978: 
                   5979: sub save_bubble_lines {
                   5980:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5981: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5982: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5983: 	    $first_bubble_line{$line};
1.503     raeburn  5984:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5985:             $subdivided_bubble_lines{$line};
                   5986:         $env{"form.scantron.responsetype.$line"} =
                   5987:             $responsetype_per_response{$line};
1.495     albertel 5988:     }
1.691     raeburn  5989:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5990:         my $line = $masterseq_id_responsenum{$resid};
                   5991:         $env{"form.scantron.residpart.$line"} = $resid;
                   5992:     }
1.495     albertel 5993: }
                   5994: 
                   5995: 
                   5996: sub restore_bubble_lines {
                   5997:     my $line = 0;
                   5998:     %bubble_lines_per_response = ();
1.691     raeburn  5999:     %masterseq_id_responsenum = ();
1.495     albertel 6000:     while ($env{"form.scantron.bubblelines.$line"}) {
                   6001: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   6002: 	$bubble_lines_per_response{$line} = $value;
                   6003: 	$first_bubble_line{$line}  =
                   6004: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  6005:         $subdivided_bubble_lines{$line} =
                   6006:             $env{"form.scantron.sub_bubblelines.$line"};
                   6007:         $responsetype_per_response{$line} =
                   6008:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  6009:         my $id = $env{"form.scantron.residpart.$line"};
                   6010:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 6011: 	$line++;
                   6012:     }
                   6013: }
                   6014: 
1.423     albertel 6015: =pod 
                   6016: 
                   6017: =item scantron_filenames
                   6018: 
                   6019:    Returns a list of the scantron files in the current course 
                   6020: 
                   6021: =cut
1.422     foxr     6022: 
1.202     albertel 6023: sub scantron_filenames {
1.257     albertel 6024:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6025:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  6026:     my $getpropath = 1;
1.662     raeburn  6027:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   6028:                                                         $cname,$getpropath);
1.202     albertel 6029:     my @possiblenames;
1.662     raeburn  6030:     if (ref($dirlist) eq 'ARRAY') {
                   6031:         foreach my $filename (sort(@{$dirlist})) {
                   6032: 	    ($filename)=split(/&/,$filename);
                   6033: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   6034: 	    $filename=~s/^scantron_orig_//;
                   6035: 	    push(@possiblenames,$filename);
                   6036:         }
1.202     albertel 6037:     }
                   6038:     return @possiblenames;
                   6039: }
                   6040: 
1.423     albertel 6041: =pod 
                   6042: 
                   6043: =item scantron_uploads
                   6044: 
                   6045:    Returns  html drop-down list of scantron files in current course.
                   6046: 
                   6047:  Arguments:
                   6048:    $file2grade - filename to set as selected in the dropdown
                   6049: 
                   6050: =cut
1.422     foxr     6051: 
1.202     albertel 6052: sub scantron_uploads {
1.209     ng       6053:     my ($file2grade) = @_;
1.202     albertel 6054:     my $result=	'<select name="scantron_selectfile">';
                   6055:     $result.="<option></option>";
                   6056:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 6057: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 6058:     }
                   6059:     $result.="</select>";
                   6060:     return $result;
                   6061: }
                   6062: 
1.423     albertel 6063: =pod 
                   6064: 
                   6065: =item scantron_scantab
                   6066: 
                   6067:   Returns html drop down of the scantron formats in the scantronformat.tab
                   6068:   file.
                   6069: 
                   6070: =cut
1.422     foxr     6071: 
1.82      albertel 6072: sub scantron_scantab {
                   6073:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 6074:     $result.='<option></option>'."\n";
1.754     raeburn  6075:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  6076:     if (@lines > 0) {
                   6077:         foreach my $line (@lines) {
                   6078:             next if (($line =~ /^\#/) || ($line eq ''));
                   6079: 	    my ($name,$descrip)=split(/:/,$line);
                   6080: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   6081:         }
1.82      albertel 6082:     }
                   6083:     $result.='</select>'."\n";
1.518     raeburn  6084:     return $result;
                   6085: }
                   6086: 
1.423     albertel 6087: =pod 
                   6088: 
                   6089: =item scantron_CODElist
                   6090: 
                   6091:   Returns html drop down of the saved CODE lists from current course,
                   6092:   generated from earlier printings.
                   6093: 
                   6094: =cut
1.422     foxr     6095: 
1.186     albertel 6096: sub scantron_CODElist {
1.257     albertel 6097:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6098:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 6099:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   6100:     my $namechoice='<option></option>';
1.225     albertel 6101:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 6102: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 6103: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 6104: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   6105:     }
                   6106:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6107:     return $namechoice;
                   6108: }
                   6109: 
1.423     albertel 6110: =pod 
                   6111: 
                   6112: =item scantron_CODEunique
                   6113: 
                   6114:   Returns the html for "Each CODE to be used once" radio.
                   6115: 
                   6116: =cut
1.422     foxr     6117: 
1.186     albertel 6118: sub scantron_CODEunique {
1.532     bisitz   6119:     my $result='<span class="LC_nobreak">
1.272     albertel 6120:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6121:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6122:                 </span>
1.532     bisitz   6123:                 <span class="LC_nobreak">
1.272     albertel 6124:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6125:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6126:                 </span>';
1.186     albertel 6127:     return $result;
                   6128: }
1.423     albertel 6129: 
                   6130: =pod 
                   6131: 
                   6132: =item scantron_selectphase
                   6133: 
1.659     raeburn  6134:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6135:   Allows for - starting a grading run.
1.424     albertel 6136:              - downloading existing scan data (original, corrected
1.423     albertel 6137:                                                 or skipped info)
                   6138: 
                   6139:              - uploading new scan data
                   6140: 
                   6141:  Arguments:
                   6142:   $r          - The Apache request object
                   6143:   $file2grade - name of the file that contain the scanned data to score
                   6144: 
                   6145: =cut
1.186     albertel 6146: 
1.75      albertel 6147: sub scantron_selectphase {
1.608     www      6148:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6149:     if (!$symb) {return '';}
1.582     raeburn  6150:     my $map_error;
                   6151:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6152:     if ($map_error) {
                   6153:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6154:         return;
                   6155:     }
1.324     albertel 6156:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6157:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6158:     my $format_selector=&scantron_scantab();
1.186     albertel 6159:     my $CODE_selector=&scantron_CODElist();
                   6160:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6161:     my $result;
1.422     foxr     6162: 
1.513     foxr     6163:     $ssi_error = 0;
                   6164: 
1.770     raeburn  6165:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 6166: 
                   6167: 	# Chunk of form to prompt for a scantron file upload.
                   6168: 
                   6169:         $r->print('
1.754     raeburn  6170:     <br />');
1.606     wenzelju 6171:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6172:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  6173:     my $csec= $env{'request.course.sec'};
1.736     damieng  6174:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6175:     &js_escape(\$alertmsg);
1.754     raeburn  6176:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 6177:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   6178:     function checkUpload(formname) {
                   6179: 	if (formname.upfile.value == "") {
1.736     damieng  6180: 	    alert("'.$alertmsg.'");
1.606     wenzelju 6181: 	    return false;
                   6182: 	}
                   6183: 	formname.submit();
1.756     raeburn  6184:     }'."\n".$formatjs));
1.606     wenzelju 6185:     $r->print('
                   6186:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6187:                 '.$default_form_data.'
                   6188:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  6189:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 6190:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6191:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  6192:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6193:               '.&Apache::loncommon::start_data_table_header_row().'
                   6194:                 <th>
                   6195:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6196:                 </th>
                   6197:               '.&Apache::loncommon::end_data_table_header_row().'
                   6198:               '.&Apache::loncommon::start_data_table_row().'
                   6199:             <td>
                   6200:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6201:     if ($formatoptions) {
                   6202:         $r->print('</td>
                   6203:                  '.&Apache::loncommon::end_data_table_row().'
                   6204:                  '.&Apache::loncommon::start_data_table_row().'
                   6205:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6206:                  </td>
                   6207:                  '.&Apache::loncommon::end_data_table_row().'
                   6208:                  '.&Apache::loncommon::start_data_table_row().'
                   6209:                  <td>'
                   6210:         );
                   6211:     } else {
                   6212:         $r->print(' <br />');
                   6213:     }
                   6214:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6215:               </td>
                   6216:              '.&Apache::loncommon::end_data_table_row().'
                   6217:              '.&Apache::loncommon::end_data_table().'
                   6218:              </form>'
                   6219:     );
1.606     wenzelju 6220: 
                   6221:     }
                   6222: 
1.422     foxr     6223:     # Chunk of form to prompt for a file to grade and how:
                   6224: 
1.489     albertel 6225:     $result.= '
                   6226:     <br />
                   6227:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6228:     <input type="hidden" name="command" value="scantron_warning" />
                   6229:     '.$default_form_data.'
                   6230:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6231:        '.&Apache::loncommon::start_data_table_header_row().'
                   6232:             <th colspan="2">
1.492     albertel 6233:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6234:             </th>
                   6235:        '.&Apache::loncommon::end_data_table_header_row().'
                   6236:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6237:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6238:        '.&Apache::loncommon::end_data_table_row().'
                   6239:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6240:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6241:        '.&Apache::loncommon::end_data_table_row().'
                   6242:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6243:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6244:        '.&Apache::loncommon::end_data_table_row().'
                   6245:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6246:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6247:        '.&Apache::loncommon::end_data_table_row().'
                   6248:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6249:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6250:        '.&Apache::loncommon::end_data_table_row().'
                   6251:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6252: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6253:             <td>
1.492     albertel 6254: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6255:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6256:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6257: 	    </td>
1.489     albertel 6258:        '.&Apache::loncommon::end_data_table_row().'
                   6259:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6260:             <td colspan="2">
1.572     www      6261:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6262:             </td>
1.489     albertel 6263:        '.&Apache::loncommon::end_data_table_row().'
                   6264:     '.&Apache::loncommon::end_data_table().'
                   6265:     </form>
                   6266: ';
1.162     albertel 6267:    
                   6268:     $r->print($result);
                   6269: 
1.422     foxr     6270:     # Chunk of the form that prompts to view a scoring office file,
                   6271:     # corrected file, skipped records in a file.
                   6272: 
1.489     albertel 6273:     $r->print('
                   6274:    <br />
                   6275:    <form action="/adm/grades" name="scantron_download">
                   6276:      '.$default_form_data.'
                   6277:      <input type="hidden" name="command" value="scantron_download" />
                   6278:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6279:        '.&Apache::loncommon::start_data_table_header_row().'
                   6280:               <th>
1.492     albertel 6281:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6282:               </th>
                   6283:        '.&Apache::loncommon::end_data_table_header_row().'
                   6284:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6285:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6286:                 <br />
1.492     albertel 6287:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6288:        '.&Apache::loncommon::end_data_table_row().'
                   6289:      '.&Apache::loncommon::end_data_table().'
                   6290:    </form>
                   6291:    <br />
                   6292: ');
1.162     albertel 6293: 
1.457     banghart 6294:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6295: 
1.694     bisitz   6296:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6297:              $default_form_data."\n".
                   6298:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6299:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6300:              '<th colspan="2">
1.572     www      6301:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6302:              '</th>'."\n".
                   6303:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6304:               &Apache::loncommon::start_data_table_row()."\n".
                   6305:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6306:               '<td> '.$sequence_selector.' </td>'.
                   6307:               &Apache::loncommon::end_data_table_row()."\n".
                   6308:               &Apache::loncommon::start_data_table_row()."\n".
                   6309:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6310:               '<td> '.$file_selector.' </td>'."\n".
                   6311:               &Apache::loncommon::end_data_table_row()."\n".
                   6312:               &Apache::loncommon::start_data_table_row()."\n".
                   6313:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6314:               '<td> '.$format_selector.' </td>'."\n".
                   6315:               &Apache::loncommon::end_data_table_row()."\n".
                   6316:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6317:               '<td> '.&mt('Options').' </td>'."\n".
                   6318:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6319:               &Apache::loncommon::end_data_table_row()."\n".
                   6320:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6321:               '<td colspan="2">'."\n".
                   6322:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6323:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6324:               '</td>'."\n".
                   6325:               &Apache::loncommon::end_data_table_row()."\n".
                   6326:               &Apache::loncommon::end_data_table()."\n".
                   6327:               '</form><br />');
                   6328:     return;
1.75      albertel 6329: }
                   6330: 
1.423     albertel 6331: =pod 
                   6332: 
                   6333: =item username_to_idmap
                   6334: 
1.556     weissno  6335:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6336:     student username:domain. If a single ID occurs for more than one student,
                   6337:     the status of the student is checked, and if Active, the value in the hash
                   6338:     will be set to the Active student.
1.423     albertel 6339: 
                   6340:   Arguments:
                   6341: 
                   6342:     $classlist - reference to the class list hash. This is a hash
                   6343:                  keyed by student name:domain  whose elements are references
1.424     albertel 6344:                  to arrays containing various chunks of information
1.423     albertel 6345:                  about the student. (See loncoursedata for more info).
                   6346: 
                   6347:   Returns
                   6348:     %idmap - the constructed hash
                   6349: 
                   6350: =cut
                   6351: 
1.82      albertel 6352: sub username_to_idmap {
                   6353:     my ($classlist)= @_;
                   6354:     my %idmap;
                   6355:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6356:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6357:         unless ($id eq '') {
                   6358:             if (!exists($idmap{$id})) {
                   6359:                 $idmap{$id} = $student;
                   6360:             } else {
                   6361:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6362:                 if ($status eq 'Active') {
                   6363:                     $idmap{$id} = $student;
                   6364:                 }
                   6365:             }
                   6366:         }
1.82      albertel 6367:     }
                   6368:     return %idmap;
                   6369: }
1.423     albertel 6370: 
                   6371: =pod
                   6372: 
1.424     albertel 6373: =item scantron_fixup_scanline
1.423     albertel 6374: 
                   6375:    Process a requested correction to a scanline.
                   6376: 
                   6377:   Arguments:
1.754     raeburn  6378:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6379:     $scan_data         - hash of correction information 
                   6380:                           (see &scantron_getfile())
                   6381:     $line              - existing scanline
                   6382:     $whichline         - line number of the passed in scanline
                   6383:     $field             - type of change to process 
                   6384:                          (either 
1.573     bisitz   6385:                           'ID'     -> correct the student/employee ID
1.423     albertel 6386:                           'CODE'   -> correct the CODE
                   6387:                           'answer' -> fixup the submitted answers)
                   6388:     
                   6389:    $args               - hash of additional info,
                   6390:                           - 'ID' 
                   6391:                                'newid' -> studentID to use in replacement
1.424     albertel 6392:                                           of existing one
1.423     albertel 6393:                           - 'CODE' 
                   6394:                                'CODE_ignore_dup' - set to true if duplicates
                   6395:                                                    should be ignored.
                   6396: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6397:                                         if the existing unfound code should
1.423     albertel 6398:                                         be used as is
                   6399:                           - 'answer'
                   6400:                                'response' - new answer or 'none' if blank
                   6401:                                'question' - the bubble line to change
1.503     raeburn  6402:                                'questionnum' - the question identifier,
                   6403:                                                may include subquestion. 
1.423     albertel 6404: 
                   6405:   Returns:
                   6406:     $line - the modified scanline
                   6407: 
                   6408:   Side effects: 
                   6409:     $scan_data - may be updated
                   6410: 
                   6411: =cut
                   6412: 
1.82      albertel 6413: 
1.157     albertel 6414: sub scantron_fixup_scanline {
                   6415:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6416:     if ($field eq 'ID') {
                   6417: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6418: 	    return ($line,1,'New value too large');
1.157     albertel 6419: 	}
                   6420: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6421: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6422: 				     $args->{'newid'});
                   6423: 	}
                   6424: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6425: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6426: 	if ($args->{'newid'}=~/^\s*$/) {
                   6427: 	    &scan_data($scan_data,"$whichline.user",
                   6428: 		       $args->{'username'}.':'.$args->{'domain'});
                   6429: 	}
1.186     albertel 6430:     } elsif ($field eq 'CODE') {
1.192     albertel 6431: 	if ($args->{'CODE_ignore_dup'}) {
                   6432: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6433: 	}
                   6434: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6435: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6436: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6437: 		return ($line,1,'New CODE value too large');
                   6438: 	    }
                   6439: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6440: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6441: 	    }
                   6442: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6443: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6444: 	}
1.157     albertel 6445:     } elsif ($field eq 'answer') {
1.497     foxr     6446: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6447: 	my $off=$scantron_config->{'Qoff'};
                   6448: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6449: 	my $answer=${off}x$length;
                   6450: 	if ($args->{'response'} eq 'none') {
                   6451: 	    &scan_data($scan_data,
1.503     raeburn  6452: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6453: 	} else {
                   6454: 	    if ($on eq 'letter') {
                   6455: 		my @alphabet=('A'..'Z');
                   6456: 		$answer=$alphabet[$args->{'response'}];
                   6457: 	    } elsif ($on eq 'number') {
                   6458: 		$answer=$args->{'response'}+1;
                   6459: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6460: 	    } else {
1.497     foxr     6461: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6462: 	    }
1.497     foxr     6463: 	    &scan_data($scan_data,
1.503     raeburn  6464: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6465: 	}
1.497     foxr     6466: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6467: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6468:     }
                   6469:     return $line;
                   6470: }
1.423     albertel 6471: 
                   6472: =pod
                   6473: 
                   6474: =item scan_data
                   6475: 
                   6476:     Edit or look up  an item in the scan_data hash.
                   6477: 
                   6478:   Arguments:
                   6479:     $scan_data  - The hash (see scantron_getfile)
                   6480:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6481:                   scantronfilename_key).
1.423     albertel 6482:     $data        - New value of the hash entry.
                   6483:     $delete      - If true, the entry is removed from the hash.
                   6484: 
                   6485:   Returns:
                   6486:     The new value of the hash table field (undefined if deleted).
                   6487: 
                   6488: =cut
                   6489: 
                   6490: 
1.157     albertel 6491: sub scan_data {
                   6492:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6493:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6494:     if (defined($value)) {
                   6495: 	$scan_data->{$filename.'_'.$key} = $value;
                   6496:     }
                   6497:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6498:     return $scan_data->{$filename.'_'.$key};
                   6499: }
1.423     albertel 6500: 
1.495     albertel 6501: # ----- These first few routines are general use routines.----
                   6502: 
                   6503: # Return the number of occurences of a pattern in a string.
                   6504: 
                   6505: sub occurence_count {
                   6506:     my ($string, $pattern) = @_;
                   6507: 
                   6508:     my @matches = ($string =~ /$pattern/g);
                   6509: 
                   6510:     return scalar(@matches);
                   6511: }
                   6512: 
                   6513: 
                   6514: # Take a string known to have digits and convert all the
                   6515: # digits into letters in the range J,A..I.
                   6516: 
                   6517: sub digits_to_letters {
                   6518:     my ($input) = @_;
                   6519: 
                   6520:     my @alphabet = ('J', 'A'..'I');
                   6521: 
                   6522:     my @input    = split(//, $input);
                   6523:     my $output ='';
                   6524:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6525: 	if ($input[$i] =~ /\d/) {
                   6526: 	    $output .= $alphabet[$input[$i]];
                   6527: 	} else {
                   6528: 	    $output .= $input[$i];
                   6529: 	}
                   6530:     }
                   6531:     return $output;
                   6532: }
                   6533: 
1.423     albertel 6534: =pod 
                   6535: 
                   6536: =item scantron_parse_scanline
                   6537: 
1.711     bisitz   6538:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6539: 
                   6540:  Arguments:
1.711     bisitz   6541:     line             - The text of the bubblesheet file line to process
1.423     albertel 6542:     whichline        - Line number
1.711     bisitz   6543:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6544:     scan_data        - Hash of extra information about the scanline
                   6545:                        (see scantron_getfile for more information)
                   6546:     just_header      - True if should not process question answers but only
                   6547:                        the stuff to the left of the answers.
1.691     raeburn  6548:     randomorder      - True if randomorder in use
                   6549:     randompick       - True if randompick in use
                   6550:     sequence         - Exam folder URL
                   6551:     master_seq       - Ref to array containing symbs in exam folder
                   6552:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6553:                        (corresponding values are resource objects)
                   6554:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6555:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6556:                        are refs to an array of resource objects, ordered
                   6557:                        according to order used for CODE, when randomorder
                   6558:                        and or randompick are in use.
                   6559:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6560:                        for current line to question number used for same question
                   6561:                         in "Master Sequence" (as seen by Course Coordinator).
                   6562:     startline        - Ref to hash where key is question number (0 is first)
                   6563:                        and value is number of first bubble line for current 
                   6564:                        student or code-based randompick and/or randomorder.
                   6565:     totalref         - Ref of scalar used to score total number of bubble
                   6566:                        lines needed for responses in a scan line (used when
                   6567:                        randompick in use. 
                   6568:     
1.423     albertel 6569:  Returns:
                   6570:    Hash containing the result of parsing the scanline
                   6571: 
                   6572:    Keys are all proceeded by the string 'scantron.'
                   6573: 
                   6574:        CODE    - the CODE in use for this scanline
                   6575:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6576:                  by the operator
                   6577:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6578:                             CODEs were selected, but the usage has been
                   6579:                             forced by the operator
1.556     weissno  6580:        ID  - student/employee ID
1.423     albertel 6581:        PaperID - if used, the ID number printed on the sheet when the 
                   6582:                  paper was scanned
                   6583:        FirstName - first name from the sheet
                   6584:        LastName  - last name from the sheet
                   6585: 
                   6586:      if just_header was not true these key may also exist
                   6587: 
1.447     foxr     6588:        missingerror - a list of bubble ranges that are considered to be answers
                   6589:                       to a single question that don't have any bubbles filled in.
                   6590:                       Of the form questionnumber:firstbubblenumber:count.
                   6591:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6592:                       to a single question that have more than one bubble filled in.
                   6593:                       Of the form questionnumber::firstbubblenumber:count
                   6594:    
                   6595:                 In the above, count is the number of bubble responses in the
                   6596:                 input line needed to represent the possible answers to the question.
                   6597:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6598:                 per line would have count = 2.
                   6599: 
1.423     albertel 6600:        maxquest     - the number of the last bubble line that was parsed
                   6601: 
                   6602:        (<number> starts at 1)
                   6603:        <number>.answer - zero or more letters representing the selected
                   6604:                          letters from the scanline for the bubble line 
                   6605:                          <number>.
                   6606:                          if blank there was either no bubble or there where
                   6607:                          multiple bubbles, (consult the keys missingerror and
                   6608:                          doubleerror if this is an error condition)
                   6609: 
                   6610: =cut
                   6611: 
1.82      albertel 6612: sub scantron_parse_scanline {
1.691     raeburn  6613:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6614:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6615:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6616: 
1.82      albertel 6617:     my %record;
1.691     raeburn  6618:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6619:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6620: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6621: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6622: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6623: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6624: 	    $record{'scantron.CODE'}=substr($data,
                   6625: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6626: 					    $$scantron_config{'CODElength'});
1.191     albertel 6627: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6628: 		$record{'scantron.useCODE'}=1;
                   6629: 	    }
1.192     albertel 6630: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6631: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6632: 	    }
1.82      albertel 6633: 	} else {
                   6634: 	    #FIXME interpret first N questions
                   6635: 	}
                   6636:     }
1.83      albertel 6637:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6638: 				  $$scantron_config{'IDlength'});
1.157     albertel 6639:     $record{'scantron.PaperID'}=
                   6640: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6641: 	       $$scantron_config{'PaperIDlength'});
                   6642:     $record{'scantron.FirstName'}=
                   6643: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6644: 	       $$scantron_config{'FirstNamelength'});
                   6645:     $record{'scantron.LastName'}=
                   6646: 	substr($data,$$scantron_config{'LastName'}-1,
                   6647: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6648:     if ($just_header) { return \%record; }
1.194     albertel 6649: 
1.82      albertel 6650:     my @alphabet=('A'..'Z');
                   6651:     my $questnum=0;
1.447     foxr     6652:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6653: 
1.691     raeburn  6654:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6655:     if ($randompick || $randomorder) {
                   6656:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6657:                                          $master_seq,$symb_to_resource,
                   6658:                                          $partids_by_symb,$orderedforcode,
                   6659:                                          $respnumlookup,$startline);
                   6660:         if ($total) {
                   6661:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6662:         }
                   6663:         if (ref($totalref)) {
                   6664:             $$totalref = $total;
                   6665:         }
                   6666:     }
                   6667:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6668:     chomp($questions);		# Get rid of any trailing \n.
                   6669:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6670:     while (length($questions)) {
1.691     raeburn  6671:         my $answers_needed;
                   6672:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6673:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6674:         } else {
                   6675: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6676:         }
1.503     raeburn  6677:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6678:                              || 1;
                   6679:         $questnum++;
                   6680:         my $quest_id = $questnum;
                   6681:         my $currentquest = substr($questions,0,$answer_length);
                   6682:         $questions       = substr($questions,$answer_length);
                   6683:         if (length($currentquest) < $answer_length) { next; }
                   6684: 
1.691     raeburn  6685:         my $subdivided;
                   6686:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6687:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6688:         } else {
                   6689:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6690:         }
                   6691:         if ($subdivided =~ /,/) {
1.503     raeburn  6692:             my $subquestnum = 1;
                   6693:             my $subquestions = $currentquest;
1.691     raeburn  6694:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6695:             foreach my $subans (@subanswers_needed) {
                   6696:                 my $subans_length =
                   6697:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6698:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6699:                 $subquestions   = substr($subquestions,$subans_length);
                   6700:                 $quest_id = "$questnum.$subquestnum";
                   6701:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6702:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6703:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6704:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6705:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6706:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6707:                 } else {
                   6708:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6709:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6710:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6711:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6712:                 }
                   6713:                 $subquestnum ++;
                   6714:             }
                   6715:         } else {
                   6716:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6717:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6718:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6719:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6720:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6721:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6722:             } else {
                   6723:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6724:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6725:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6726:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6727:             }
                   6728:         }
                   6729:     }
                   6730:     $record{'scantron.maxquest'}=$questnum;
                   6731:     return \%record;
                   6732: }
1.447     foxr     6733: 
1.691     raeburn  6734: sub get_master_seq {
                   6735:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6736:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6737:                    (ref($symb_to_resource) eq 'HASH'));
                   6738:     my $resource_error;
                   6739:     foreach my $resource (@{$resources}) {
                   6740:         my $ressymb;
                   6741:         if (ref($resource)) {
                   6742:             $ressymb = $resource->symb();
                   6743:             push(@{$master_seq},$ressymb);
                   6744:             $symb_to_resource->{$ressymb} = $resource;
                   6745:         } else {
                   6746:             $resource_error = 1;
                   6747:             last;
                   6748:         }
                   6749:     }
                   6750:     return $resource_error;
                   6751: }
                   6752: 
                   6753: sub get_respnum_lookups {
                   6754:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6755:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6756:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6757:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6758:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6759:                    (ref($startline) eq 'HASH'));
                   6760:     my ($user,$scancode);
                   6761:     if ((exists($record->{'scantron.CODE'})) &&
                   6762:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6763:         $scancode = $record->{'scantron.CODE'};
                   6764:     } else {
                   6765:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6766:     }
                   6767:     my @mapresources =
                   6768:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6769:                      $orderedforcode);
                   6770:     my $total = 0;
                   6771:     my $count = 0;
                   6772:     foreach my $resource (@mapresources) {
                   6773:         my $id = $resource->id();
                   6774:         my $symb = $resource->symb();
                   6775:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6776:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6777:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6778:                 if ($respnum ne '') {
                   6779:                     $respnumlookup->{$count} = $respnum;
                   6780:                     $startline->{$count} = $total;
                   6781:                     $total += $bubble_lines_per_response{$respnum};
                   6782:                     $count ++;
                   6783:                 }
                   6784:             }
                   6785:         }
                   6786:     }
                   6787:     return $total;
                   6788: }
                   6789: 
1.503     raeburn  6790: sub scantron_validator_lettnum {
                   6791:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6792:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6793:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6794: 
                   6795:     # Qon 'letter' implies for each slot in currquest we have:
                   6796:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6797:     #    about anything else (esp. a value of Qoff) for missing
                   6798:     #    bubbles.
                   6799:     #
                   6800:     # Qon 'number' implies each slot gives a digit that indexes the
                   6801:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6802:     #    and * or ? for double bubbles on a single line.
                   6803:     #
1.447     foxr     6804: 
1.503     raeburn  6805:     my $matchon;
                   6806:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6807:         $matchon = '[A-Z]';
                   6808:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6809:         $matchon = '\d';
                   6810:     }
                   6811:     my $occurrences = 0;
1.691     raeburn  6812:     my $responsenum = $questnum-1;
                   6813:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6814:        $responsenum = $respnumlookup->{$questnum-1} 
                   6815:     }
                   6816:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6817:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6818:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6819:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6820:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6821:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6822:         my @singlelines = split('',$currquest);
                   6823:         foreach my $entry (@singlelines) {
                   6824:             $occurrences = &occurence_count($entry,$matchon);
                   6825:             if ($occurrences > 1) {
                   6826:                 last;
                   6827:             }
1.691     raeburn  6828:         }
1.503     raeburn  6829:     } else {
                   6830:         $occurrences = &occurence_count($currquest,$matchon); 
                   6831:     }
                   6832:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6833:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6834:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6835:             my $bubble = substr($currquest,$ans,1);
                   6836:             if ($bubble =~ /$matchon/ ) {
                   6837:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6838:                     if ($bubble == 0) {
                   6839:                         $bubble = 10; 
                   6840:                     }
                   6841:                     $record->{"scantron.$ansnum.answer"} = 
                   6842:                         $alphabet->[$bubble-1];
                   6843:                 } else {
                   6844:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6845:                 }
                   6846:             } else {
                   6847:                 $record->{"scantron.$ansnum.answer"}='';
                   6848:             }
                   6849:             $ansnum++;
                   6850:         }
                   6851:     } elsif (!defined($currquest)
                   6852:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6853:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6854:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6855:             $record->{"scantron.$ansnum.answer"}='';
                   6856:             $ansnum++;
                   6857:         }
                   6858:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6859:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6860:         }
                   6861:     } else {
                   6862:         if ($$scantron_config{'Qon'} eq 'number') {
                   6863:             $currquest = &digits_to_letters($currquest);            
                   6864:         }
                   6865:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6866:             my $bubble = substr($currquest,$ans,1);
                   6867:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6868:             $ansnum++;
                   6869:         }
                   6870:     }
                   6871:     return $ansnum;
                   6872: }
1.447     foxr     6873: 
1.503     raeburn  6874: sub scantron_validator_positional {
                   6875:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6876:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6877:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6878: 
1.503     raeburn  6879:     # Otherwise there's a positional notation;
                   6880:     # each bubble line requires Qlength items, and there are filled in
                   6881:     # bubbles for each case where there 'Qon' characters.
                   6882:     #
1.447     foxr     6883: 
1.503     raeburn  6884:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6885: 
1.503     raeburn  6886:     # If the split only gives us one element.. the full length of the
                   6887:     # answer string, no bubbles are filled in:
1.447     foxr     6888: 
1.507     raeburn  6889:     if ($answers_needed eq '') {
                   6890:         return;
                   6891:     }
                   6892: 
1.503     raeburn  6893:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6894:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6895:             $record->{"scantron.$ansnum.answer"}='';
                   6896:             $ansnum++;
                   6897:         }
                   6898:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6899:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6900:         }
                   6901:     } elsif (scalar(@array) == 2) {
                   6902:         my $location = length($array[0]);
                   6903:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6904:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6905:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6906:             if ($ans eq $line_num) {
                   6907:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6908:             } else {
                   6909:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6910:             }
                   6911:             $ansnum++;
                   6912:          }
                   6913:     } else {
                   6914:         #  If there's more than one instance of a bubble character
                   6915:         #  That's a double bubble; with positional notation we can
                   6916:         #  record all the bubbles filled in as well as the
                   6917:         #  fact this response consists of multiple bubbles.
                   6918:         #
1.691     raeburn  6919:         my $responsenum = $questnum-1;
                   6920:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6921:             $responsenum = $respnumlookup->{$questnum-1}
                   6922:         }
                   6923:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6924:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6925:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6926:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6927:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6928:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6929:             my $doubleerror = 0;
                   6930:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6931:                    (!$doubleerror)) {
                   6932:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6933:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6934:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6935:                if (length(@currarray) > 2) {
                   6936:                    $doubleerror = 1;
                   6937:                } 
                   6938:             }
                   6939:             if ($doubleerror) {
                   6940:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6941:             }
                   6942:         } else {
                   6943:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6944:         }
                   6945:         my $item = $ansnum;
                   6946:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6947:             $record->{"scantron.$item.answer"} = '';
                   6948:             $item ++;
                   6949:         }
1.447     foxr     6950: 
1.503     raeburn  6951:         my @ans=@array;
                   6952:         my $i=0;
                   6953:         my $increment = 0;
                   6954:         while ($#ans) {
                   6955:             $i+=length($ans[0]) + $increment;
                   6956:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6957:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6958:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6959:             shift(@ans);
                   6960:             $increment = 1;
                   6961:         }
                   6962:         $ansnum += $answers_needed;
1.82      albertel 6963:     }
1.503     raeburn  6964:     return $ansnum;
1.82      albertel 6965: }
                   6966: 
1.423     albertel 6967: =pod
                   6968: 
                   6969: =item scantron_add_delay
                   6970: 
                   6971:    Adds an error message that occurred during the grading phase to a
                   6972:    queue of messages to be shown after grading pass is complete
                   6973: 
                   6974:  Arguments:
1.424     albertel 6975:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6976:    $scanline    - the scanline that caused the error
                   6977:    $errormesage - the error message
                   6978:    $errorcode   - a numeric code for the error
                   6979: 
                   6980:  Side Effects:
1.424     albertel 6981:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6982: 
                   6983: =cut
                   6984: 
1.82      albertel 6985: sub scantron_add_delay {
1.140     albertel 6986:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6987:     push(@$delayqueue,
                   6988: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6989: 	  'ecode' => $errorcode }
                   6990: 	 );
1.82      albertel 6991: }
                   6992: 
1.423     albertel 6993: =pod
                   6994: 
                   6995: =item scantron_find_student
                   6996: 
1.424     albertel 6997:    Finds the username for the current scanline
                   6998: 
                   6999:   Arguments:
                   7000:    $scantron_record - hash result from scantron_parse_scanline
                   7001:    $scan_data       - hash of correction information 
                   7002:                       (see &scantron_getfile() form more information)
                   7003:    $idmap           - hash from &username_to_idmap()
                   7004:    $line            - number of current scanline
                   7005:  
                   7006:   Returns:
                   7007:    Either 'username:domain' or undef if unknown
                   7008: 
1.423     albertel 7009: =cut
                   7010: 
1.82      albertel 7011: sub scantron_find_student {
1.157     albertel 7012:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 7013:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 7014:     if ($scanID =~ /^\s*$/) {
                   7015:  	return &scan_data($scan_data,"$line.user");
                   7016:     }
1.83      albertel 7017:     foreach my $id (keys(%$idmap)) {
1.157     albertel 7018:  	if (lc($id) eq lc($scanID)) {
                   7019:  	    return $$idmap{$id};
                   7020:  	}
1.83      albertel 7021:     }
                   7022:     return undef;
                   7023: }
                   7024: 
1.423     albertel 7025: =pod
                   7026: 
                   7027: =item scantron_filter
                   7028: 
1.424     albertel 7029:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   7030:    hidden resources was selected
                   7031: 
1.423     albertel 7032: =cut
                   7033: 
1.83      albertel 7034: sub scantron_filter {
                   7035:     my ($curres)=@_;
1.331     albertel 7036: 
                   7037:     if (ref($curres) && $curres->is_problem()) {
                   7038: 	# if the user has asked to not have either hidden
                   7039: 	# or 'randomout' controlled resources to be graded
                   7040: 	# don't include them
                   7041: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7042: 	    && $curres->randomout) {
                   7043: 	    return 0;
                   7044: 	}
1.83      albertel 7045: 	return 1;
                   7046:     }
                   7047:     return 0;
1.82      albertel 7048: }
                   7049: 
1.423     albertel 7050: =pod
                   7051: 
                   7052: =item scantron_process_corrections
                   7053: 
1.424     albertel 7054:    Gets correction information out of submitted form data and corrects
                   7055:    the scanline
                   7056: 
1.423     albertel 7057: =cut
                   7058: 
1.157     albertel 7059: sub scantron_process_corrections {
                   7060:     my ($r) = @_;
1.754     raeburn  7061:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7062:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7063:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 7064:     my $which=$env{'form.scantron_line'};
1.200     albertel 7065:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 7066:     my ($skip,$err,$errmsg);
1.257     albertel 7067:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 7068: 	$skip=1;
1.257     albertel 7069:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   7070: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   7071: 	    $env{'form.scantron_domain'};
1.157     albertel 7072: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   7073: 	($line,$err,$errmsg)=
                   7074: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   7075: 				     'ID',{'newid'=>$newid,
1.257     albertel 7076: 				    'username'=>$env{'form.scantron_username'},
                   7077: 				    'domain'=>$env{'form.scantron_domain'}});
                   7078:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   7079: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 7080: 	my $newCODE;
1.192     albertel 7081: 	my %args;
1.190     albertel 7082: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 7083: 	    $newCODE='use_unfound';
1.190     albertel 7084: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 7085: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 7086: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 7087: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 7088: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 7089: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 7090: 	}
1.257     albertel 7091: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 7092: 	    $args{'CODE_ignore_dup'}=1;
                   7093: 	}
                   7094: 	$args{'CODE'}=$newCODE;
1.186     albertel 7095: 	($line,$err,$errmsg)=
                   7096: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7097: 				     'CODE',\%args);
1.257     albertel 7098:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7099: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7100: 	    ($line,$err,$errmsg)=
                   7101: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7102: 					 $which,'answer',
                   7103: 					 { 'question'=>$question,
1.503     raeburn  7104: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7105:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7106: 	    if ($err) { last; }
                   7107: 	}
                   7108:     }
                   7109:     if ($err) {
1.703     bisitz   7110:         $r->print(
                   7111:             '<p class="LC_error">'
                   7112:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7113:                 $errmsg)
1.704     raeburn  7114:            .'</p>');
1.157     albertel 7115:     } else {
1.200     albertel 7116: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7117: 	&scantron_putfile($scanlines,$scan_data);
                   7118:     }
                   7119: }
                   7120: 
1.423     albertel 7121: =pod
                   7122: 
                   7123: =item reset_skipping_status
                   7124: 
1.424     albertel 7125:    Forgets the current set of remember skipped scanlines (and thus
                   7126:    reverts back to considering all lines in the
                   7127:    scantron_skipped_<filename> file)
                   7128: 
1.423     albertel 7129: =cut
                   7130: 
1.200     albertel 7131: sub reset_skipping_status {
                   7132:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7133:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7134:     &scantron_putfile(undef,$scan_data);
                   7135: }
                   7136: 
1.423     albertel 7137: =pod
                   7138: 
                   7139: =item start_skipping
                   7140: 
1.424     albertel 7141:    Marks a scanline to be skipped. 
                   7142: 
1.423     albertel 7143: =cut
                   7144: 
1.376     albertel 7145: sub start_skipping {
1.200     albertel 7146:     my ($scan_data,$i)=@_;
                   7147:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7148:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7149: 	$remembered{$i}=2;
                   7150:     } else {
                   7151: 	$remembered{$i}=1;
                   7152:     }
1.200     albertel 7153:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7154: }
                   7155: 
1.423     albertel 7156: =pod
                   7157: 
                   7158: =item should_be_skipped
                   7159: 
1.424     albertel 7160:    Checks whether a scanline should be skipped.
                   7161: 
1.423     albertel 7162: =cut
                   7163: 
1.200     albertel 7164: sub should_be_skipped {
1.376     albertel 7165:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7166:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7167: 	# not redoing old skips
1.376     albertel 7168: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7169: 	return 0;
                   7170:     }
                   7171:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7172: 
                   7173:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7174: 	return 0;
                   7175:     }
1.200     albertel 7176:     return 1;
                   7177: }
                   7178: 
1.423     albertel 7179: =pod
                   7180: 
                   7181: =item remember_current_skipped
                   7182: 
1.424     albertel 7183:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7184:    file and remembers them into scan_data for later use.
                   7185: 
1.423     albertel 7186: =cut
                   7187: 
1.200     albertel 7188: sub remember_current_skipped {
                   7189:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7190:     my %to_remember;
                   7191:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7192: 	if ($scanlines->{'skipped'}[$i]) {
                   7193: 	    $to_remember{$i}=1;
                   7194: 	}
                   7195:     }
1.376     albertel 7196: 
1.200     albertel 7197:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7198:     &scantron_putfile(undef,$scan_data);
                   7199: }
                   7200: 
1.423     albertel 7201: =pod
                   7202: 
                   7203: =item check_for_error
                   7204: 
1.424     albertel 7205:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  7206:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7207:     something went wrong.
                   7208: 
1.423     albertel 7209: =cut
                   7210: 
1.200     albertel 7211: sub check_for_error {
                   7212:     my ($r,$result)=@_;
                   7213:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7214: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7215:     }
                   7216: }
1.157     albertel 7217: 
1.423     albertel 7218: =pod
                   7219: 
                   7220: =item scantron_warning_screen
                   7221: 
1.424     albertel 7222:    Interstitial screen to make sure the operator has selected the
                   7223:    correct options before we start the validation phase.
                   7224: 
1.423     albertel 7225: =cut
                   7226: 
1.203     albertel 7227: sub scantron_warning_screen {
1.650     raeburn  7228:     my ($button_text,$symb)=@_;
1.257     albertel 7229:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  7230:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7231:     my $CODElist;
1.284     albertel 7232:     if ($scantron_config{'CODElocation'} &&
                   7233: 	$scantron_config{'CODEstart'} &&
                   7234: 	$scantron_config{'CODElength'}) {
                   7235: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   7236: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7237: 	$CODElist=
1.492     albertel 7238: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7239: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7240:     }
1.663     raeburn  7241:     my $lastbubblepoints;
                   7242:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7243:         $lastbubblepoints =
                   7244:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7245:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7246:     }
1.770     raeburn  7247:     return '
1.203     albertel 7248: <p>
1.492     albertel 7249: <span class="LC_warning">
1.705     raeburn  7250: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7251: </p>
                   7252: <table>
1.492     albertel 7253: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7254: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  7255: '.$CODElist.$lastbubblepoints.'
1.203     albertel 7256: </table>
1.680     raeburn  7257: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  7258: '.&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  7259: ';
1.203     albertel 7260: }
                   7261: 
1.423     albertel 7262: =pod
                   7263: 
                   7264: =item scantron_do_warning
                   7265: 
1.424     albertel 7266:    Check if the operator has picked something for all required
                   7267:    fields. Error out if something is missing.
                   7268: 
1.423     albertel 7269: =cut
                   7270: 
1.203     albertel 7271: sub scantron_do_warning {
1.608     www      7272:     my ($r,$symb)=@_;
1.203     albertel 7273:     if (!$symb) {return '';}
1.324     albertel 7274:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7275:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7276:     if ( $env{'form.selectpage'} eq '' ||
                   7277: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7278: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7279: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7280: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7281: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7282: 	} 
1.257     albertel 7283: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7284: 	    $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  7285: 	}
1.257     albertel 7286: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7287: 	    $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  7288: 	}
1.237     albertel 7289:     } else {
1.650     raeburn  7290: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  7291:         my ($checksec,@possibles) = &gradable_sections();
                   7292:         my $gradesections;
                   7293:         if ($checksec) {
                   7294:             my $file=$env{'form.scantron_selectfile'};
                   7295:             if (&valid_file($file)) {
                   7296:                 my %bysec = &scantron_get_sections();
                   7297:                 my $table;
                   7298:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   7299:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   7300:                     $table = &Apache::loncommon::start_data_table()."\n".
                   7301:                              &Apache::loncommon::start_data_table_header_row().
                   7302:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   7303:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   7304:                     if ($bysec{'none'}) {
                   7305:                         $table .= &Apache::loncommon::start_data_table_row().
                   7306:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   7307:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7308:                     }
                   7309:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   7310:                         next if ($sec eq 'none');
                   7311:                         $table .= &Apache::loncommon::start_data_table_row().
                   7312:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   7313:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7314:                     }
                   7315:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   7316:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   7317:                                       '<p>'.$table.'</p>';
                   7318:                     if (@possibles) {
                   7319:                         $gradesections .= '<p>'.
                   7320:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   7321:                                               scalar(@possibles)).'<br />'.
                   7322:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   7323:                                               '<i>'.$checksec.'</i>').' ';
                   7324:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   7325:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   7326:                         }
                   7327:                         $gradesections .= '</p>';
                   7328:                     }
                   7329:                 }
                   7330:             } else {
                   7331:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   7332:             }
                   7333:         }
1.663     raeburn  7334:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7335: 	$r->print('
1.770     raeburn  7336: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 7337: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7338: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7339: ');
1.237     albertel 7340:     }
1.614     www      7341:     $r->print("</form><br />");
1.203     albertel 7342:     return '';
                   7343: }
                   7344: 
1.423     albertel 7345: =pod
                   7346: 
                   7347: =item scantron_form_start
                   7348: 
1.424     albertel 7349:     html hidden input for remembering all selected grading options
                   7350: 
1.423     albertel 7351: =cut
                   7352: 
1.203     albertel 7353: sub scantron_form_start {
                   7354:     my ($max_bubble)=@_;
                   7355:     my $result= <<SCANTRONFORM;
                   7356: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7357:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7358:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7359:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7360:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7361:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7362:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7363:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7364:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7365:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7366: SCANTRONFORM
1.447     foxr     7367: 
                   7368:   my $line = 0;
                   7369:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7370:        my $chunk =
                   7371: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7372:        $chunk .=
                   7373: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7374:        $chunk .= 
                   7375:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7376:        $chunk .=
                   7377:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7378:        $chunk .=
                   7379:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7380:        $result .= $chunk;
                   7381:        $line++;
1.691     raeburn  7382:     }
1.203     albertel 7383:     return $result;
                   7384: }
                   7385: 
1.423     albertel 7386: =pod
                   7387: 
                   7388: =item scantron_validate_file
                   7389: 
1.659     raeburn  7390:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7391: 
                   7392:     Also processes any necessary information resets that need to
                   7393:     occur before validation begins (ignore previous corrections,
                   7394:     restarting the skipped records processing)
                   7395: 
1.423     albertel 7396: =cut
                   7397: 
1.157     albertel 7398: sub scantron_validate_file {
1.608     www      7399:     my ($r,$symb) = @_;
1.157     albertel 7400:     if (!$symb) {return '';}
1.324     albertel 7401:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7402:     
1.703     bisitz   7403:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7404:     # them when doing the corrections reset
1.257     albertel 7405:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7406: 	&reset_skipping_status();
                   7407:     }
1.257     albertel 7408:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7409: 	&remember_current_skipped();
1.257     albertel 7410: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7411:     }
                   7412: 
1.257     albertel 7413:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7414: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7415: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7416: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7417: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7418:     }
1.200     albertel 7419: 
1.257     albertel 7420:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7421: 	&scantron_process_corrections($r);
                   7422:     }
1.770     raeburn  7423: 
                   7424:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   7425:     my ($checksec,@gradable);
                   7426:     if ($env{'request.course.sec'}) {
                   7427:         ($checksec,my @possibles) = &gradable_sections();
                   7428:         if ($checksec) {
                   7429:             if (@possibles) {
                   7430:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   7431:                 if (@chosensecs) {
                   7432:                     foreach my $sec (@chosensecs) {
                   7433:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   7434:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   7435:                                 push(@gradable,$sec);
                   7436:                             }
                   7437:                         }
                   7438:                     }
                   7439:                 }
                   7440:             }
                   7441:             $r->print('<p><table>');
                   7442:             if (@gradable) {
                   7443:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   7444:                 $r->print(
                   7445:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   7446:             } else {
                   7447:                 $r->print(
                   7448:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   7449:             }
                   7450:             $r->print('</table></p>');
                   7451:         }
                   7452:     }
                   7453:     $r->rflush();
                   7454: 
1.157     albertel 7455:     #get the student pick code ready
                   7456:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7457:     my $nav_error;
1.754     raeburn  7458:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7459:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7460:     if ($nav_error) {
                   7461:         $r->print(&navmap_errormsg());
                   7462:         return '';
                   7463:     }
1.203     albertel 7464:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7465:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7466:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7467:     }
1.157     albertel 7468:     $r->print($result);
                   7469:     
1.334     albertel 7470:     my @validate_phases=( 'sequence',
                   7471: 			  'ID',
1.157     albertel 7472: 			  'CODE',
                   7473: 			  'doublebubble',
                   7474: 			  'missingbubbles');
1.257     albertel 7475:     if (!$env{'form.validatepass'}) {
                   7476: 	$env{'form.validatepass'} = 0;
1.157     albertel 7477:     }
1.257     albertel 7478:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  7479:     my %skipbysec=();
1.448     foxr     7480: 
1.157     albertel 7481:     my $stop=0;
                   7482:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7483: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7484: 	$r->rflush();
1.691     raeburn  7485:      
1.157     albertel 7486: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7487: 	{
                   7488: 	    no strict 'refs';
1.770     raeburn  7489:             my @extras=();
                   7490:             if ($validate_phases[$currentphase] eq 'ID') {
                   7491:                 @extras = (\%skipbysec,$checksec,@gradable);
                   7492:             }
                   7493: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 7494: 	}
                   7495:     }
                   7496:     if (!$stop) {
1.650     raeburn  7497: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  7498:         my $secinfo;
                   7499:         if (keys(%skipbysec) > 0) {
                   7500:             my $seclist = '<ul>';
                   7501:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   7502:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   7503:             }
                   7504:             $seclist .= '</ul>';
                   7505:             $secinfo = '<p class="LC_info">'.
                   7506:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   7507:                            $seclist).
                   7508:                        '</p>';
                   7509:         }
1.542     raeburn  7510: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  7511:                   $secinfo.$warning.
1.542     raeburn  7512:                   &mt('Perform verification for each student after storage of submissions?').
                   7513:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7514:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7515:                   ('&nbsp;'x3).'<label>'.
                   7516:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7517:                   '</label></span><br />'.
                   7518:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7519:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7520:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7521:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7522:     } else {
                   7523: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7524: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7525:     }
                   7526:     if ($stop) {
1.334     albertel 7527: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7528: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7529: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7530: 
1.650     raeburn  7531: 	    $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 7532: 	} else {
1.503     raeburn  7533:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7534: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7535:             } else {
1.539     riegler  7536:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7537:             }
1.492     albertel 7538: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7539: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7540: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7541: 	}
1.157     albertel 7542:     }
1.614     www      7543:     $r->print(" </form><br />");
1.157     albertel 7544:     return '';
                   7545: }
                   7546: 
1.423     albertel 7547: 
                   7548: =pod
                   7549: 
                   7550: =item scantron_remove_file
                   7551: 
1.659     raeburn  7552:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7553:    scantron_original_<filename> is never removed
                   7554: 
                   7555: 
1.423     albertel 7556: =cut
                   7557: 
1.200     albertel 7558: sub scantron_remove_file {
1.192     albertel 7559:     my ($which)=@_;
1.257     albertel 7560:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7561:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7562:     my $file='scantron_';
1.200     albertel 7563:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7564: 	$file.=$which.'_';
1.192     albertel 7565:     } else {
                   7566: 	return 'refused';
                   7567:     }
1.257     albertel 7568:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7569:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7570: }
                   7571: 
1.423     albertel 7572: 
                   7573: =pod
                   7574: 
                   7575: =item scantron_remove_scan_data
                   7576: 
1.659     raeburn  7577:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7578:    data file.  (In the case that both the are doing skipped records we need
                   7579:    to remember the old skipped lines for the time being so that element
                   7580:    persists for a while.)
                   7581: 
1.423     albertel 7582: =cut
                   7583: 
1.200     albertel 7584: sub scantron_remove_scan_data {
1.257     albertel 7585:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7586:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7587:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7588:     my @todelete;
1.257     albertel 7589:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7590:     foreach my $key (@keys) {
                   7591: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7592: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7593: 		$key=~/remember_skipping/) {
                   7594: 		next;
                   7595: 	    }
1.192     albertel 7596: 	    push(@todelete,$key);
                   7597: 	}
                   7598:     }
1.200     albertel 7599:     my $result;
1.192     albertel 7600:     if (@todelete) {
1.491     albertel 7601: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7602: 				       \@todelete,$cdom,$cname);
                   7603:     } else {
                   7604: 	$result = 'ok';
1.192     albertel 7605:     }
                   7606:     return $result;
                   7607: }
                   7608: 
1.423     albertel 7609: 
                   7610: =pod
                   7611: 
                   7612: =item scantron_getfile
                   7613: 
1.659     raeburn  7614:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7615:     the scan_data hash
                   7616:   
                   7617:   Arguments:
                   7618:     None
                   7619: 
                   7620:   Returns:
                   7621:     2 hash references
                   7622: 
                   7623:      - first one has 
                   7624:          orig      -
                   7625:          corrected -
                   7626:          skipped   -  each of which points to an array ref of the specified
                   7627:                       file broken up into individual lines
                   7628:          count     - number of scanlines
                   7629:  
                   7630:      - second is the scan_data hash possible keys are
1.425     albertel 7631:        ($number refers to scanline numbered $number and thus the key affects
                   7632:         only that scanline
                   7633:         $bubline refers to the specific bubble line element and the aspects
                   7634:         refers to that specific bubble line element)
                   7635: 
                   7636:        $number.user - username:domain to use
                   7637:        $number.CODE_ignore_dup 
                   7638:                     - ignore the duplicate CODE error 
                   7639:        $number.useCODE
                   7640:                     - use the CODE in the scanline as is
                   7641:        $number.no_bubble.$bubline
                   7642:                     - it is valid that there is no bubbled in bubble
                   7643:                       at $number $bubline
                   7644:        remember_skipping
                   7645:                     - a frozen hash containing keys of $number and values
                   7646:                       of either 
                   7647:                         1 - we are on a 'do skipped records pass' and plan
                   7648:                             on processing this line
                   7649:                         2 - we are on a 'do skipped records pass' and this
                   7650:                             scanline has been marked to skip yet again
1.424     albertel 7651: 
1.423     albertel 7652: =cut
                   7653: 
1.157     albertel 7654: sub scantron_getfile {
1.200     albertel 7655:     #FIXME really would prefer a scantron directory
1.257     albertel 7656:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7657:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7658:     my $lines;
                   7659:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7660: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7661:     my %scanlines;
                   7662:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7663:     my $temp=$scanlines{'orig'};
                   7664:     $scanlines{'count'}=$#$temp;
                   7665: 
                   7666:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7667: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7668:     if ($lines eq '-1') {
                   7669: 	$scanlines{'corrected'}=[];
                   7670:     } else {
                   7671: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7672:     }
                   7673:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7674: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7675:     if ($lines eq '-1') {
                   7676: 	$scanlines{'skipped'}=[];
                   7677:     } else {
                   7678: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7679:     }
1.175     albertel 7680:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7681:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7682:     my %scan_data = @tmp;
                   7683:     return (\%scanlines,\%scan_data);
                   7684: }
                   7685: 
1.423     albertel 7686: =pod
                   7687: 
                   7688: =item lonnet_putfile
                   7689: 
1.424     albertel 7690:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7691: 
                   7692:  Arguments:
                   7693:    $contents - data to store
                   7694:    $filename - filename to store $contents into
                   7695: 
                   7696:  Returns:
                   7697:    result value from &Apache::lonnet::finishuserfileupload
                   7698: 
1.423     albertel 7699: =cut
                   7700: 
1.157     albertel 7701: sub lonnet_putfile {
                   7702:     my ($contents,$filename)=@_;
1.257     albertel 7703:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7704:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7705:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7706:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7707: 
                   7708: }
                   7709: 
1.423     albertel 7710: =pod
                   7711: 
                   7712: =item scantron_putfile
                   7713: 
1.659     raeburn  7714:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7715:     scan_data hash. (Does not modify the original version only the
                   7716:     corrected and skipped versions.
                   7717: 
                   7718:  Arguments:
                   7719:     $scanlines - hash ref that looks like the first return value from
                   7720:                  &scantron_getfile()
                   7721:     $scan_data - hash ref that looks like the second return value from
                   7722:                  &scantron_getfile()
                   7723: 
1.423     albertel 7724: =cut
                   7725: 
1.157     albertel 7726: sub scantron_putfile {
                   7727:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7728:     #FIXME really would prefer a scantron directory
1.257     albertel 7729:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7730:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7731:     if ($scanlines) {
                   7732: 	my $prefix='scantron_';
1.157     albertel 7733: # no need to update orig, shouldn't change
                   7734: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7735: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7736: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7737: 			$prefix.'corrected_'.
1.257     albertel 7738: 			$env{'form.scantron_selectfile'});
1.200     albertel 7739: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7740: 			$prefix.'skipped_'.
1.257     albertel 7741: 			$env{'form.scantron_selectfile'});
1.200     albertel 7742:     }
1.175     albertel 7743:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7744: }
                   7745: 
1.423     albertel 7746: =pod
                   7747: 
                   7748: =item scantron_get_line
                   7749: 
1.424     albertel 7750:    Returns the correct version of the scanline
                   7751: 
                   7752:  Arguments:
                   7753:     $scanlines - hash ref that looks like the first return value from
                   7754:                  &scantron_getfile()
                   7755:     $scan_data - hash ref that looks like the second return value from
                   7756:                  &scantron_getfile()
                   7757:     $i         - number of the requested line (starts at 0)
                   7758: 
                   7759:  Returns:
                   7760:    A scanline, (either the original or the corrected one if it
                   7761:    exists), or undef if the requested scanline should be
                   7762:    skipped. (Either because it's an skipped scanline, or it's an
                   7763:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7764:    pass.
                   7765: 
1.423     albertel 7766: =cut
                   7767: 
1.157     albertel 7768: sub scantron_get_line {
1.200     albertel 7769:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7770:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7771:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7772:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7773:     return $scanlines->{'orig'}[$i]; 
                   7774: }
                   7775: 
1.423     albertel 7776: =pod
                   7777: 
                   7778: =item scantron_todo_count
                   7779: 
1.424     albertel 7780:     Counts the number of scanlines that need processing.
                   7781: 
                   7782:  Arguments:
                   7783:     $scanlines - hash ref that looks like the first return value from
                   7784:                  &scantron_getfile()
                   7785:     $scan_data - hash ref that looks like the second return value from
                   7786:                  &scantron_getfile()
                   7787: 
                   7788:  Returns:
                   7789:     $count - number of scanlines to process
                   7790: 
1.423     albertel 7791: =cut
                   7792: 
1.200     albertel 7793: sub get_todo_count {
                   7794:     my ($scanlines,$scan_data)=@_;
                   7795:     my $count=0;
                   7796:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7797: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7798: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7799: 	$count++;
                   7800:     }
                   7801:     return $count;
                   7802: }
                   7803: 
1.423     albertel 7804: =pod
                   7805: 
                   7806: =item scantron_put_line
                   7807: 
1.659     raeburn  7808:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7809:     data file.
                   7810: 
                   7811:  Arguments:
                   7812:     $scanlines - hash ref that looks like the first return value from
                   7813:                  &scantron_getfile()
                   7814:     $scan_data - hash ref that looks like the second return value from
                   7815:                  &scantron_getfile()
                   7816:     $i         - line number to update
                   7817:     $newline   - contents of the updated scanline
                   7818:     $skip      - if true make the line for skipping and update the
                   7819:                  'skipped' file
                   7820: 
1.423     albertel 7821: =cut
                   7822: 
1.157     albertel 7823: sub scantron_put_line {
1.200     albertel 7824:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7825:     if ($skip) {
                   7826: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7827: 	&start_skipping($scan_data,$i);
1.157     albertel 7828: 	return;
                   7829:     }
                   7830:     $scanlines->{'corrected'}[$i]=$newline;
                   7831: }
                   7832: 
1.423     albertel 7833: =pod
                   7834: 
                   7835: =item scantron_clear_skip
                   7836: 
1.424     albertel 7837:    Remove a line from the 'skipped' file
                   7838: 
                   7839:  Arguments:
                   7840:     $scanlines - hash ref that looks like the first return value from
                   7841:                  &scantron_getfile()
                   7842:     $scan_data - hash ref that looks like the second return value from
                   7843:                  &scantron_getfile()
                   7844:     $i         - line number to update
                   7845: 
1.423     albertel 7846: =cut
                   7847: 
1.376     albertel 7848: sub scantron_clear_skip {
                   7849:     my ($scanlines,$scan_data,$i)=@_;
                   7850:     if (exists($scanlines->{'skipped'}[$i])) {
                   7851: 	undef($scanlines->{'skipped'}[$i]);
                   7852: 	return 1;
                   7853:     }
                   7854:     return 0;
                   7855: }
                   7856: 
1.423     albertel 7857: =pod
                   7858: 
                   7859: =item scantron_filter_not_exam
                   7860: 
1.424     albertel 7861:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7862:    filter out resources that are not marked as 'exam' mode
                   7863: 
1.423     albertel 7864: =cut
                   7865: 
1.334     albertel 7866: sub scantron_filter_not_exam {
                   7867:     my ($curres)=@_;
                   7868:     
                   7869:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7870: 	# if the user has asked to not have either hidden
                   7871: 	# or 'randomout' controlled resources to be graded
                   7872: 	# don't include them
                   7873: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7874: 	    && $curres->randomout) {
                   7875: 	    return 0;
                   7876: 	}
                   7877: 	return 1;
                   7878:     }
                   7879:     return 0;
                   7880: }
                   7881: 
1.423     albertel 7882: =pod
                   7883: 
                   7884: =item scantron_validate_sequence
                   7885: 
1.424     albertel 7886:     Validates the selected sequence, checking for resource that are
                   7887:     not set to exam mode.
                   7888: 
1.423     albertel 7889: =cut
                   7890: 
1.334     albertel 7891: sub scantron_validate_sequence {
                   7892:     my ($r,$currentphase) = @_;
                   7893: 
                   7894:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7895:     unless (ref($navmap)) {
                   7896:         $r->print(&navmap_errormsg());
                   7897:         return (1,$currentphase);
                   7898:     }
1.334     albertel 7899:     my (undef,undef,$sequence)=
                   7900: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7901: 
                   7902:     my $map=$navmap->getResourceByUrl($sequence);
                   7903: 
                   7904:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7905:                                     value="ignore" />');
                   7906:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7907: 	my @resources=
                   7908: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7909: 	if (@resources) {
1.675     bisitz   7910: 	    $r->print(
                   7911:                 '<p class="LC_warning">'
                   7912:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7913:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7914:                    .' work correctly.')
                   7915:                .'</p>'
                   7916:             );
1.334     albertel 7917: 	    return (1,$currentphase);
                   7918: 	}
                   7919:     }
                   7920: 
                   7921:     return (0,$currentphase+1);
                   7922: }
                   7923: 
1.423     albertel 7924: 
                   7925: 
1.157     albertel 7926: sub scantron_validate_ID {
1.770     raeburn  7927:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 7928:     
                   7929:     #get student info
                   7930:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7931:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  7932:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 7933: 
                   7934:     #get scantron line setup
1.754     raeburn  7935:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7936:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7937: 
                   7938:     my $nav_error;
1.649     raeburn  7939:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7940:     if ($nav_error) {
                   7941:         $r->print(&navmap_errormsg());
                   7942:         return(1,$currentphase);
                   7943:     }
1.157     albertel 7944: 
                   7945:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  7946:     my $unsavedskips = 0;
1.157     albertel 7947:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7948: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7949: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7950: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7951: 						 $scan_data);
                   7952: 	my $id=$$scan_record{'scantron.ID'};
                   7953: 	my $found;
                   7954: 	foreach my $checkid (keys(%idmap)) {
                   7955: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7956: 	}
                   7957: 	if ($found) {
                   7958: 	    my $username=$idmap{$found};
1.770     raeburn  7959:             if ($checksec) {
                   7960:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   7961:                     my $stusec = $classlist->{$username}->[$secidx];
                   7962:                     if ($stusec ne $checksec) {
                   7963:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7964:                             my $skip=1;
                   7965:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7966:                             if (ref($skipbysec) eq 'HASH') {
                   7967:                                 if ($stusec eq '') {
                   7968:                                     $skipbysec->{'none'} ++;
                   7969:                                 } else {
                   7970:                                     $skipbysec->{$stusec} ++;
                   7971:                                 }
                   7972:                             }
                   7973:                             $unsavedskips ++;
                   7974:                             next;
                   7975:                         }
                   7976:                     }
                   7977:                 }
                   7978:             }
1.157     albertel 7979: 	    if ($found{'ids'}{$found}) {
                   7980: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7981: 					 $line,'duplicateID',$found);
1.770     raeburn  7982:                 if ($unsavedskips) {
                   7983:                     &scantron_putfile($scanlines,$scan_data);
                   7984:                     $unsavedskips = 0;
                   7985:                 }
1.194     albertel 7986: 		return(1,$currentphase);
1.157     albertel 7987: 	    } elsif ($found{'usernames'}{$username}) {
                   7988: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7989: 					 $line,'duplicateID',$username);
1.770     raeburn  7990:                 if ($unsavedskips) {
                   7991:                     &scantron_putfile($scanlines,$scan_data);
                   7992:                     $unsavedskips = 0;
                   7993:                 }
1.194     albertel 7994: 		return(1,$currentphase);
1.157     albertel 7995: 	    }
1.186     albertel 7996: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7997: 	    $found{'ids'}{$found}++;
                   7998: 	    $found{'usernames'}{$username}++;
                   7999: 	} else {
                   8000: 	    if ($id =~ /^\s*$/) {
1.158     albertel 8001: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  8002:                 if (($checksec && $username ne '')) {
                   8003:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   8004:                         my $stusec = $classlist->{$username}->[$secidx];
                   8005:                         if ($stusec ne $checksec) {
                   8006:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   8007:                                 my $skip=1;
                   8008:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   8009:                                 if (ref($skipbysec) eq 'HASH') {
                   8010:                                     if ($stusec eq '') {
                   8011:                                         $skipbysec->{'none'} ++;
                   8012:                                     } else {
                   8013:                                         $skipbysec->{$stusec} ++;
                   8014:                                     }
                   8015:                                 }
                   8016:                                 $unsavedskips ++;
                   8017:                                 next;
                   8018:                             }
                   8019:                         }
                   8020:                     }
                   8021: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 8022: 		    &scantron_get_correction($r,$i,$scan_record,
                   8023: 					     \%scantron_config,
                   8024: 					     $line,'duplicateID',$username);
1.770     raeburn  8025:                     if ($unsavedskips) {
                   8026:                         &scantron_putfile($scanlines,$scan_data);
                   8027:                         $unsavedskips = 0;
                   8028:                     }
1.194     albertel 8029: 		    return(1,$currentphase);
1.157     albertel 8030: 		} elsif (!defined($username)) {
                   8031: 		    &scantron_get_correction($r,$i,$scan_record,
                   8032: 					     \%scantron_config,
                   8033: 					     $line,'incorrectID');
1.770     raeburn  8034:                     if ($unsavedskips) {
                   8035:                         &scantron_putfile($scanlines,$scan_data);
                   8036:                         $unsavedskips = 0;
                   8037:                     }
1.194     albertel 8038: 		    return(1,$currentphase);
1.157     albertel 8039: 		}
                   8040: 		$found{'usernames'}{$username}++;
                   8041: 	    } else {
                   8042: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   8043: 					 $line,'incorrectID');
1.770     raeburn  8044:                 if ($unsavedskips) {
                   8045:                     &scantron_putfile($scanlines,$scan_data);
                   8046:                     $unsavedskips = 0;
                   8047:                 }
1.194     albertel 8048: 		return(1,$currentphase);
1.157     albertel 8049: 	    }
                   8050: 	}
                   8051:     }
1.770     raeburn  8052:     if ($unsavedskips) {
                   8053:         &scantron_putfile($scanlines,$scan_data);
                   8054:         $unsavedskips = 0;
                   8055:     }
1.157     albertel 8056:     return (0,$currentphase+1);
                   8057: }
                   8058: 
1.770     raeburn  8059: sub scantron_get_sections {
                   8060:     my %bysec;
                   8061:     if ($env{'form.scantron_format'} ne '') {
                   8062:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   8063:         my ($scanlines,$scan_data)=&scantron_getfile();
                   8064:         my $classlist=&Apache::loncoursedata::get_classlist();
                   8065:         my %idmap=&username_to_idmap($classlist);
                   8066:         foreach my $key (keys(%idmap)) {
                   8067:             my $lckey = lc($key);
                   8068:             $idmap{$lckey} = $idmap{$key};
                   8069:         }
                   8070:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   8071:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8072:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   8073:             if ($line=~/^[\s\cz]*$/) { next; }
                   8074:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8075:                                                      $scan_data);
                   8076:             my $id=lc($$scan_record{'scantron.ID'});
                   8077:             if (exists($idmap{$id})) {
                   8078:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   8079:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   8080:                     if ($stusec eq '') {
                   8081:                         $bysec{'none'} ++;
                   8082:                     } else {
                   8083:                         $bysec{$stusec} ++;
                   8084:                     }
                   8085:                 }
                   8086:             }
                   8087:         }
                   8088:     }
                   8089:     return %bysec;
                   8090: }
1.423     albertel 8091: 
1.157     albertel 8092: sub scantron_get_correction {
1.691     raeburn  8093:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   8094:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 8095: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 8096: #to show both the current line and the previous one and allow skipping
                   8097: #the previous one or the current one
                   8098: 
1.333     albertel 8099:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   8100:         $r->print(
                   8101:             '<p class="LC_warning">'
                   8102:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   8103:                 "<b>$error</b>",
                   8104:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   8105:            ."</p> \n");
1.157     albertel 8106:     } else {
1.658     bisitz   8107:         $r->print(
                   8108:             '<p class="LC_warning">'
                   8109:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8110:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8111:            ."</p> \n");
                   8112:     }
                   8113:     my $message =
                   8114:         '<p>'
                   8115:        .&mt('The ID on the form is [_1]',
                   8116:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8117:        .'<br />'
1.665     raeburn  8118:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   8119:             $$scan_record{'scantron.LastName'},
                   8120:             $$scan_record{'scantron.FirstName'})
                   8121:        .'</p>';
1.242     albertel 8122: 
1.157     albertel 8123:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8124:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8125:                            # Array populated for doublebubble or
                   8126:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8127:                            # to validate radio button checking   
                   8128: 
1.157     albertel 8129:     if ($error =~ /ID$/) {
1.186     albertel 8130: 	if ($error eq 'incorrectID') {
1.658     bisitz   8131:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8132: 		      "</p>\n");
1.157     albertel 8133: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   8134:             $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 8135: 	}
1.242     albertel 8136: 	$r->print($message);
1.492     albertel 8137: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8138: 	$r->print("\n<ul><li> ");
                   8139: 	#FIXME it would be nice if this sent back the user ID and
                   8140: 	#could do partial userID matches
                   8141: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8142: 				       'scantron_username','scantron_domain'));
                   8143: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   8144: 	$r->print("\n:\n".
1.257     albertel 8145: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8146: 
                   8147: 	$r->print('</li>');
1.186     albertel 8148:     } elsif ($error =~ /CODE$/) {
                   8149: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   8150: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8151: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   8152: 	    $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 8153: 	}
1.658     bisitz   8154: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   8155: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8156:                  ."</p>\n");
1.242     albertel 8157: 	$r->print($message);
1.658     bisitz   8158: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8159: 	$r->print("\n<br /> ");
1.194     albertel 8160: 	my $i=0;
1.273     albertel 8161: 	if ($error eq 'incorrectCODE' 
                   8162: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8163: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8164: 	    if ($closest > 0) {
                   8165: 		foreach my $testcode (@{$closest}) {
                   8166: 		    my $checked='';
1.569     bisitz   8167: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8168: 		    $r->print("
                   8169:    <label>
1.569     bisitz   8170:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8171:        ".&mt("Use the similar CODE [_1] instead.",
                   8172: 	    "<b><tt>".$testcode."</tt></b>")."
                   8173:     </label>
                   8174:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8175: 		    $r->print("\n<br />");
                   8176: 		    $i++;
                   8177: 		}
1.194     albertel 8178: 	    }
                   8179: 	}
1.273     albertel 8180: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8181: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8182: 	    $r->print("
                   8183:     <label>
1.569     bisitz   8184:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  8185:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8186: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8187:     </label>");
1.273     albertel 8188: 	    $r->print("\n<br />");
                   8189: 	}
1.194     albertel 8190: 
1.597     wenzelju 8191: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8192: function change_radio(field) {
1.190     albertel 8193:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8194:     var i;
                   8195:     for (i=0;i<slct.length;i++) {
                   8196:         if (slct[i].value==field) { slct[i].checked=true; }
                   8197:     }
                   8198: }
                   8199: ENDSCRIPT
1.187     albertel 8200: 	my $href="/adm/pickcode?".
1.359     www      8201: 	   "form=".&escape("scantronupload").
                   8202: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8203: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8204: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8205: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8206: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8207: 	    $r->print("
                   8208:     <label>
                   8209:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8210:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8211: 	     "<a target='_blank' href='$href'>","</a>")."
                   8212:     </label> 
1.558     bisitz   8213:     ".&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 8214: 	    $r->print("\n<br />");
                   8215: 	}
1.492     albertel 8216: 	$r->print("
                   8217:     <label>
                   8218:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8219:        ".&mt("Use [_1] as the CODE.",
                   8220: 	     "</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 8221: 	$r->print("\n<br /><br />");
1.157     albertel 8222:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   8223: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8224: 
                   8225: 	# The form field scantron_questions is acutally a list of line numbers.
                   8226: 	# represented by this form so:
                   8227: 
1.691     raeburn  8228: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8229:                                                 $respnumlookup,$startline);
1.497     foxr     8230: 
1.157     albertel 8231: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8232: 		  $line_list.'" />');
1.242     albertel 8233: 	$r->print($message);
1.492     albertel 8234: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8235: 	foreach my $question (@{$arg}) {
1.503     raeburn  8236: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8237:                                                    $scan_record, $error,
                   8238:                                                    $randomorder,$randompick,
                   8239:                                                    $respnumlookup,$startline);
1.524     raeburn  8240:             push(@lines_to_correct,@linenums);
1.157     albertel 8241: 	}
1.503     raeburn  8242:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8243:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   8244: 	$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 8245: 	$r->print($message);
1.492     albertel 8246: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8247: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8248: 
1.503     raeburn  8249: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8250: 	# a list of question numbers. Therefore:
                   8251: 	#
1.691     raeburn  8252: 
                   8253: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8254:                                                 $respnumlookup,$startline);
1.497     foxr     8255: 
1.157     albertel 8256: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8257: 		  $line_list.'" />');
1.157     albertel 8258: 	foreach my $question (@{$arg}) {
1.503     raeburn  8259: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8260:                                                    $scan_record, $error,
                   8261:                                                    $randomorder,$randompick,
                   8262:                                                    $respnumlookup,$startline);
1.524     raeburn  8263:             push(@lines_to_correct,@linenums);
1.157     albertel 8264: 	}
1.503     raeburn  8265:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8266:     } else {
                   8267: 	$r->print("\n<ul>");
                   8268:     }
                   8269:     $r->print("\n</li></ul>");
1.497     foxr     8270: }
                   8271: 
1.503     raeburn  8272: sub verify_bubbles_checked {
                   8273:     my (@ansnums) = @_;
                   8274:     my $ansnumstr = join('","',@ansnums);
                   8275:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  8276:     &js_escape(\$warning);
1.767     raeburn  8277:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8278: function verify_bubble_radio(form) {
                   8279:     var ansnumArray = new Array ("$ansnumstr");
                   8280:     var need_bubble_count = 0;
                   8281:     for (var i=0; i<ansnumArray.length; i++) {
                   8282:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8283:             var bubble_picked = 0; 
                   8284:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8285:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8286:                     bubble_picked = 1;
                   8287:                 }
                   8288:             }
                   8289:             if (bubble_picked == 0) {
                   8290:                 need_bubble_count ++;
                   8291:             }
                   8292:         }
                   8293:     }
                   8294:     if (need_bubble_count) {
                   8295:         alert("$warning");
                   8296:         return;
                   8297:     }
                   8298:     form.submit(); 
                   8299: }
                   8300: ENDSCRIPT
                   8301:     return $output;
                   8302: }
                   8303: 
1.497     foxr     8304: =pod
                   8305: 
                   8306: =item  questions_to_line_list
1.157     albertel 8307: 
1.497     foxr     8308: Converts a list of questions into a string of comma separated
                   8309: line numbers in the answer sheet used by the questions.  This is
                   8310: used to fill in the scantron_questions form field.
                   8311: 
                   8312:   Arguments:
                   8313:      questions    - Reference to an array of questions.
1.691     raeburn  8314:      randomorder  - True if randomorder in use.
                   8315:      randompick   - True if randompick in use.
                   8316:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8317:                      for current line to question number used for same question
                   8318:                      in "Master Seqence" (as seen by Course Coordinator).
                   8319:      startline    - Reference to hash where key is question number (0 is first)
                   8320:                     and key is number of first bubble line for current student
                   8321:                     or code-based randompick and/or randomorder.
1.693     raeburn  8322: 
1.497     foxr     8323: =cut
                   8324: 
                   8325: 
                   8326: sub questions_to_line_list {
1.691     raeburn  8327:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8328:     my @lines;
                   8329: 
1.503     raeburn  8330:     foreach my $item (@{$questions}) {
                   8331:         my $question = $item;
                   8332:         my ($first,$count,$last);
                   8333:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8334:             $question = $1;
                   8335:             my $subquestion = $2;
1.691     raeburn  8336:             my $responsenum = $question-1;
                   8337:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8338:                 $responsenum = $respnumlookup->{$question-1};
                   8339:                 if (ref($startline) eq 'HASH') {
                   8340:                     $first = $startline->{$question-1} + 1;
                   8341:                 }
                   8342:             } else {
                   8343:                 $first = $first_bubble_line{$responsenum} + 1;
                   8344:             }
                   8345:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8346:             my $subcount = 1;
                   8347:             while ($subcount<$subquestion) {
                   8348:                 $first += $subans[$subcount-1];
                   8349:                 $subcount ++;
                   8350:             }
                   8351:             $count = $subans[$subquestion-1];
                   8352:         } else {
1.691     raeburn  8353:             my $responsenum = $question-1;
                   8354:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8355:                 $responsenum = $respnumlookup->{$question-1};
                   8356:                 if (ref($startline) eq 'HASH') {
                   8357:                     $first = $startline->{$question-1} + 1;
                   8358:                 }
                   8359:             } else {
                   8360:                 $first = $first_bubble_line{$responsenum} + 1;
                   8361:             }
                   8362: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8363:         }
1.506     raeburn  8364:         $last = $first+$count-1;
1.503     raeburn  8365:         push(@lines, ($first..$last));
1.497     foxr     8366:     }
                   8367:     return join(',', @lines);
                   8368: }
                   8369: 
                   8370: =pod 
                   8371: 
                   8372: =item prompt_for_corrections
                   8373: 
                   8374: Prompts for a potentially multiline correction to the
                   8375: user's bubbling (factors out common code from scantron_get_correction
                   8376: for multi and missing bubble cases).
                   8377: 
                   8378:  Arguments:
                   8379:    $r           - Apache request object.
                   8380:    $question    - The question number to prompt for.
                   8381:    $scan_config - The scantron file configuration hash.
                   8382:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8383:    $error       - Type of error
1.691     raeburn  8384:    $randomorder - True if randomorder in use.
                   8385:    $randompick  - True if randompick in use.
                   8386:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8387:                     for current line to question number used for same question
                   8388:                     in "Master Seqence" (as seen by Course Coordinator).
                   8389:    $startline   - Reference to hash where key is question number (0 is first)
                   8390:                   and value is number of first bubble line for current student
                   8391:                   or code-based randompick and/or randomorder.
                   8392: 
1.497     foxr     8393: 
                   8394:  Implicit inputs:
                   8395:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8396:                                   Numbered from 0 (but question numbers are from
                   8397:                                   1.
                   8398:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8399:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8400:                                   type problems render as separate sub-questions, 
1.503     raeburn  8401:                                   in exam mode. This hash contains a 
                   8402:                                   comma-separated list of the lines per 
                   8403:                                   sub-question.
1.510     raeburn  8404:    %responsetype_per_response   - essayresponse, formularesponse,
                   8405:                                   stringresponse, imageresponse, reactionresponse,
                   8406:                                   and organicresponse type problem parts can have
1.503     raeburn  8407:                                   multiple lines per response if the weight
                   8408:                                   assigned exceeds 10.  In this case, only
                   8409:                                   one bubble per line is permitted, but more 
                   8410:                                   than one line might contain bubbles, e.g.
                   8411:                                   bubbling of: line 1 - J, line 2 - J, 
                   8412:                                   line 3 - B would assign 22 points.  
1.497     foxr     8413: 
                   8414: =cut
                   8415: 
                   8416: sub prompt_for_corrections {
1.691     raeburn  8417:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8418:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8419:     my ($current_line,$lines);
                   8420:     my @linenums;
                   8421:     my $questionnum = $question;
1.691     raeburn  8422:     my ($first,$responsenum);
1.503     raeburn  8423:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8424:         $question = $1;
                   8425:         my $subquestion = $2;
1.691     raeburn  8426:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8427:             $responsenum = $respnumlookup->{$question-1};
                   8428:             if (ref($startline) eq 'HASH') {
                   8429:                 $first = $startline->{$question-1};
                   8430:             }
                   8431:         } else {
                   8432:             $responsenum = $question-1;
1.714     raeburn  8433:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8434:         }
                   8435:         $current_line = $first + 1 ;
                   8436:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8437:         my $subcount = 1;
                   8438:         while ($subcount<$subquestion) {
                   8439:             $current_line += $subans[$subcount-1];
                   8440:             $subcount ++;
                   8441:         }
                   8442:         $lines = $subans[$subquestion-1];
                   8443:     } else {
1.691     raeburn  8444:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8445:             $responsenum = $respnumlookup->{$question-1};
                   8446:             if (ref($startline) eq 'HASH') { 
                   8447:                 $first = $startline->{$question-1};
                   8448:             }
                   8449:         } else {
                   8450:             $responsenum = $question-1;
                   8451:             $first = $first_bubble_line{$responsenum};
                   8452:         }
                   8453:         $current_line = $first + 1;
                   8454:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8455:     }
1.497     foxr     8456:     if ($lines > 1) {
1.503     raeburn  8457:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8458:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8459:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8460:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8461:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8462:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8463:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8464:             $r->print(
                   8465:                 &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)
                   8466:                .'<br /><br />'
                   8467:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8468:                .'<br />'
                   8469:                .&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.')
                   8470:                .'<br />'
                   8471:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8472:                .'<br /><br />'
                   8473:             );
1.503     raeburn  8474:         } else {
                   8475:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8476:         }
1.497     foxr     8477:     }
                   8478:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8479:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8480: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8481: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8482:         push(@linenums,$current_line);
1.497     foxr     8483: 	$current_line++;
                   8484:     }
                   8485:     if ($lines > 1) {
                   8486: 	$r->print("<hr /><br />");
                   8487:     }
1.503     raeburn  8488:     return @linenums;
1.157     albertel 8489: }
1.423     albertel 8490: 
                   8491: =pod
                   8492: 
                   8493: =item scantron_bubble_selector
                   8494:   
                   8495:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8496:    possibly showing the existing the selected bubbles if known
1.423     albertel 8497: 
                   8498:  Arguments:
                   8499:     $r           - Apache request object
1.754     raeburn  8500:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8501:     $line        - Number of the line being displayed.
1.503     raeburn  8502:     $questionnum - Question number (may include subquestion)
                   8503:     $error       - Type of error.
1.497     foxr     8504:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8505: 
                   8506: =cut
                   8507: 
1.157     albertel 8508: sub scantron_bubble_selector {
1.503     raeburn  8509:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8510:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8511: 
                   8512:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8513:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8514:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8515:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8516:             $max=$$scan_config{'BubblesPerRow'};
                   8517:             if (($scmode eq 'number') && ($max > 10)) {
                   8518:                 $max = 10;
                   8519:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8520:                 $max = 26;
                   8521:             }
                   8522:         } else {
                   8523:             $max = 10;
                   8524:         }
                   8525:     }
1.274     albertel 8526: 
1.157     albertel 8527:     my @alphabet=('A'..'Z');
1.503     raeburn  8528:     $r->print(&Apache::loncommon::start_data_table().
                   8529:               &Apache::loncommon::start_data_table_row());
                   8530:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8531:     for (my $i=0;$i<$max+1;$i++) {
                   8532: 	$r->print("\n".'<td align="center">');
                   8533: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8534: 	else { $r->print('&nbsp;'); }
                   8535: 	$r->print('</td>');
                   8536:     }
1.503     raeburn  8537:     $r->print(&Apache::loncommon::end_data_table_row().
                   8538:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8539:     for (my $i=0;$i<$max;$i++) {
                   8540: 	$r->print("\n".
                   8541: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8542: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8543:     }
1.503     raeburn  8544:     my $nobub_checked = ' ';
                   8545:     if ($error eq 'missingbubble') {
                   8546:         $nobub_checked = ' checked = "checked" ';
                   8547:     }
                   8548:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8549: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8550:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8551:               $line.'" value="'.$questionnum.'" /></td>');
                   8552:     $r->print(&Apache::loncommon::end_data_table_row().
                   8553:               &Apache::loncommon::end_data_table());
1.157     albertel 8554: }
                   8555: 
1.423     albertel 8556: =pod
                   8557: 
                   8558: =item num_matches
                   8559: 
1.424     albertel 8560:    Counts the number of characters that are the same between the two arguments.
                   8561: 
                   8562:  Arguments:
                   8563:    $orig - CODE from the scanline
                   8564:    $code - CODE to match against
                   8565: 
                   8566:  Returns:
                   8567:    $count - integer count of the number of same characters between the
                   8568:             two arguments
                   8569: 
1.423     albertel 8570: =cut
                   8571: 
1.194     albertel 8572: sub num_matches {
                   8573:     my ($orig,$code) = @_;
                   8574:     my @code=split(//,$code);
                   8575:     my @orig=split(//,$orig);
                   8576:     my $same=0;
                   8577:     for (my $i=0;$i<scalar(@code);$i++) {
                   8578: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8579:     }
                   8580:     return $same;
                   8581: }
                   8582: 
1.423     albertel 8583: =pod
                   8584: 
                   8585: =item scantron_get_closely_matching_CODEs
                   8586: 
1.424     albertel 8587:    Cycles through all CODEs and finds the set that has the greatest
                   8588:    number of same characters as the provided CODE
                   8589: 
                   8590:  Arguments:
                   8591:    $allcodes - hash ref returned by &get_codes()
                   8592:    $CODE     - CODE from the current scanline
                   8593: 
                   8594:  Returns:
                   8595:    2 element list
                   8596:     - first elements is number of how closely matching the best fit is 
                   8597:       (5 means best set has 5 matching characters)
                   8598:     - second element is an arrary ref containing the set of valid CODEs
                   8599:       that best fit the passed in CODE
                   8600: 
1.423     albertel 8601: =cut
                   8602: 
1.194     albertel 8603: sub scantron_get_closely_matching_CODEs {
                   8604:     my ($allcodes,$CODE)=@_;
                   8605:     my @CODEs;
                   8606:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8607: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8608:     }
                   8609: 
                   8610:     return ($#CODEs,$CODEs[-1]);
                   8611: }
                   8612: 
1.423     albertel 8613: =pod
                   8614: 
                   8615: =item get_codes
                   8616: 
1.424     albertel 8617:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8618:    set of remembered CODEs.
                   8619: 
                   8620:  Arguments:
                   8621:   $old_name - name of the set of remembered CODEs
                   8622:   $cdom     - domain of the course
                   8623:   $cnum     - internal course name
                   8624: 
                   8625:  Returns:
                   8626:   %allcodes - keys are the valid CODEs, values are all 1
                   8627: 
1.423     albertel 8628: =cut
                   8629: 
1.194     albertel 8630: sub get_codes {
1.280     foxr     8631:     my ($old_name, $cdom, $cnum) = @_;
                   8632:     if (!$old_name) {
                   8633: 	$old_name=$env{'form.scantron_CODElist'};
                   8634:     }
                   8635:     if (!$cdom) {
                   8636: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8637:     }
                   8638:     if (!$cnum) {
                   8639: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8640:     }
1.278     albertel 8641:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8642: 				    $cdom,$cnum);
                   8643:     my %allcodes;
                   8644:     if ($result{"type\0$old_name"} eq 'number') {
                   8645: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8646:     } else {
                   8647: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8648:     }
1.194     albertel 8649:     return %allcodes;
                   8650: }
                   8651: 
1.423     albertel 8652: =pod
                   8653: 
                   8654: =item scantron_validate_CODE
                   8655: 
1.424     albertel 8656:    Validates all scanlines in the selected file to not have any
                   8657:    invalid or underspecified CODEs and that none of the codes are
                   8658:    duplicated if this was requested.
                   8659: 
1.423     albertel 8660: =cut
                   8661: 
1.157     albertel 8662: sub scantron_validate_CODE {
                   8663:     my ($r,$currentphase) = @_;
1.754     raeburn  8664:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8665:     if ($scantron_config{'CODElocation'} &&
                   8666: 	$scantron_config{'CODEstart'} &&
                   8667: 	$scantron_config{'CODElength'}) {
1.257     albertel 8668: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8669: 	    &FIXME_blow_up()
                   8670: 	}
                   8671:     } else {
                   8672: 	return (0,$currentphase+1);
                   8673:     }
                   8674:     
                   8675:     my %usedCODEs;
                   8676: 
1.194     albertel 8677:     my %allcodes=&get_codes();
1.186     albertel 8678: 
1.582     raeburn  8679:     my $nav_error;
1.649     raeburn  8680:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8681:     if ($nav_error) {
                   8682:         $r->print(&navmap_errormsg());
                   8683:         return(1,$currentphase);
                   8684:     }
1.447     foxr     8685: 
1.186     albertel 8686:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8687:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8688: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8689: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8690: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8691: 						 $scan_data);
                   8692: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8693: 	my $error=0;
1.224     albertel 8694: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8695: 	    &scantron_get_correction($r,$i,$scan_record,
                   8696: 				     \%scantron_config,
                   8697: 				     $line,'incorrectCODE',\%allcodes);
                   8698: 	    return(1,$currentphase);
                   8699: 	}
1.221     albertel 8700: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8701: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8702: 	    &scantron_get_correction($r,$i,$scan_record,
                   8703: 				     \%scantron_config,
1.194     albertel 8704: 				     $line,'incorrectCODE',\%allcodes);
                   8705: 	    return(1,$currentphase);
1.186     albertel 8706: 	}
1.214     albertel 8707: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8708: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8709: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8710: 	    &scantron_get_correction($r,$i,$scan_record,
                   8711: 				     \%scantron_config,
1.194     albertel 8712: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8713: 	    return(1,$currentphase);
1.186     albertel 8714: 	}
1.524     raeburn  8715: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8716:     }
1.157     albertel 8717:     return (0,$currentphase+1);
                   8718: }
                   8719: 
1.423     albertel 8720: =pod
                   8721: 
                   8722: =item scantron_validate_doublebubble
                   8723: 
1.424     albertel 8724:    Validates all scanlines in the selected file to not have any
                   8725:    bubble lines with multiple bubbles marked.
                   8726: 
1.423     albertel 8727: =cut
                   8728: 
1.157     albertel 8729: sub scantron_validate_doublebubble {
                   8730:     my ($r,$currentphase) = @_;
                   8731:     #get student info
                   8732:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8733:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8734:     my (undef,undef,$sequence)=
                   8735:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8736: 
                   8737:     #get scantron line setup
1.754     raeburn  8738:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8739:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8740: 
                   8741:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8742:     unless (ref($navmap)) {
                   8743:         $r->print(&navmap_errormsg());
                   8744:         return(1,$currentphase);
                   8745:     }
                   8746:     my $map=$navmap->getResourceByUrl($sequence);
                   8747:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8748:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8749:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8750:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8751: 
1.583     raeburn  8752:     my $nav_error;
1.691     raeburn  8753:     if (ref($map)) {
                   8754:         $randomorder = $map->randomorder();
                   8755:         $randompick = $map->randompick();
                   8756:         if ($randomorder || $randompick) {
                   8757:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8758:             if ($nav_error) {
                   8759:                 $r->print(&navmap_errormsg());
                   8760:                 return(1,$currentphase);
                   8761:             }
                   8762:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8763:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8764:         }
                   8765:     } else {
                   8766:         $r->print(&navmap_errormsg());
                   8767:         return(1,$currentphase);
                   8768:     }
                   8769: 
1.649     raeburn  8770:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8771:     if ($nav_error) {
                   8772:         $r->print(&navmap_errormsg());
                   8773:         return(1,$currentphase);
                   8774:     }
1.447     foxr     8775: 
1.157     albertel 8776:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8777: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8778: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8779: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8780: 						 $scan_data,undef,\%idmap,$randomorder,
                   8781:                                                  $randompick,$sequence,\@master_seq,
                   8782:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8783:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8784: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8785: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8786: 				 'doublebubble',
1.691     raeburn  8787: 				 $$scan_record{'scantron.doubleerror'},
                   8788:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8789:     	return (1,$currentphase);
                   8790:     }
                   8791:     return (0,$currentphase+1);
                   8792: }
                   8793: 
1.423     albertel 8794: 
1.503     raeburn  8795: sub scantron_get_maxbubble {
1.649     raeburn  8796:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8797:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8798: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8799: 	&restore_bubble_lines();
1.257     albertel 8800: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8801:     }
1.330     albertel 8802: 
1.447     foxr     8803:     my (undef, undef, $sequence) =
1.257     albertel 8804: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8805: 
1.447     foxr     8806:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8807:     unless (ref($navmap)) {
                   8808:         if (ref($nav_error)) {
                   8809:             $$nav_error = 1;
                   8810:         }
1.591     raeburn  8811:         return;
1.582     raeburn  8812:     }
1.191     albertel 8813:     my $map=$navmap->getResourceByUrl($sequence);
                   8814:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8815:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8816: 
                   8817:     &Apache::lonxml::clear_problem_counter();
                   8818: 
1.557     raeburn  8819:     my $uname       = $env{'user.name'};
                   8820:     my $udom        = $env{'user.domain'};
1.435     foxr     8821:     my $cid         = $env{'request.course.id'};
                   8822:     my $total_lines = 0;
                   8823:     %bubble_lines_per_response = ();
1.447     foxr     8824:     %first_bubble_line         = ();
1.503     raeburn  8825:     %subdivided_bubble_lines   = ();
                   8826:     %responsetype_per_response = ();
1.691     raeburn  8827:     %masterseq_id_responsenum  = ();
1.554     raeburn  8828: 
1.447     foxr     8829:     my $response_number = 0;
                   8830:     my $bubble_line     = 0;
1.191     albertel 8831:     foreach my $resource (@resources) {
1.691     raeburn  8832:         my $resid = $resource->id(); 
1.672     raeburn  8833:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8834:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8835:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8836: 	    foreach my $part_id (@{$parts}) {
                   8837:                 my $lines;
                   8838: 
                   8839: 	        # TODO - make this a persistent hash not an array.
                   8840: 
                   8841:                 # optionresponse, matchresponse and rankresponse type items 
                   8842:                 # render as separate sub-questions in exam mode.
                   8843:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8844:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8845:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8846:                     my ($numbub,$numshown);
                   8847:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8848:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8849:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8850:                         }
                   8851:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8852:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8853:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8854:                         }
                   8855:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8856:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8857:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8858:                         }
                   8859:                     }
                   8860:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8861:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8862:                     }
1.649     raeburn  8863:                     my $bubbles_per_row =
                   8864:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8865:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8866:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8867:                         $inner_bubble_lines++;
                   8868:                     }
                   8869:                     for (my $i=0; $i<$numshown; $i++) {
                   8870:                         $subdivided_bubble_lines{$response_number} .= 
                   8871:                             $inner_bubble_lines.',';
                   8872:                     }
                   8873:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8874:                     $lines = $numshown * $inner_bubble_lines;
                   8875:                 } else {
                   8876:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8877:                 }
1.542     raeburn  8878: 
                   8879:                 $first_bubble_line{$response_number} = $bubble_line;
                   8880: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8881:                 $responsetype_per_response{$response_number} = 
                   8882:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8883:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8884: 	        $response_number++;
                   8885: 
                   8886: 	        $bubble_line +=  $lines;
                   8887: 	        $total_lines +=  $lines;
                   8888: 	    }
                   8889:         }
                   8890:     }
1.552     raeburn  8891:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8892: 
                   8893:     &save_bubble_lines();
                   8894:     $env{'form.scantron_maxbubble'} =
                   8895: 	$total_lines;
                   8896:     return $env{'form.scantron_maxbubble'};
                   8897: }
1.523     raeburn  8898: 
1.649     raeburn  8899: sub bubblesheet_bubbles_per_row {
                   8900:     my ($scantron_config) = @_;
                   8901:     my $bubbles_per_row;
                   8902:     if (ref($scantron_config) eq 'HASH') {
                   8903:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8904:     }
                   8905:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8906:         $bubbles_per_row = 10;
                   8907:     }
                   8908:     return $bubbles_per_row;
                   8909: }
                   8910: 
1.157     albertel 8911: sub scantron_validate_missingbubbles {
                   8912:     my ($r,$currentphase) = @_;
                   8913:     #get student info
                   8914:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8915:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8916:     my (undef,undef,$sequence)=
                   8917:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8918: 
                   8919:     #get scantron line setup
1.754     raeburn  8920:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8921:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8922: 
                   8923:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8924:     unless (ref($navmap)) {
                   8925:         $r->print(&navmap_errormsg());
                   8926:         return(1,$currentphase);
                   8927:     }
                   8928: 
                   8929:     my $map=$navmap->getResourceByUrl($sequence);
                   8930:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8931:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8932:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8933:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8934: 
1.582     raeburn  8935:     my $nav_error;
1.691     raeburn  8936:     if (ref($map)) {
                   8937:         $randomorder = $map->randomorder();
                   8938:         $randompick = $map->randompick();
                   8939:         if ($randomorder || $randompick) {
                   8940:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8941:             if ($nav_error) {
                   8942:                 $r->print(&navmap_errormsg());
                   8943:                 return(1,$currentphase);
                   8944:             }
                   8945:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8946:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8947:         }
                   8948:     } else {
                   8949:         $r->print(&navmap_errormsg());
                   8950:         return(1,$currentphase);
                   8951:     }
                   8952: 
                   8953: 
1.649     raeburn  8954:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8955:     if ($nav_error) {
1.691     raeburn  8956:         $r->print(&navmap_errormsg());
1.693     raeburn  8957:         return(1,$currentphase);
1.582     raeburn  8958:     }
1.691     raeburn  8959: 
1.157     albertel 8960:     if (!$max_bubble) { $max_bubble=2**31; }
                   8961:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8962: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8963: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8964: 	my $scan_record =
                   8965:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8966: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8967:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8968:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8969: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8970: 	my @to_correct;
1.470     foxr     8971: 	
                   8972: 	# Probably here's where the error is...
                   8973: 
1.157     albertel 8974: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8975:             my $lastbubble;
                   8976:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8977:                my $question = $1;
                   8978:                my $subquestion = $2;
1.691     raeburn  8979:                my ($first,$responsenum);
                   8980:                if ($randomorder || $randompick) {
                   8981:                    $responsenum = $respnumlookup{$question-1};
                   8982:                    $first = $startline{$question-1};
                   8983:                } else {
                   8984:                    $responsenum = $question-1; 
                   8985:                    $first = $first_bubble_line{$responsenum};
                   8986:                }
                   8987:                if (!defined($first)) { next; }
                   8988:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8989:                my $subcount = 1;
                   8990:                while ($subcount<$subquestion) {
                   8991:                    $first += $subans[$subcount-1];
                   8992:                    $subcount ++;
                   8993:                }
                   8994:                my $count = $subans[$subquestion-1];
                   8995:                $lastbubble = $first + $count;
                   8996:             } else {
1.691     raeburn  8997:                my ($first,$responsenum);
                   8998:                if ($randomorder || $randompick) {
                   8999:                    $responsenum = $respnumlookup{$missing-1};
                   9000:                    $first = $startline{$missing-1};
                   9001:                } else {
                   9002:                    $responsenum = $missing-1;
                   9003:                    $first = $first_bubble_line{$responsenum};
                   9004:                }
                   9005:                if (!defined($first)) { next; }
                   9006:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  9007:             }
                   9008:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 9009: 	    push(@to_correct,$missing);
                   9010: 	}
                   9011: 	if (@to_correct) {
                   9012: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  9013: 				     $line,'missingbubble',\@to_correct,
                   9014:                                      $randomorder,$randompick,\%respnumlookup,
                   9015:                                      \%startline);
1.157     albertel 9016: 	    return (1,$currentphase);
                   9017: 	}
                   9018: 
                   9019:     }
                   9020:     return (0,$currentphase+1);
                   9021: }
                   9022: 
1.663     raeburn  9023: sub hand_bubble_option {
                   9024:     my (undef, undef, $sequence) =
                   9025:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9026:     return if ($sequence eq '');
                   9027:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9028:     unless (ref($navmap)) {
                   9029:         return;
                   9030:     }
                   9031:     my $needs_hand_bubbles;
                   9032:     my $map=$navmap->getResourceByUrl($sequence);
                   9033:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9034:     foreach my $res (@resources) {
                   9035:         if (ref($res)) {
                   9036:             if ($res->is_problem()) {
                   9037:                 my $partlist = $res->parts();
                   9038:                 foreach my $part (@{ $partlist }) {
                   9039:                     my @types = $res->responseType($part);
                   9040:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   9041:                         $needs_hand_bubbles = 1;
                   9042:                         last;
                   9043:                     }
                   9044:                 }
                   9045:             }
                   9046:         }
                   9047:     }
                   9048:     if ($needs_hand_bubbles) {
1.754     raeburn  9049:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  9050:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9051:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   9052:                &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 />').
                   9053:                '<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  9054:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  9055:     }
                   9056:     return;
                   9057: }
1.423     albertel 9058: 
1.82      albertel 9059: sub scantron_process_students {
1.608     www      9060:     my ($r,$symb) = @_;
1.513     foxr     9061: 
1.257     albertel 9062:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     9063:     if (!$symb) {
                   9064: 	return '';
                   9065:     }
1.324     albertel 9066:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 9067: 
1.754     raeburn  9068:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  9069:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 9070:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 9071:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9072:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 9073:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9074:     unless (ref($navmap)) {
                   9075:         $r->print(&navmap_errormsg());
                   9076:         return '';
1.691     raeburn  9077:     }
1.83      albertel 9078:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9079:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  9080:         %grader_randomlists_by_symb);
1.677     raeburn  9081:     if (ref($map)) {
                   9082:         $randomorder = $map->randomorder();
1.689     raeburn  9083:         $randompick = $map->randompick();
1.691     raeburn  9084:     } else {
                   9085:         $r->print(&navmap_errormsg());
                   9086:         return '';
1.677     raeburn  9087:     }
1.691     raeburn  9088:     my $nav_error;
1.83      albertel 9089:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9090:     if ($randomorder || $randompick) {
                   9091:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9092:         if ($nav_error) {
                   9093:             $r->print(&navmap_errormsg());
                   9094:             return '';
                   9095:         }
                   9096:     }
1.557     raeburn  9097:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  9098:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  9099: 
1.554     raeburn  9100:     my ($uname,$udom);
1.82      albertel 9101:     my $result= <<SCANTRONFORM;
1.81      albertel 9102: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   9103:   <input type="hidden" name="command" value="scantron_configphase" />
                   9104:   $default_form_data
                   9105: SCANTRONFORM
1.82      albertel 9106:     $r->print($result);
                   9107: 
1.770     raeburn  9108:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 9109:     my @delayqueue;
1.542     raeburn  9110:     my (%completedstudents,%scandata);
1.770     raeburn  9111: 
1.520     www      9112:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9113:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9114:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   9115:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9116:     $r->print('<br />');
1.140     albertel 9117:     my $start=&Time::HiRes::time();
1.158     albertel 9118:     my $i=-1;
1.542     raeburn  9119:     my $started;
1.447     foxr     9120: 
1.649     raeburn  9121:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9122:     if ($nav_error) {
                   9123:         $r->print(&navmap_errormsg());
                   9124:         return '';
                   9125:     }
                   9126: 
1.513     foxr     9127:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9128:     # the user and return.
                   9129: 
                   9130:     if ($ssi_error) {
                   9131: 	$r->print("</form>");
                   9132: 	&ssi_print_error($r);
1.520     www      9133:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9134: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9135:     }
1.447     foxr     9136: 
1.755     raeburn  9137:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9138:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  9139:     my %orderedforcode;
1.542     raeburn  9140: 
1.157     albertel 9141:     while ($i<$scanlines->{'count'}) {
                   9142:  	($uname,$udom)=('','');
                   9143:  	$i++;
1.200     albertel 9144:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9145:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9146: 	if ($started) {
1.667     www      9147: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9148: 	}
                   9149: 	$started=1;
1.691     raeburn  9150:         my %respnumlookup = ();
                   9151:         my %startline = ();
                   9152:         my $total;
1.157     albertel 9153:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9154:                                                  $scan_data,undef,\%idmap,$randomorder,
                   9155:                                                  $randompick,$sequence,\@master_seq,
                   9156:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9157:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9158:                                                  \$total);
1.157     albertel 9159:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9160:  					      \%idmap,$i)) {
                   9161:   	    &scantron_add_delay(\@delayqueue,$line,
                   9162:  				'Unable to find a student that matches',1);
                   9163:  	    next;
                   9164:   	}
                   9165:  	if (exists $completedstudents{$uname}) {
                   9166:  	    &scantron_add_delay(\@delayqueue,$line,
                   9167:  				'Student '.$uname.' has multiple sheets',2);
                   9168:  	    next;
                   9169:  	}
1.677     raeburn  9170:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  9171:         if (($checksec ne '') && ($checksec ne $usec)) {
                   9172:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   9173:                 &scantron_add_delay(\@delayqueue,$line,
                   9174:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   9175:                 next;
                   9176:             }
                   9177:         }
1.677     raeburn  9178:         my $user = $uname.':'.$usec;
1.157     albertel 9179:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9180: 
1.677     raeburn  9181:         my $scancode;
                   9182:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9183:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9184:             $scancode = $scan_record->{'scantron.CODE'};
                   9185:         } else {
                   9186:             $scancode = '';
                   9187:         }
                   9188: 
                   9189:         my @mapresources = @resources;
1.689     raeburn  9190:         if ($randomorder || $randompick) {
1.678     raeburn  9191:             @mapresources = 
1.691     raeburn  9192:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9193:                              \%orderedforcode);
1.677     raeburn  9194:         }
1.586     raeburn  9195:         my (%partids_by_symb,$res_error);
1.677     raeburn  9196:         foreach my $resource (@mapresources) {
1.586     raeburn  9197:             my $ressymb;
                   9198:             if (ref($resource)) {
                   9199:                 $ressymb = $resource->symb();
                   9200:             } else {
                   9201:                 $res_error = 1;
                   9202:                 last;
                   9203:             }
1.557     raeburn  9204:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9205:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9206:                 my $currcode;
                   9207:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9208:                     $currcode = $scancode;
                   9209:                 }
1.557     raeburn  9210:                 my ($analysis,$parts) =
1.672     raeburn  9211:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  9212:                                               $uname,$udom,undef,$bubbles_per_row,
                   9213:                                               $currcode);
1.557     raeburn  9214:                 $partids_by_symb{$ressymb} = $parts;
                   9215:             } else {
                   9216:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9217:             }
1.554     raeburn  9218:         }
                   9219: 
1.586     raeburn  9220:         if ($res_error) {
                   9221:             &scantron_add_delay(\@delayqueue,$line,
                   9222:                                 'An error occurred while grading student '.$uname,2);
                   9223:             next;
                   9224:         }
                   9225: 
1.330     albertel 9226: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9227:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9228: 
                   9229: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9230: 	    &scantron_putfile($scanlines,$scan_data);
                   9231: 	}
1.161     albertel 9232: 	
1.542     raeburn  9233:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9234:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  9235:                                    $bubbles_per_row,$randomorder,$randompick,
                   9236:                                    \%respnumlookup,\%startline) 
                   9237:             eq 'ssi_error') {
1.542     raeburn  9238:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9239:             $r->print("</form>");
                   9240:             &ssi_print_error($r);
                   9241:             &Apache::lonnet::remove_lock($lock);
                   9242:             return '';      # Why return ''?  Beats me.
                   9243:         }
1.513     foxr     9244: 
1.692     raeburn  9245:         if (($scancode) && ($randomorder || $randompick)) {
                   9246:             my $parmresult =
                   9247:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   9248:                                                        '0_examcode',2,$scancode,
                   9249:                                                        'string_examcode',$uname,
                   9250:                                                        $udom);
                   9251:         }
1.140     albertel 9252: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9253:         if ($env{'form.verifyrecord'}) {
                   9254:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  9255:             if ($randompick) {
                   9256:                 if ($total) {
                   9257:                     $lastpos = $total*$scantron_config{'Qlength'};
                   9258:                 }
                   9259:             }
                   9260: 
1.542     raeburn  9261:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9262:             chomp($studentdata);
                   9263:             $studentdata =~ s/\r$//;
                   9264:             my $studentrecord = '';
                   9265:             my $counter = -1;
1.677     raeburn  9266:             foreach my $resource (@mapresources) {
1.554     raeburn  9267:                 my $ressymb = $resource->symb();
1.542     raeburn  9268:                 ($counter,my $recording) =
                   9269:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9270:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9271:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9272:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9273:                 $studentrecord .= $recording;
                   9274:             }
                   9275:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9276:                 &Apache::lonxml::clear_problem_counter();
                   9277:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9278:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  9279:                                            $bubbles_per_row,$randomorder,$randompick,
                   9280:                                            \%respnumlookup,\%startline) 
                   9281:                     eq 'ssi_error') {
1.554     raeburn  9282:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9283:                     $r->print("</form>");
                   9284:                     &ssi_print_error($r);
                   9285:                     &Apache::lonnet::remove_lock($lock);
                   9286:                     delete($completedstudents{$uname});
                   9287:                     return '';
                   9288:                 }
1.542     raeburn  9289:                 $counter = -1;
                   9290:                 $studentrecord = '';
1.677     raeburn  9291:                 foreach my $resource (@mapresources) {
1.554     raeburn  9292:                     my $ressymb = $resource->symb();
1.542     raeburn  9293:                     ($counter,my $recording) =
                   9294:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9295:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9296:                                                  \%scantron_config,\%lettdig,$numletts,
                   9297:                                                  $randomorder,$randompick,\%respnumlookup,
                   9298:                                                  \%startline);
1.542     raeburn  9299:                     $studentrecord .= $recording;
                   9300:                 }
                   9301:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   9302:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9303:                     if ($scancode eq '') {
1.658     bisitz   9304:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9305:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9306:                     } else {
1.658     bisitz   9307:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9308:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9309:                     }
                   9310:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9311:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9312:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9313:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9314:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9315:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   9316:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9317:                               &Apache::loncommon::end_data_table_row().
                   9318:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9319:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   9320:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9321:                               &Apache::loncommon::end_data_table_row().
                   9322:                               &Apache::loncommon::end_data_table().'</p>');
                   9323:                 } else {
                   9324:                     $r->print('<br /><span class="LC_warning">'.
                   9325:                              &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 />'.
                   9326:                              &mt("As a consequence, this user's submission history records two tries.").
                   9327:                                  '</span><br />');
                   9328:                 }
                   9329:             }
                   9330:         }
1.543     raeburn  9331:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9332:     } continue {
1.330     albertel 9333: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9334: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9335:     }
1.140     albertel 9336:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9337:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9338: #    my $lasttime = &Time::HiRes::time()-$start;
                   9339: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9340: 
1.200     albertel 9341:     $r->print("</form>");
1.157     albertel 9342:     return '';
1.75      albertel 9343: }
1.157     albertel 9344: 
1.557     raeburn  9345: sub graders_resources_pass {
1.649     raeburn  9346:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9347:         $bubbles_per_row) = @_;
1.557     raeburn  9348:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9349:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9350:         foreach my $resource (@{$resources}) {
                   9351:             my $ressymb = $resource->symb();
                   9352:             my ($analysis,$parts) =
                   9353:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  9354:                                           $env{'user.name'},$env{'user.domain'},
                   9355:                                           1,$bubbles_per_row);
1.557     raeburn  9356:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9357:             if (ref($analysis) eq 'HASH') {
                   9358:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9359:                     $grader_randomlists_by_symb->{$ressymb} =
                   9360:                         $analysis->{'parts_withrandomlist'};
                   9361:                 }
                   9362:             }
                   9363:         }
                   9364:     }
                   9365:     return;
                   9366: }
                   9367: 
1.678     raeburn  9368: =pod
                   9369: 
                   9370: =item users_order
                   9371: 
                   9372:   Returns array of resources in current map, ordered based on either CODE,
                   9373:   if this is a CODEd exam, or based on student's identity if this is a 
                   9374:   "NAMEd" exam.
                   9375: 
1.691     raeburn  9376:   Should be used when randomorder and/or randompick applied when the 
                   9377:   corresponding exam was printed, prior to students completing bubblesheets 
                   9378:   for the version of the exam the student received.
1.678     raeburn  9379: 
                   9380: =cut
                   9381: 
                   9382: sub users_order  {
1.691     raeburn  9383:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9384:     my @mapresources;
1.691     raeburn  9385:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9386:         return @mapresources;
1.691     raeburn  9387:     }
                   9388:     if ($scancode) {
                   9389:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9390:             @mapresources = @{$orderedforcode->{$scancode}};
                   9391:         } else {
                   9392:             $env{'form.CODE'} = $scancode;
                   9393:             my $actual_seq =
                   9394:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9395:                                                                $master_seq,
                   9396:                                                                $user,$scancode,1);
                   9397:             if (ref($actual_seq) eq 'ARRAY') {
                   9398:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9399:                 if (ref($orderedforcode) eq 'HASH') {
                   9400:                     if (@mapresources > 0) { 
                   9401:                         $orderedforcode->{$scancode} = \@mapresources;
                   9402:                     }
                   9403:                 }
                   9404:             }
                   9405:             delete($env{'form.CODE'});
1.678     raeburn  9406:         }
                   9407:     } else {
                   9408:         my $actual_seq =
                   9409:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9410:                                                            $master_seq,
1.688     raeburn  9411:                                                            $user,undef,1);
1.678     raeburn  9412:         if (ref($actual_seq) eq 'ARRAY') {
                   9413:             @mapresources = 
                   9414:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9415:         }
1.691     raeburn  9416:     }
                   9417:     return @mapresources;
1.678     raeburn  9418: }
                   9419: 
1.542     raeburn  9420: sub grade_student_bubbles {
1.691     raeburn  9421:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9422:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9423:     my $uselookup = 0;
                   9424:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9425:         (ref($startline) eq 'HASH')) {
                   9426:         $uselookup = 1;
                   9427:     }
                   9428: 
1.554     raeburn  9429:     if (ref($resources) eq 'ARRAY') {
                   9430:         my $count = 0;
                   9431:         foreach my $resource (@{$resources}) {
                   9432:             my $ressymb = $resource->symb();
                   9433:             my %form = ('submitted'      => 'scantron',
                   9434:                         'grade_target'   => 'grade',
                   9435:                         'grade_username' => $uname,
                   9436:                         'grade_domain'   => $udom,
                   9437:                         'grade_courseid' => $env{'request.course.id'},
                   9438:                         'grade_symb'     => $ressymb,
                   9439:                         'CODE'           => $scancode
                   9440:                        );
1.649     raeburn  9441:             if ($bubbles_per_row ne '') {
                   9442:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9443:             }
1.663     raeburn  9444:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9445:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9446:             }
1.554     raeburn  9447:             if (ref($parts) eq 'HASH') {
                   9448:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9449:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9450:                         if ($uselookup) {
                   9451:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9452:                         } else {
                   9453:                             $form{'scantron_questnum_start.'.$part} =
                   9454:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9455:                         }
1.554     raeburn  9456:                         $count++;
                   9457:                     }
                   9458:                 }
                   9459:             }
                   9460:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9461:             return 'ssi_error' if ($ssi_error);
                   9462:             last if (&Apache::loncommon::connection_aborted($r));
                   9463:         }
1.542     raeburn  9464:     }
                   9465:     return;
                   9466: }
                   9467: 
1.157     albertel 9468: sub scantron_upload_scantron_data {
1.767     raeburn  9469:     my ($r,$symb) = @_;
1.565     raeburn  9470:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9471:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9472:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9473:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9474:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9475: 							  'domainid',
1.565     raeburn  9476: 							  'coursename',$dom);
                   9477:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9478:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9479:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9480:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9481:     &js_escape(\$nofile_alert);
1.579     raeburn  9482:     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  9483:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9484:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9485:     function checkUpload(formname) {
                   9486: 	if (formname.upfile.value == "") {
1.579     raeburn  9487: 	    alert("'.$nofile_alert.'");
1.157     albertel 9488: 	    return false;
                   9489: 	}
1.565     raeburn  9490:         if (formname.courseid.value == "") {
1.579     raeburn  9491:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9492:             return false;
                   9493:         }
1.157     albertel 9494: 	formname.submit();
                   9495:     }
1.565     raeburn  9496: 
                   9497:     function ToSyllabus() {
                   9498:         var cdom = '."'$dom'".';
                   9499:         var cnum = document.rules.courseid.value;
                   9500:         if (cdom == "" || cdom == null) {
                   9501:             return;
                   9502:         }
                   9503:         if (cnum == "" || cnum == null) {
                   9504:            return;
                   9505:         }
                   9506:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9507:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9508:         return;
                   9509:     }
                   9510: 
1.754     raeburn  9511:     '.$formatjs.'
1.597     wenzelju 9512: '));
                   9513:     $r->print('
1.648     bisitz   9514: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9515: 
1.492     albertel 9516: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9517: '.$default_form_data.
                   9518:   &Apache::lonhtmlcommon::start_pick_box().
                   9519:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9520:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9521:   &Apache::lonhtmlcommon::row_closure().
                   9522:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9523:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9524:   &Apache::lonhtmlcommon::row_closure().
                   9525:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9526:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9527:   &Apache::lonhtmlcommon::row_closure());
                   9528:     if ($formatoptions) {
                   9529:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9530:                   &Apache::lonhtmlcommon::row_closure());
                   9531:     }
                   9532:     $r->print(
1.565     raeburn  9533:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9534:   '<input type="file" name="upfile" size="50" />'.
                   9535:   &Apache::lonhtmlcommon::row_closure(1).
                   9536:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9537: 
1.492     albertel 9538: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9539: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9540: </form>
1.492     albertel 9541: ');
1.157     albertel 9542:     return '';
                   9543: }
                   9544: 
1.754     raeburn  9545: sub scantron_upload_dataformat {
                   9546:     my ($dom) = @_;
                   9547:     my ($formatoptions,$formattitle,$formatjs);
                   9548:     $formatjs = <<'END';
                   9549: function toggleScantab(form) {
                   9550:    return;
                   9551: }
                   9552: END
                   9553:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9554:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9555:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9556:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9557:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9558:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  9559:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   9560:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9561:                             my ($onclick,$formatextra,$singleline);
                   9562:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9563:                             my $count = 0;
                   9564:                             foreach my $line (@lines) {
                   9565:                                 next if ($line =~ /^#/);
                   9566:                                 $singleline = $line;
                   9567:                                 $count ++;
                   9568:                             }
                   9569:                             if ($count > 1) {
                   9570:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  9571:                                                '<span class="LC_nobreak">'.
1.776     raeburn  9572:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  9573:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  9574:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9575:                                 $formatjs = <<"END";
1.754     raeburn  9576: function toggleScantab(form) {
                   9577:     var divid = 'bubbletype';
                   9578:     if (document.getElementById(divid)) {
                   9579:         var radioname = 'fileformat';
                   9580:         var num = form.elements[radioname].length;
                   9581:         if (num) {
                   9582:             for (var i=0; i<num; i++) {
                   9583:                 if (form.elements[radioname][i].checked) {
                   9584:                     var chosen = form.elements[radioname][i].value;
                   9585:                     if (chosen == 'dat') {
                   9586:                         document.getElementById(divid).style.display = 'none';
                   9587:                     } else if (chosen == 'csv') {
1.757     raeburn  9588:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  9589:                     }
                   9590:                 }
                   9591:             }
                   9592:         }
                   9593:     }
                   9594:     return;
                   9595: }
                   9596: 
                   9597: END
1.756     raeburn  9598:                             } elsif ($count == 1) {
                   9599:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9600:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9601:                             }
                   9602:                             $formattitle = &mt('File format');
                   9603:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9604:                                              &mt('Plain Text (no delimiters)').
                   9605:                                              '</label>'.('&nbsp;'x2).
                   9606:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9607:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9608:                         }
                   9609:                     }
                   9610:                 }
                   9611:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  9612:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9613:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  9614:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  9615:                         $formatoptions = &scantron_scantab();
                   9616:                     }
1.754     raeburn  9617:                 }
                   9618:             }
                   9619:         }
                   9620:     }
                   9621:     return ($formatoptions,$formattitle,$formatjs);
                   9622: }
1.423     albertel 9623: 
1.157     albertel 9624: sub scantron_upload_scantron_data_save {
1.767     raeburn  9625:     my ($r,$symb) = @_;
1.182     albertel 9626:     my $doanotherupload=
                   9627: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9628: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9629: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9630: 	'</form>'."\n";
1.257     albertel 9631:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9632: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  9633: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   9634:         !&Apache::lonnet::allowed('usc',
                   9635:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      9636: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9637: 	unless ($symb) {
1.182     albertel 9638: 	    $r->print($doanotherupload);
                   9639: 	}
1.162     albertel 9640: 	return '';
                   9641:     }
1.257     albertel 9642:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9643:     my $uploadedfile;
1.710     bisitz   9644:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9645:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9646:         $r->print(
                   9647:             &Apache::lonhtmlcommon::confirm_success(
                   9648:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9649:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9650:     } else {
1.754     raeburn  9651:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9652:         my $parser;
                   9653:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9654:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9655:                 my $is_csv;
                   9656:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9657:                 if (@possibles > 1) {
                   9658:                     if ($env{'form.fileformat'} eq 'csv') {
                   9659:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9660:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9661:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9662:                                     $is_csv = 1;
                   9663:                                 }
1.754     raeburn  9664:                             }
                   9665:                         }
                   9666:                     }
                   9667:                 } elsif (@possibles == 1) {
                   9668:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9669:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9670:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9671:                                 $is_csv = 1;
                   9672:                             }
1.754     raeburn  9673:                         }
                   9674:                     }
                   9675:                 }
                   9676:                 if ($is_csv) {
                   9677:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9678:                 }
                   9679:             }
                   9680:         }
                   9681:         my $result =
                   9682:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9683:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9684:         if ($result =~ m{^/uploaded/}) {
                   9685:             $r->print(
                   9686:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9687:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9688:                         (length($env{'form.upfile'})-1),
                   9689:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9690:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  9691:             if ($uploadedfile =~ /^scantron_orig_/) {
                   9692:                 my $logname = $uploadedfile;
                   9693:                 $logname =~ s/^scantron_orig_//;
                   9694:                 if ($logname ne '') {
                   9695:                     my $now = time;
                   9696:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   9697:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9698:                 }
                   9699:             }
1.567     raeburn  9700:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  9701:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   9702:         } else {
                   9703:             $r->print(
                   9704:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9705:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9706:                           $result,
1.568     raeburn  9707: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9708: 	}
                   9709:     }
1.174     albertel 9710:     if ($symb) {
1.612     www      9711: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9712:     } else {
1.182     albertel 9713: 	$r->print($doanotherupload);
1.174     albertel 9714:     }
1.157     albertel 9715:     return '';
                   9716: }
                   9717: 
1.567     raeburn  9718: sub validate_uploaded_scantron_file {
1.770     raeburn  9719:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   9720: 
1.567     raeburn  9721:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9722:     my @lines;
                   9723:     if ($scanlines ne '-1') {
                   9724:         @lines=split("\n",$scanlines,-1);
                   9725:     }
1.770     raeburn  9726:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   9727:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   9728:     if ($context eq 'download') {
                   9729:         $priv = 'mgr';
                   9730:     } else {
                   9731:         $priv = 'usc';
                   9732:     }
                   9733:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   9734:             (($env{'request.course.id'}) &&
                   9735:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   9736:         if ($env{'request.course.sec'} ne '') {
                   9737:             unless (&Apache::lonnet::allowed($priv,
                   9738:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   9739:                 unless ($context eq 'download') {
                   9740:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   9741:                 }
                   9742:                 return $output;
                   9743:             }
                   9744:             ($checksec,@possibles)=&gradable_sections();
                   9745:         }
                   9746:     }
1.567     raeburn  9747:     if (@lines) {
                   9748:         my (%counts,$max_match_format);
1.710     bisitz   9749:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9750:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9751:         my %idmap = &username_to_idmap($classlist);
                   9752:         foreach my $key (keys(%idmap)) {
                   9753:             my $lckey = lc($key);
                   9754:             $idmap{$lckey} = $idmap{$key};
                   9755:         }
                   9756:         my %unique_formats;
1.754     raeburn  9757:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9758:         foreach my $line (@formatlines) {
                   9759:             chomp($line);
                   9760:             my @config = split(/:/,$line);
                   9761:             my $idstart = $config[5];
                   9762:             my $idlength = $config[6];
                   9763:             if (($idstart ne '') && ($idlength > 0)) {
                   9764:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9765:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9766:                 } else {
                   9767:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9768:                 }
                   9769:             }
                   9770:         }
                   9771:         foreach my $key (keys(%unique_formats)) {
                   9772:             my ($idstart,$idlength) = split(':',$key);
                   9773:             %{$counts{$key}} = (
                   9774:                                'found'   => 0,
                   9775:                                'total'   => 0,
1.770     raeburn  9776:                                'totalanysec' => 0,
                   9777:                                'othersec' => 0,
1.567     raeburn  9778:                               );
                   9779:             foreach my $line (@lines) {
                   9780:                 next if ($line =~ /^#/);
                   9781:                 next if ($line =~ /^[\s\cz]*$/);
                   9782:                 my $id = substr($line,$idstart-1,$idlength);
                   9783:                 $id = lc($id);
                   9784:                 if (exists($idmap{$id})) {
1.770     raeburn  9785:                     if ($checksec ne '') {
                   9786:                         $counts{$key}{'totalanysec'} ++;
                   9787:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9788:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9789:                             if ($stusec ne $checksec) {
                   9790:                                 if (@possibles) {
                   9791:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   9792:                                         $counts{$key}{'othersec'} ++;
                   9793:                                         next;
                   9794:                                     }
                   9795:                                 } else {
                   9796:                                     $counts{$key}{'othersec'} ++;
                   9797:                                     next;
                   9798:                                 }
                   9799:                             }
                   9800:                         }
                   9801:                     }
1.567     raeburn  9802:                     $counts{$key}{'found'} ++;
                   9803:                 }
                   9804:                 $counts{$key}{'total'} ++;
                   9805:             }
                   9806:             if ($counts{$key}{'total'}) {
                   9807:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9808:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9809:                     $max_match_pct = $percent_match;
                   9810:                     $max_match_format = $key;
1.710     bisitz   9811:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9812:                     $max_match_count = $counts{$key}{'total'};
                   9813:                 }
                   9814:             }
                   9815:         }
1.770     raeburn  9816:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  9817:             my $format_descs;
                   9818:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9819:             for (my $i=0; $i<$numwithformat; $i++) {
                   9820:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9821:                 if ($i<$numwithformat-2) {
                   9822:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9823:                 } elsif ($i==$numwithformat-2) {
                   9824:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9825:                 } elsif ($i==$numwithformat-1) {
                   9826:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9827:                 }
                   9828:             }
                   9829:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9830:             $output .= '<br />';
                   9831:             if ($found_match_count == $max_match_count) {
                   9832:                 # 100% matching entries
                   9833:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9834:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9835:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9836:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9837:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9838:                     ' in the file (for the format defined for [_3]).',
                   9839:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9840:             } else {
                   9841:                 # Not all entries matching? -> Show warning and additional info
                   9842:                 $output .=
                   9843:                     &Apache::lonhtmlcommon::confirm_success(
                   9844:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9845:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9846:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9847:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9848:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9849:                         ' in the file (for the format defined for [_3]).',
                   9850:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9851:                     '<p class="LC_info">'.
                   9852:                     &mt('A low percentage of matches results from one of the following:').
                   9853:                     '</p><ul>'.
                   9854:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9855:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9856:                                '<i>'.$cdom.'</i>').'</li>'.
                   9857:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9858:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9859:                     '</ul>';
                   9860:             }
1.770     raeburn  9861:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9862:                 if ($counts{$max_match_format}{'othersec'}) {
                   9863:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   9864:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   9865:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   9866:                     &js_escape(\$confirmdel);
                   9867:                     $output .= '<p class="LC_warning">'.
                   9868:                                &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',
                   9869:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   9870:                                '<br />'.
                   9871:                                &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>').
                   9872:                                '</p><p>'.
                   9873:                                &mt('If you prefer to delete the file now, use: [_1]').
                   9874:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   9875:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   9876:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   9877:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   9878:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   9879:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   9880:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   9881:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   9882:                                '</form></p>';
                   9883:                 }
                   9884:             }
1.567     raeburn  9885:         }
1.770     raeburn  9886:         if (($context eq 'download') && ($checksec ne '')) {
                   9887:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9888:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   9889:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   9890:             }
                   9891:         } 
                   9892:     } elsif ($context ne 'download') {
1.710     bisitz   9893:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9894:     }
                   9895:     return $output;
                   9896: }
                   9897: 
1.770     raeburn  9898: sub gradable_sections {
                   9899:     my $checksec = $env{'request.course.sec'};
                   9900:     my @oksecs;
                   9901:     if ($checksec) {
                   9902:         my %availablesecs = &sections_grade_privs();
                   9903:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   9904:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   9905:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   9906:                     push(@oksecs,$sec);
                   9907:                 }
                   9908:             }
                   9909:             if (grep(/^all$/,@oksecs)) {
                   9910:                 undef($checksec);
                   9911:             }
                   9912:         }
                   9913:     }
                   9914:     return($checksec,@oksecs);
                   9915: }
                   9916: 
                   9917: sub sections_grade_privs {
                   9918:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9919:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9920:     my %availablesecs = (
                   9921:                           mgr => [],
                   9922:                           vgr => [],
                   9923:                           usc => [],
                   9924:                         );
                   9925:     my $ccrole = 'cc';
                   9926:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   9927:         $ccrole = 'co';
                   9928:     }
                   9929:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   9930:                                                      'userroles',['active'],
                   9931:                                                      [$ccrole,'in','cr'],$cdom,1);
                   9932:     my $crsid = $cnum.':'.$cdom;
                   9933:     foreach my $item (keys(%crsroleshash)) {
                   9934:         next unless ($item =~ /^$crsid\:/);
                   9935:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   9936:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   9937:         if ($sec ne '') {
                   9938:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   9939:         }
                   9940:         if (($role eq $ccrole) || ($role eq 'in')) {
                   9941:             foreach my $priv ('mgr','vgr','usc') { 
                   9942:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9943:                     if ($sec eq '') {
                   9944:                         $availablesecs{$priv} = ['all'];
                   9945:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   9946:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9947:                             push(@{$availablesecs{$priv}},$sec);
                   9948:                         }
                   9949:                     }
                   9950:                 }
                   9951:             }
                   9952:         } elsif ($role =~ m{^cr/}) {
                   9953:             foreach my $priv ('mgr','vgr','usc') {
                   9954:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9955:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   9956:                         if ($sec eq '') {
                   9957:                             $availablesecs{$priv} = ['all'];
                   9958:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   9959:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9960:                                 push(@{$availablesecs{$priv}},$sec);
                   9961:                             }
                   9962:                         }
                   9963:                     }
                   9964:                 }
                   9965:             }
                   9966:         }
                   9967:     }
                   9968:     return %availablesecs;
                   9969: }
                   9970: 
                   9971: sub scantron_upload_delete {
                   9972:     my ($r,$symb) = @_;
                   9973:     my $filename = $env{'form.uploadedfile'};
                   9974:     if ($filename =~ /^scantron_orig_/) {
                   9975:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   9976:             &Apache::lonnet::allowed('usc',
                   9977:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   9978:             &Apache::lonnet::allowed('usc',
                   9979:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   9980:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   9981:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   9982:             if ($retrieval eq '-1') {
                   9983:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9984:                           &mt('File requested for deletion not found.'));
                   9985:             } else {
                   9986:                 $filename =~ s/^scantron_orig_//;
                   9987:                 if ($filename ne '') {
                   9988:                     my ($is_valid,$numleft);
                   9989:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9990:                     if (keys(%info)) {
                   9991:                         if (ref($info{$filename}) eq 'HASH') {
                   9992:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   9993:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9994:                                     $is_valid = 1;
                   9995:                                     delete($info{$filename}{$timestamp}); 
                   9996:                                 }
                   9997:                             }
                   9998:                             $numleft = scalar(keys(%{$info{$filename}}));
                   9999:                         }
                   10000:                     }
                   10001:                     if ($is_valid) {
                   10002:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   10003:                         if ($result eq 'ok') {
                   10004:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   10005:                             if ($numleft) {
                   10006:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   10007:                             } else {
                   10008:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   10009:                             }
                   10010:                         } else {
                   10011:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10012:                                       &mt('Result was [_1]',$result));
                   10013:                         }
                   10014:                     } else {
                   10015:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10016:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   10017:                     }
                   10018:                 } else {
                   10019:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10020:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   10021:                 }
                   10022:             }
                   10023:         } else {
                   10024:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   10025:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   10026:         }
                   10027:     } else {
                   10028:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10029:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   10030:     }
                   10031:     return;
                   10032: }
                   10033: 
1.202     albertel 10034: sub valid_file {
                   10035:     my ($requested_file)=@_;
                   10036:     foreach my $filename (sort(&scantron_filenames())) {
                   10037: 	if ($requested_file eq $filename) { return 1; }
                   10038:     }
                   10039:     return 0;
                   10040: }
                   10041: 
                   10042: sub scantron_download_scantron_data {
1.767     raeburn  10043:     my ($r,$symb) = @_;
1.608     www      10044:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 10045:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10046:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10047:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 10048:     if (! &valid_file($file)) {
1.492     albertel 10049: 	$r->print('
1.202     albertel 10050: 	<p>
1.686     bisitz   10051: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 10052:         </p>
1.492     albertel 10053: ');
1.202     albertel 10054: 	return;
                   10055:     }
1.770     raeburn  10056:     my (%uploader,$is_owner,%counts,$percent);
                   10057:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   10058:     if (ref($uploader{$file}) eq 'HASH') {
                   10059:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   10060:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   10061:                 $is_owner = 1;
                   10062:                 last;
                   10063:             }
                   10064:         }
                   10065:     }
                   10066:     unless ($is_owner) {
                   10067:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   10068:         if ($counts{'totalanysec'}) {
                   10069:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   10070:             if ($percent_othersec >= 10) {
                   10071:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   10072:                 $r->print('<p class="LC_warning">'.
                   10073:                           &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).
                   10074:                           '</p>');
                   10075:                 return;
                   10076:             }
                   10077:         }
                   10078:     }
1.202     albertel 10079:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   10080:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   10081:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   10082:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   10083:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   10084:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 10085:     $r->print('
1.202     albertel 10086:     <p>
1.723     raeburn  10087: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 10088: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 10089:     </p>
                   10090:     <p>
1.492     albertel 10091: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   10092: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 10093:     </p>
                   10094:     <p>
1.492     albertel 10095: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   10096: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 10097:     </p>
1.492     albertel 10098: ');
1.202     albertel 10099:     return '';
                   10100: }
1.157     albertel 10101: 
1.523     raeburn  10102: sub checkscantron_results {
1.608     www      10103:     my ($r,$symb) = @_;
1.523     raeburn  10104:     if (!$symb) {return '';}
                   10105:     my $cid = $env{'request.course.id'};
1.755     raeburn  10106:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  10107:     my $numletts = scalar(keys(%lettdig));
                   10108:     my $cnum = $env{'course.'.$cid.'.num'};
                   10109:     my $cdom = $env{'course.'.$cid.'.domain'};
                   10110:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10111:     my %record;
                   10112:     my %scantron_config =
1.754     raeburn  10113:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  10114:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  10115:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  10116:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10117:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   10118:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10119:     unless (ref($navmap)) {
                   10120:         $r->print(&navmap_errormsg());
                   10121:         return '';
                   10122:     }
1.523     raeburn  10123:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10124:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10125:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  10126:     if (ref($map)) { 
                   10127:         $randomorder=$map->randomorder();
1.689     raeburn  10128:         $randompick=$map->randompick();
1.677     raeburn  10129:     }
1.557     raeburn  10130:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10131:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10132:     if ($nav_error) {
                   10133:         $r->print(&navmap_errormsg());
                   10134:         return '';
1.678     raeburn  10135:     }
1.673     raeburn  10136:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10137:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  10138:     my ($uname,$udom);
1.523     raeburn  10139:     my (%scandata,%lastname,%bylast);
                   10140:     $r->print('
                   10141: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   10142: 
                   10143:     my @delayqueue;
                   10144:     my %completedstudents;
                   10145: 
1.691     raeburn  10146:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10147:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  10148:     my ($username,$domain,$started);
1.649     raeburn  10149:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10150:     if ($nav_error) {
                   10151:         $r->print(&navmap_errormsg());
                   10152:         return '';
                   10153:     }
1.523     raeburn  10154: 
1.667     www      10155:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  10156:     my $start=&Time::HiRes::time();
                   10157:     my $i=-1;
                   10158: 
                   10159:     while ($i<$scanlines->{'count'}) {
                   10160:         ($username,$domain,$uname)=('','','');
                   10161:         $i++;
                   10162:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   10163:         if ($line=~/^[\s\cz]*$/) { next; }
                   10164:         if ($started) {
1.667     www      10165:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  10166:         }
                   10167:         $started=1;
                   10168:         my $scan_record=
                   10169:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   10170:                                                      $scan_data);
1.693     raeburn  10171:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10172:                                               \%idmap,$i)) {
1.523     raeburn  10173:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10174:                                 'Unable to find a student that matches',1);
                   10175:             next;
                   10176:         }
                   10177:         if (exists $completedstudents{$uname}) {
                   10178:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10179:                                 'Student '.$uname.' has multiple sheets',2);
                   10180:             next;
                   10181:         }
                   10182:         my $pid = $scan_record->{'scantron.ID'};
                   10183:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   10184:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  10185:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   10186:         my $user = $uname.':'.$usec;
1.523     raeburn  10187:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  10188: 
1.678     raeburn  10189:         my $scancode;
1.677     raeburn  10190:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10191:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10192:             $scancode = $scan_record->{'scantron.CODE'};
                   10193:         } else {
                   10194:             $scancode = '';
                   10195:         }
                   10196: 
                   10197:         my @mapresources = @resources;
1.691     raeburn  10198:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   10199:         my %respnumlookup=();
                   10200:         my %startline=();
1.689     raeburn  10201:         if ($randomorder || $randompick) {
1.678     raeburn  10202:             @mapresources =
1.691     raeburn  10203:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10204:                              \%orderedforcode);
                   10205:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   10206:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   10207:                                              \%grader_partids_by_symb,\%orderedforcode,
                   10208:                                              \%respnumlookup,\%startline);
                   10209:             if ($randompick && $total) {
                   10210:                 $lastpos = $total*$scantron_config{'Qlength'};
                   10211:             }
1.677     raeburn  10212:         }
1.691     raeburn  10213:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10214:         chomp($scandata{$pid});
                   10215:         $scandata{$pid} =~ s/\r$//;
                   10216: 
1.523     raeburn  10217:         my $counter = -1;
1.677     raeburn  10218:         foreach my $resource (@mapresources) {
1.557     raeburn  10219:             my $parts;
1.554     raeburn  10220:             my $ressymb = $resource->symb();
1.557     raeburn  10221:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10222:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10223:                 my $currcode;
                   10224:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10225:                     $currcode = $scancode;
                   10226:                 }
1.557     raeburn  10227:                 (my $analysis,$parts) =
1.672     raeburn  10228:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   10229:                                               $username,$domain,undef,
1.741     raeburn  10230:                                               $bubbles_per_row,$currcode);
1.557     raeburn  10231:             } else {
                   10232:                 $parts = $grader_partids_by_symb{$ressymb};
                   10233:             }
1.542     raeburn  10234:             ($counter,my $recording) =
                   10235:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  10236:                                          $scandata{$pid},$parts,
1.691     raeburn  10237:                                          \%scantron_config,\%lettdig,$numletts,
                   10238:                                          $randomorder,$randompick,
                   10239:                                          \%respnumlookup,\%startline);
1.542     raeburn  10240:             $record{$pid} .= $recording;
1.523     raeburn  10241:         }
                   10242:     }
                   10243:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   10244:     $r->print('<br />');
                   10245:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   10246:     $passed = 0;
                   10247:     $failed = 0;
                   10248:     $numstudents = 0;
                   10249:     foreach my $last (sort(keys(%bylast))) {
                   10250:         if (ref($bylast{$last}) eq 'ARRAY') {
                   10251:             foreach my $pid (sort(@{$bylast{$last}})) {
                   10252:                 my $showscandata = $scandata{$pid};
                   10253:                 my $showrecord = $record{$pid};
                   10254:                 $showscandata =~ s/\s/&nbsp;/g;
                   10255:                 $showrecord =~ s/\s/&nbsp;/g;
                   10256:                 if ($scandata{$pid} eq $record{$pid}) {
                   10257:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   10258:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      10259: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  10260: '</tr>'."\n".
                   10261: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10262: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  10263:                     $passed ++;
                   10264:                 } else {
                   10265:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      10266:                     $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  10267: '</tr>'."\n".
                   10268: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10269: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  10270: '</tr>'."\n";
                   10271:                     $failed ++;
                   10272:                 }
                   10273:                 $numstudents ++;
                   10274:             }
                   10275:         }
                   10276:     }
1.648     bisitz   10277:     $r->print(
                   10278:         '<p>'
                   10279:        .&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).',
                   10280:             '<b>',
                   10281:             $numstudents,
                   10282:             '</b>',
                   10283:             $env{'form.scantron_maxbubble'})
                   10284:        .'</p>'
                   10285:     );
1.682     raeburn  10286:     $r->print('<p>'
1.683     raeburn  10287:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  10288:              .'<br />'
                   10289:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10290:              .'</p>'
                   10291:     );
1.523     raeburn  10292:     if ($passed) {
1.572     www      10293:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10294:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10295:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10296:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10297:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10298:                  $okstudents."\n".
                   10299:                  &Apache::loncommon::end_data_table().'<br />');
                   10300:     }
                   10301:     if ($failed) {
1.572     www      10302:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10303:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10304:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10305:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10306:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10307:                  $badstudents."\n".
                   10308:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10309:                  &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  10310:     }
1.614     www      10311:     $r->print('</form><br />');
1.523     raeburn  10312:     return;
                   10313: }
                   10314: 
1.542     raeburn  10315: sub verify_scantron_grading {
1.554     raeburn  10316:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  10317:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10318:         $respnumlookup,$startline) = @_;
1.542     raeburn  10319:     my ($record,%expected,%startpos);
                   10320:     return ($counter,$record) if (!ref($resource));
                   10321:     return ($counter,$record) if (!$resource->is_problem());
                   10322:     my $symb = $resource->symb();
1.554     raeburn  10323:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10324:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10325:         $counter ++;
                   10326:         $expected{$part_id} = 0;
1.691     raeburn  10327:         my $respnum = $counter;
                   10328:         if ($randomorder || $randompick) {
                   10329:             $respnum = $respnumlookup->{$counter};
                   10330:             $startpos{$part_id} = $startline->{$counter} + 1;
                   10331:         } else {
                   10332:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10333:         }
                   10334:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10335:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10336:             foreach my $item (@sub_lines) {
                   10337:                 $expected{$part_id} += $item;
                   10338:             }
                   10339:         } else {
1.691     raeburn  10340:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10341:         }
                   10342:     }
                   10343:     if ($symb) {
                   10344:         my %recorded;
                   10345:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10346:         if ($returnhash{'version'}) {
                   10347:             my %lasthash=();
                   10348:             my $version;
                   10349:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10350:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10351:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10352:                 }
                   10353:             }
                   10354:             foreach my $key (keys(%lasthash)) {
                   10355:                 if ($key =~ /\.scantron$/) {
                   10356:                     my $value = &unescape($lasthash{$key});
                   10357:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10358:                     if ($value eq '') {
                   10359:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10360:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10361:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10362:                             }
                   10363:                         }
                   10364:                     } else {
                   10365:                         my @tocheck;
                   10366:                         my @items = split(//,$value);
                   10367:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10368:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10369:                             if (@items < $expected{$part_id}) {
                   10370:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10371:                                 my @singles = split(//,$fragment);
                   10372:                                 foreach my $pos (@singles) {
                   10373:                                     if ($pos eq ' ') {
                   10374:                                         push(@tocheck,$pos);
                   10375:                                     } else {
                   10376:                                         my $next = shift(@items);
                   10377:                                         push(@tocheck,$next);
                   10378:                                     }
                   10379:                                 }
                   10380:                             } else {
                   10381:                                 @tocheck = @items;
                   10382:                             }
                   10383:                             foreach my $letter (@tocheck) {
                   10384:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10385:                                     if ($letter !~ /^[A-J]$/) {
                   10386:                                         $letter = $scantron_config->{'Qoff'};
                   10387:                                     }
                   10388:                                     $recorded{$part_id} .= $letter;
                   10389:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10390:                                     my $digit;
                   10391:                                     if ($letter !~ /^[A-J]$/) {
                   10392:                                         $digit = $scantron_config->{'Qoff'};
                   10393:                                     } else {
                   10394:                                         $digit = $lettdig->{$letter};
                   10395:                                     }
                   10396:                                     $recorded{$part_id} .= $digit;
                   10397:                                 }
                   10398:                             }
                   10399:                         } else {
                   10400:                             @tocheck = @items;
                   10401:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10402:                                 my $curr_sub = shift(@tocheck);
                   10403:                                 my $digit;
                   10404:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10405:                                     $digit = $lettdig->{$curr_sub}-1;
                   10406:                                 }
                   10407:                                 if ($curr_sub eq 'J') {
                   10408:                                     $digit += scalar($numletts);
                   10409:                                 }
                   10410:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10411:                                     if ($j == $digit) {
                   10412:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10413:                                     } else {
                   10414:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10415:                                     }
                   10416:                                 }
                   10417:                             }
                   10418:                         }
                   10419:                     }
                   10420:                 }
                   10421:             }
                   10422:         }
1.554     raeburn  10423:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10424:             if ($recorded{$part_id} eq '') {
                   10425:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10426:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10427:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10428:                     }
                   10429:                 }
                   10430:             }
                   10431:             $record .= $recorded{$part_id};
                   10432:         }
                   10433:     }
                   10434:     return ($counter,$record);
                   10435: }
                   10436: 
1.75      albertel 10437: #-------- end of section for handling grading scantron forms -------
                   10438: #
                   10439: #-------------------------------------------------------------------
                   10440: 
1.72      ng       10441: #-------------------------- Menu interface -------------------------
                   10442: #
1.614     www      10443: #--- Href with symb and command ---
                   10444: 
                   10445: sub href_symb_cmd {
                   10446:     my ($symb,$cmd)=@_;
1.669     raeburn  10447:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       10448: }
                   10449: 
1.443     banghart 10450: sub grading_menu {
1.608     www      10451:     my ($request,$symb) = @_;
1.443     banghart 10452:     if (!$symb) {return '';}
                   10453: 
                   10454:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      10455:                   'command'=>'individual');
1.538     schulted 10456:     
1.598     www      10457:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10458: 
                   10459:     $fields{'command'}='ungraded';
                   10460:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10461: 
                   10462:     $fields{'command'}='table';
                   10463:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10464: 
                   10465:     $fields{'command'}='all_for_one';
                   10466:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10467: 
1.621     www      10468:     $fields{'command'}='downloadfilesselect';
                   10469:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10470: 
1.443     banghart 10471:     $fields{'command'} = 'csvform';
1.538     schulted 10472:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10473:     
1.443     banghart 10474:     $fields{'command'} = 'processclicker';
1.538     schulted 10475:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10476:     
1.443     banghart 10477:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10478:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      10479: 
                   10480:     $fields{'command'} = 'initialverifyreceipt';
                   10481:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  10482: 
                   10483:     my %permissions;
                   10484:     if ($perm{'mgr'}) {
                   10485:         $permissions{'either'} = 'F';
                   10486:         $permissions{'mgr'} = 'F';
                   10487:     }
                   10488:     if ($perm{'vgr'}) {
                   10489:         $permissions{'either'} = 'F';
                   10490:         $permissions{'vgr'} = 'F';
                   10491:     }
                   10492: 
1.598     www      10493:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10494:             items =>[
1.598     www      10495:                         {	linktext => 'Select individual students to grade',
                   10496:                     		url => $url1a,
1.781     raeburn  10497:                     		permission => $permissions{'either'},
1.636     wenzelju 10498:                     		icon => 'grade_students.png',
1.598     www      10499:                     		linktitle => 'Grade current resource for a selection of students.'
                   10500:                         }, 
1.764     raeburn  10501:                         {       linktext => 'Grade ungraded submissions',
1.598     www      10502:                                 url => $url1b,
1.781     raeburn  10503:                                 permission => $permissions{'either'},
1.636     wenzelju 10504:                                 icon => 'ungrade_sub.png',
1.598     www      10505:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 10506:                         },
1.598     www      10507: 
                   10508:                         {       linktext => 'Grading table',
                   10509:                                 url => $url1c,
1.781     raeburn  10510:                                 permission => $permissions{'either'},
1.636     wenzelju 10511:                                 icon => 'grading_table.png',
1.598     www      10512:                                 linktitle => 'Grade current resource for all students.'
                   10513:                         },
1.615     www      10514:                         {       linktext => 'Grade page/folder for one student',
1.598     www      10515:                                 url => $url1d,
1.781     raeburn  10516:                                 permission => $permissions{'either'},
1.636     wenzelju 10517:                                 icon => 'grade_PageFolder.png',
1.598     www      10518:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      10519:                         },
                   10520:                         {       linktext => 'Download submissions',
                   10521:                                 url => $url1e,
1.781     raeburn  10522:                                 permission => $permissions{'either'},
1.636     wenzelju 10523:                                 icon => 'download_sub.png',
1.621     www      10524:                                 linktitle => 'Download all students submissions.'
1.598     www      10525:                         }]},
                   10526:                          { categorytitle=>'Automated Grading',
                   10527:                items =>[
                   10528: 
1.538     schulted 10529:                 	    {	linktext => 'Upload Scores',
                   10530:                     		url => $url2,
1.780     raeburn  10531:                     		permission => $permissions{'mgr'},
1.538     schulted 10532:                     		icon => 'uploadscores.png',
                   10533:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10534:                 	    },
                   10535:                 	    {	linktext => 'Process Clicker',
                   10536:                     		url => $url3,
1.780     raeburn  10537:                     		permission => $permissions{'mgr'},
1.538     schulted 10538:                     		icon => 'addClickerInfoFile.png',
                   10539:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10540:                 	    },
1.587     raeburn  10541:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10542:                     		url => $url4,
1.780     raeburn  10543:                     		permission => $permissions{'mgr'},
1.636     wenzelju 10544:                     		icon => 'bubblesheet.png',
1.648     bisitz   10545:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      10546:                 	    },
1.616     www      10547:                             {   linktext => 'Verify Receipt Number',
1.602     www      10548:                                 url => $url5,
1.780     raeburn  10549:                                 permission => $permissions{'either'},
1.636     wenzelju 10550:                                 icon => 'receipt_number.png',
1.602     www      10551:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10552:                             }
                   10553: 
1.538     schulted 10554:                     ]
                   10555:             });
                   10556: 
1.443     banghart 10557:     # Create the menu
                   10558:     my $Str;
1.445     banghart 10559:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10560:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      10561:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 10562: 
1.602     www      10563:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10564:     return $Str;    
                   10565: }
                   10566: 
1.598     www      10567: sub ungraded {
                   10568:     my ($request)=@_;
                   10569:     &submit_options($request);
                   10570: }
                   10571: 
1.599     www      10572: sub submit_options_sequence {
1.608     www      10573:     my ($request,$symb) = @_;
1.599     www      10574:     if (!$symb) {return '';}
1.600     www      10575:     &commonJSfunctions($request);
                   10576:     my $result;
1.599     www      10577: 
1.600     www      10578:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10579:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      10580:     $result.=&selectfield(0).
1.601     www      10581:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      10582:             <div>
                   10583:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10584:             </div>
                   10585:         </div>
                   10586:   </form>';
                   10587:     return $result;
                   10588: }
                   10589: 
                   10590: sub submit_options_table {
1.608     www      10591:     my ($request,$symb) = @_;
1.600     www      10592:     if (!$symb) {return '';}
1.599     www      10593:     &commonJSfunctions($request);
1.746     raeburn  10594:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      10595:     my $result;
                   10596: 
                   10597:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10598:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      10599: 
1.745     raeburn  10600:     $result.=&selectfield(1,$is_tool).
1.601     www      10601:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      10602:             <div>
                   10603:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10604:             </div>
                   10605:         </div>
                   10606:   </form>';
                   10607:     return $result;
                   10608: }
1.443     banghart 10609: 
1.621     www      10610: sub submit_options_download {
                   10611:     my ($request,$symb) = @_;
                   10612:     if (!$symb) {return '';}
                   10613: 
1.773     raeburn  10614:     my $res_error;
                   10615:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10616:         &response_type($symb,\$res_error);
                   10617:     if ($res_error) {
                   10618:         $request->print(&mt('An error occurred retrieving response types'));
                   10619:         return;
                   10620:     }
                   10621:     unless ($numessay) {
                   10622:         $request->print(&mt('No essayresponse items found'));
                   10623:         return;
                   10624:     }
                   10625:     my $table;
                   10626:     if (ref($partlist) eq 'ARRAY') {
                   10627:         if (scalar(@$partlist) > 1 ) {
                   10628:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   10629:         }
                   10630:     }
                   10631: 
1.746     raeburn  10632:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      10633:     &commonJSfunctions($request);
                   10634: 
                   10635:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  10636:                $table."\n".
                   10637:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      10638:     $result.='
                   10639: <h2>
1.750     raeburn  10640:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  10641: </h2>'.&selectfield(1,$is_tool).'
1.621     www      10642:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   10643:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10644:             </div>
                   10645:           </div>
1.600     www      10646: 
                   10647: 
1.621     www      10648:   </form>';
                   10649:     return $result;
                   10650: }
                   10651: 
1.443     banghart 10652: #--- Displays the submissions first page -------
                   10653: sub submit_options {
1.608     www      10654:     my ($request,$symb) = @_;
1.72      ng       10655:     if (!$symb) {return '';}
                   10656: 
1.746     raeburn  10657:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       10658:     &commonJSfunctions($request);
1.473     albertel 10659:     my $result;
1.533     bisitz   10660: 
1.72      ng       10661:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10662: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  10663:     $result.=&selectfield(1,$is_tool).'
1.601     www      10664:                 <input type="hidden" name="command" value="submission" /> 
                   10665: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10666:             </div>
                   10667:           </div>
                   10668:   </form>';
                   10669:     return $result;
                   10670: }
1.533     bisitz   10671: 
1.601     www      10672: sub selectfield {
1.745     raeburn  10673:    my ($full,$is_tool)=@_;
                   10674:    my %options;
                   10675:    if ($is_tool) {
                   10676:        %options =
                   10677:            (&transtatus_options,
                   10678:             'select_form_order' => ['yes','incorrect','all']);
                   10679:    } else {
                   10680:        %options = 
                   10681:            (&substatus_options,
                   10682:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10683:    }
1.782     raeburn  10684: 
                   10685:   #
                   10686:   # PrepareClasslist() needs to be called to avoid getting a sections list
                   10687:   # for a different course from the @Sections global in lonstatistics.pm, 
                   10688:   # populated by an earlier request.
                   10689:   #
                   10690:    &Apache::lonstatistics::PrepareClasslist();
                   10691: 
1.601     www      10692:    my $result='<div class="LC_columnSection">
1.537     harmsja  10693:   
1.533     bisitz   10694:     <fieldset>
                   10695:       <legend>
                   10696:        '.&mt('Sections').'
                   10697:       </legend>
1.601     www      10698:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10699:     </fieldset>
1.537     harmsja  10700:   
1.533     bisitz   10701:     <fieldset>
                   10702:       <legend>
                   10703:         '.&mt('Groups').'
                   10704:       </legend>
                   10705:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10706:     </fieldset>
1.537     harmsja  10707:   
1.533     bisitz   10708:     <fieldset>
                   10709:       <legend>
                   10710:         '.&mt('Access Status').'
                   10711:       </legend>
1.601     www      10712:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10713:     </fieldset>';
                   10714:     if ($full) {
1.745     raeburn  10715:         my $heading = &mt('Submission Status');
                   10716:         if ($is_tool) {
                   10717:             $heading = &mt('Transaction Status');
                   10718:         }
                   10719:         $result.='
1.533     bisitz   10720:     <fieldset>
                   10721:       <legend>
1.745     raeburn  10722:         '.$heading.'
1.601     www      10723:       </legend>'.
1.635     raeburn  10724:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      10725:    '</fieldset>';
                   10726:     }
                   10727:     $result.='</div><br />';
1.44      ng       10728:     return $result;
1.2       albertel 10729: }
                   10730: 
1.738     raeburn  10731: sub substatus_options {
                   10732:     return &Apache::lonlocal::texthash(
                   10733:                                       'yes'       => 'with submissions',
                   10734:                                       'queued'    => 'in grading queue',
                   10735:                                       'graded'    => 'with ungraded submissions',
                   10736:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10737:                                       'all'       => 'with any status',
                   10738:                                       );
1.738     raeburn  10739: }
                   10740: 
1.745     raeburn  10741: sub transtatus_options {
                   10742:     return &Apache::lonlocal::texthash(
                   10743:                                        'yes'       => 'with score transactions',
                   10744:                                        'incorrect' => 'with less than full credit',
                   10745:                                        'all'       => 'with any status',
                   10746:                                       );
                   10747: }
                   10748: 
1.285     albertel 10749: sub reset_perm {
                   10750:     undef(%perm);
                   10751: }
                   10752: 
                   10753: sub init_perm {
                   10754:     &reset_perm();
1.770     raeburn  10755:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 10756: 
                   10757: 	my $scope = $env{'request.course.id'};
                   10758: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10759: 
                   10760: 	    $scope .= '/'.$env{'request.course.sec'};
                   10761: 	    if ( $perm{$test_perm}=
                   10762: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10763: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10764: 	    } else {
                   10765: 		delete($perm{$test_perm});
                   10766: 	    }
1.285     albertel 10767: 	}
                   10768:     }
                   10769: }
                   10770: 
1.674     raeburn  10771: sub init_old_essays {
                   10772:     my ($symb,$apath,$adom,$aname) = @_;
                   10773:     if ($symb ne '') {
                   10774:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10775:         if (keys(%essays) > 0) {
                   10776:             $old_essays{$symb} = \%essays;
                   10777:         }
                   10778:     }
                   10779:     return;
                   10780: }
                   10781: 
                   10782: sub reset_old_essays {
                   10783:     undef(%old_essays);
                   10784: }
                   10785: 
1.400     www      10786: sub gather_clicker_ids {
1.408     albertel 10787:     my %clicker_ids;
1.400     www      10788: 
                   10789:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10790: 
                   10791:     # Set up a couple variables.
1.407     albertel 10792:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10793:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10794:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10795: 
1.407     albertel 10796:     foreach my $student (keys(%$classlist)) {
1.438     www      10797:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10798:         my $username = $classlist->{$student}->[$username_idx];
                   10799:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10800:         my $clickers =
1.408     albertel 10801: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10802:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10803:             $id=~s/^[\#0]+//;
1.421     www      10804:             $id=~s/[\-\:]//g;
1.407     albertel 10805:             if (exists($clicker_ids{$id})) {
1.408     albertel 10806: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10807:             } else {
1.408     albertel 10808: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10809:             }
                   10810:         }
                   10811:     }
1.407     albertel 10812:     return %clicker_ids;
1.400     www      10813: }
                   10814: 
1.402     www      10815: sub gather_adv_clicker_ids {
1.408     albertel 10816:     my %clicker_ids;
1.402     www      10817:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10818:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10819:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10820:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10821:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10822:             my ($puname,$pudom)=split(/\:/,$person);
                   10823:             my $clickers =
1.408     albertel 10824: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10825:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10826: 		$id=~s/^[\#0]+//;
1.421     www      10827:                 $id=~s/[\-\:]//g;
1.408     albertel 10828: 		if (exists($clicker_ids{$id})) {
                   10829: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10830: 		} else {
                   10831: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10832: 		}
1.405     www      10833:             }
1.402     www      10834:         }
                   10835:     }
1.407     albertel 10836:     return %clicker_ids;
1.402     www      10837: }
                   10838: 
1.413     www      10839: sub clicker_grading_parameters {
                   10840:     return ('gradingmechanism' => 'scalar',
                   10841:             'upfiletype' => 'scalar',
                   10842:             'specificid' => 'scalar',
                   10843:             'pcorrect' => 'scalar',
                   10844:             'pincorrect' => 'scalar');
                   10845: }
                   10846: 
1.400     www      10847: sub process_clicker {
1.608     www      10848:     my ($r,$symb)=@_;
1.400     www      10849:     if (!$symb) {return '';}
                   10850:     my $result=&checkforfile_js();
1.632     www      10851:     $result.=&Apache::loncommon::start_data_table().
                   10852:              &Apache::loncommon::start_data_table_header_row().
                   10853:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10854:              &Apache::loncommon::end_data_table_header_row().
                   10855:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10856: # Attempt to restore parameters from last session, set defaults if not present
                   10857:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10858:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10859:                                                  \%Saveable_Parameters);
                   10860:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10861:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10862:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10863:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10864: 
                   10865:     my %checked;
1.521     www      10866:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10867:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10868:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10869:        }
                   10870:     }
                   10871: 
1.632     www      10872:     my $upload=&mt("Evaluate File");
1.400     www      10873:     my $type=&mt("Type");
1.402     www      10874:     my $attendance=&mt("Award points just for participation");
                   10875:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10876:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10877:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10878:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10879:     my $pcorrect=&mt("Percentage points for correct solution");
                   10880:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10881:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10882: 						   {'iclicker' => 'i>clicker',
1.666     www      10883:                                                     'interwrite' => 'interwrite PRS',
                   10884:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10885:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10886:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10887: function sanitycheck() {
                   10888: // Accept only integer percentages
                   10889:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10890:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10891: // Find out grading choice
                   10892:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10893:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10894:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10895:       }
                   10896:    }
                   10897: // By default, new choice equals user selection
                   10898:    newgradingchoice=gradingchoice;
                   10899: // Not good to give more points for false answers than correct ones
                   10900:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10901:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10902:    }
                   10903: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10904:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10905:       document.forms.gradesupload.pcorrect.value=100;
                   10906:       document.forms.gradesupload.pincorrect.value=100;
                   10907:    }
                   10908: // If the values are different, cannot be attendance only
                   10909:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10910:        (gradingchoice=='attendance')) {
                   10911:        newgradingchoice='personnel';
                   10912:    }
                   10913: // Change grading choice to new one
                   10914:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10915:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10916:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10917:       } else {
                   10918:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10919:       }
                   10920:    }
                   10921: // Remember the old state
                   10922:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10923: }
1.597     wenzelju 10924: ENDUPFORM
                   10925:     $result.= <<ENDUPFORM;
1.400     www      10926: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10927: <input type="hidden" name="symb" value="$symb" />
                   10928: <input type="hidden" name="command" value="processclickerfile" />
                   10929: <input type="file" name="upfile" size="50" />
                   10930: <br /><label>$type: $selectform</label>
1.632     www      10931: ENDUPFORM
                   10932:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10933:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10934:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10935: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10936: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10937: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10938: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10939: <br />&nbsp;&nbsp;&nbsp;
                   10940: <input type="text" name="givenanswer" size="50" />
1.413     www      10941: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10942: ENDGRADINGFORM
1.766     raeburn  10943:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      10944:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10945:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10946: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10947: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  10948: </form>
1.632     www      10949: ENDPERCFORM
                   10950:     $result.='</td>'.
                   10951:              &Apache::loncommon::end_data_table_row().
                   10952:              &Apache::loncommon::end_data_table();
1.400     www      10953:     return $result;
                   10954: }
                   10955: 
                   10956: sub process_clicker_file {
1.766     raeburn  10957:     my ($r,$symb) = @_;
1.400     www      10958:     if (!$symb) {return '';}
1.413     www      10959: 
                   10960:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10961:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10962:                                               \%Saveable_Parameters);
1.598     www      10963:     my $result='';
1.404     www      10964:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10965: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10966: 	return $result;
1.404     www      10967:     }
1.522     www      10968:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10969:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10970:         return $result;
1.521     www      10971:     }
1.522     www      10972:     my $foundgiven=0;
1.521     www      10973:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10974:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10975:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10976:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10977:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10978:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10979:         $foundgiven=$#answers+1;
1.521     www      10980:     }
1.407     albertel 10981:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10982:     my %correct_ids;
1.404     www      10983:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10984: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10985:     }
                   10986:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10987: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10988: 	   $correct_id=~tr/a-z/A-Z/;
                   10989: 	   $correct_id=~s/\s//gs;
                   10990: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10991:            $correct_id=~s/[\-\:]//g;
1.414     www      10992:            if ($correct_id) {
                   10993: 	      $correct_ids{$correct_id}='specified';
                   10994:            }
                   10995:         }
1.400     www      10996:     }
1.404     www      10997:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10998: 	$result.=&mt('Score based on attendance only');
1.521     www      10999:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      11000:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      11001:     } else {
1.408     albertel 11002: 	my $number=0;
1.411     www      11003: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 11004: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      11005: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 11006: 	    if ($correct_ids{$id} eq 'specified') {
                   11007: 		$result.=&mt('specified');
                   11008: 	    } else {
                   11009: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   11010: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   11011: 	    }
                   11012: 	    $number++;
                   11013: 	}
1.411     www      11014:         $result.="</p>\n";
1.710     bisitz   11015:         if ($number==0) {
                   11016:             $result .=
                   11017:                  &Apache::lonhtmlcommon::confirm_success(
                   11018:                      &mt('No IDs found to determine correct answer'),1);
                   11019:             return $result;
                   11020:         }
1.404     www      11021:     }
1.405     www      11022:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   11023:         $result .=
                   11024:             &Apache::lonhtmlcommon::confirm_success(
                   11025:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   11026:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      11027:         return $result;
1.405     www      11028:     }
1.760     raeburn  11029:     my $mimetype;
                   11030:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   11031:         my $mm = new File::MMagic;
                   11032:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   11033:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   11034:             $result.= '<p>'.
                   11035:                 &Apache::lonhtmlcommon::confirm_success(
                   11036:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   11037:             return $result;
                   11038:         }
                   11039:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   11040:         $result .= '<p>'.
                   11041:             &Apache::lonhtmlcommon::confirm_success(
                   11042:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   11043:         return $result;
                   11044:     }
1.410     www      11045: 
                   11046: # Were able to get all the info needed, now analyze the file
                   11047: 
1.411     www      11048:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 11049:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      11050:     $result.=&Apache::loncommon::start_data_table().
                   11051:              &Apache::loncommon::start_data_table_header_row().
                   11052:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   11053:              &Apache::loncommon::end_data_table_header_row().
                   11054:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   11055: <td>
1.410     www      11056: <form method="post" action="/adm/grades" name="clickeranalysis">
                   11057: <input type="hidden" name="symb" value="$symb" />
                   11058: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      11059: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   11060: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   11061: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      11062: ENDHEADER
1.522     www      11063:     if ($env{'form.gradingmechanism'} eq 'given') {
                   11064:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   11065:     } 
1.408     albertel 11066:     my %responses;
                   11067:     my @questiontitles;
1.405     www      11068:     my $errormsg='';
                   11069:     my $number=0;
                   11070:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  11071:         if ($mimetype eq 'text/plain') {
                   11072:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   11073:         } elsif ($mimetype eq 'text/html') {
                   11074:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   11075:         }
                   11076:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      11077:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  11078:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      11079:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   11080:     }
1.411     www      11081:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   11082:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   11083:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   11084:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   11085:              '<br />';
1.522     www      11086:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   11087:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      11088:        return $result;
1.522     www      11089:     } 
1.414     www      11090: # Remember Question Titles
                   11091: # FIXME: Possibly need delimiter other than ":"
                   11092:     for (my $i=0;$i<$number;$i++) {
                   11093:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   11094:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   11095:     }
1.411     www      11096:     my $correct_count=0;
                   11097:     my $student_count=0;
                   11098:     my $unknown_count=0;
1.414     www      11099: # Match answers with usernames
                   11100: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 11101:     foreach my $id (keys(%responses)) {
1.410     www      11102:        if ($correct_ids{$id}) {
1.414     www      11103:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      11104:           $correct_count++;
1.410     www      11105:        } elsif ($clicker_ids{$id}) {
1.437     www      11106:           if ($clicker_ids{$id}=~/\,/) {
                   11107: # More than one user with the same clicker!
1.632     www      11108:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11109:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11110:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      11111:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11112:                            "<select name='multi".$id."'>";
                   11113:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   11114:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   11115:              }
                   11116:              $result.='</select>';
                   11117:              $unknown_count++;
                   11118:           } else {
                   11119: # Good: found one and only one user with the right clicker
                   11120:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   11121:              $student_count++;
                   11122:           }
1.410     www      11123:        } else {
1.632     www      11124:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11125:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11126:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      11127:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11128:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   11129:                    "\n".&mt("Domain").": ".
                   11130:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  11131:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      11132:           $unknown_count++;
1.410     www      11133:        }
1.405     www      11134:     }
1.412     www      11135:     $result.='<hr />'.
                   11136:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      11137:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      11138:        if ($correct_count==0) {
1.696     bisitz   11139:           $errormsg.="Found no correct answers for grading!";
1.412     www      11140:        } elsif ($correct_count>1) {
1.414     www      11141:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      11142:        }
                   11143:     }
1.428     www      11144:     if ($number<1) {
                   11145:        $errormsg.="Found no questions.";
                   11146:     }
1.412     www      11147:     if ($errormsg) {
                   11148:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   11149:     } else {
                   11150:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   11151:     }
1.632     www      11152:     $result.='</form></td>'.
                   11153:              &Apache::loncommon::end_data_table_row().
                   11154:              &Apache::loncommon::end_data_table();
1.614     www      11155:     return $result;
1.400     www      11156: }
                   11157: 
1.405     www      11158: sub iclicker_eval {
1.406     www      11159:     my ($questiontitles,$responses)=@_;
1.405     www      11160:     my $number=0;
                   11161:     my $errormsg='';
                   11162:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      11163:         my %components=&Apache::loncommon::record_sep($line);
                   11164:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 11165: 	if ($entries[0] eq 'Question') {
                   11166: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   11167: 		$$questiontitles[$number]=$entries[$i];
                   11168: 		$number++;
                   11169: 	    }
                   11170: 	}
                   11171: 	if ($entries[0]=~/^\#/) {
                   11172: 	    my $id=$entries[0];
                   11173: 	    my @idresponses;
                   11174: 	    $id=~s/^[\#0]+//;
                   11175: 	    for (my $i=0;$i<$number;$i++) {
                   11176: 		my $idx=3+$i*6;
1.644     www      11177:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 11178: 		push(@idresponses,$entries[$idx]);
                   11179: 	    }
                   11180: 	    $$responses{$id}=join(',',@idresponses);
                   11181: 	}
1.405     www      11182:     }
                   11183:     return ($errormsg,$number);
                   11184: }
                   11185: 
1.760     raeburn  11186: sub iclickerxml_eval {
                   11187:     my ($questiontitles,$responses)=@_;
                   11188:     my $number=0;
                   11189:     my $errormsg='';
                   11190:     my @state;
                   11191:     my %respbyid;
                   11192:     my $p = HTML::Parser->new
                   11193:     (
                   11194:         xml_mode => 1,
                   11195:         start_h =>
                   11196:             [sub {
                   11197:                  my ($tagname,$attr) = @_;
                   11198:                  push(@state,$tagname);
                   11199:                  if ("@state" eq "ssn p") {
                   11200:                      my $title = $attr->{qn};
                   11201:                      $title =~ s/(^\s+|\s+$)//g;
                   11202:                      $questiontitles->[$number]=$title;
                   11203:                  } elsif ("@state" eq "ssn p v") {
                   11204:                      my $id = $attr->{id};
                   11205:                      my $entry = $attr->{ans};
                   11206:                      $id=~s/^[\#0]+//;
                   11207:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   11208:                      $respbyid{$id}[$number] = $entry;
                   11209:                  }
                   11210:             }, "tagname, attr"],
                   11211:          end_h =>
                   11212:                [sub {
                   11213:                    my ($tagname) = @_;
                   11214:                    if ("@state" eq "ssn p") {
                   11215:                        $number++;
                   11216:                    }
                   11217:                    pop(@state);
                   11218:                 }, "tagname"],
                   11219:     );
                   11220: 
                   11221:     $p->parse($env{'form.upfile'});
                   11222:     $p->eof;
                   11223:     foreach my $id (keys(%respbyid)) {
                   11224:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   11225:     }
                   11226:     return ($errormsg,$number);
                   11227: }
                   11228: 
1.419     www      11229: sub interwrite_eval {
                   11230:     my ($questiontitles,$responses)=@_;
                   11231:     my $number=0;
                   11232:     my $errormsg='';
1.420     www      11233:     my $skipline=1;
                   11234:     my $questionnumber=0;
                   11235:     my %idresponses=();
1.419     www      11236:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11237:         my %components=&Apache::loncommon::record_sep($line);
                   11238:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      11239:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   11240:         if ($entries[1] eq 'Response') { $skipline=1; }
                   11241:         next if $skipline;
                   11242:         if ($entries[0]!=$questionnumber) {
                   11243:            $questionnumber=$entries[0];
                   11244:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   11245:            $number++;
1.419     www      11246:         }
1.420     www      11247:         my $id=$entries[4];
                   11248:         $id=~s/^[\#0]+//;
1.421     www      11249:         $id=~s/^v\d*\://i;
                   11250:         $id=~s/[\-\:]//g;
1.420     www      11251:         $idresponses{$id}[$number]=$entries[6];
                   11252:     }
1.524     raeburn  11253:     foreach my $id (keys(%idresponses)) {
1.420     www      11254:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   11255:        $$responses{$id}=~s/^\s*\,//;
1.419     www      11256:     }
                   11257:     return ($errormsg,$number);
                   11258: }
                   11259: 
1.666     www      11260: sub turning_eval {
                   11261:     my ($questiontitles,$responses)=@_;
                   11262:     my $number=0;
                   11263:     my $errormsg='';
                   11264:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11265:         my %components=&Apache::loncommon::record_sep($line);
                   11266:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   11267:         if ($#entries>$number) { $number=$#entries; }
                   11268:         my $id=$entries[0];
                   11269:         my @idresponses;
                   11270:         $id=~s/^[\#0]+//;
                   11271:         unless ($id) { next; }
                   11272:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   11273:             $entries[$idx]=~s/\,/\;/g;
                   11274:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   11275:             push(@idresponses,$entries[$idx]);
                   11276:         }
                   11277:         $$responses{$id}=join(',',@idresponses);
                   11278:     }
                   11279:     for (my $i=1; $i<=$number; $i++) {
                   11280:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   11281:     }
                   11282:     return ($errormsg,$number);
                   11283: }
                   11284: 
                   11285: 
1.414     www      11286: sub assign_clicker_grades {
1.766     raeburn  11287:     my ($r,$symb) = @_;
1.414     www      11288:     if (!$symb) {return '';}
1.416     www      11289: # See which part we are saving to
1.582     raeburn  11290:     my $res_error;
                   11291:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   11292:     if ($res_error) {
                   11293:         return &navmap_errormsg();
                   11294:     }
1.416     www      11295: # FIXME: This should probably look for the first handgradeable part
                   11296:     my $part=$$partlist[0];
                   11297: # Start screen output
1.766     raeburn  11298:     my $result = &Apache::loncommon::start_data_table().
                   11299:                  &Apache::loncommon::start_data_table_header_row().
                   11300:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   11301:                  &Apache::loncommon::end_data_table_header_row().
                   11302:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11303: # Get correct result
                   11304: # FIXME: Possibly need delimiter other than ":"
                   11305:     my @correct=();
1.415     www      11306:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11307:     my $number=$env{'form.number'};
                   11308:     if ($gradingmechanism ne 'attendance') {
1.414     www      11309:        foreach my $key (keys(%env)) {
                   11310:           if ($key=~/^form\.correct\:/) {
                   11311:              my @input=split(/\,/,$env{$key});
                   11312:              for (my $i=0;$i<=$#input;$i++) {
                   11313:                  if (($correct[$i]) && ($input[$i]) &&
                   11314:                      ($correct[$i] ne $input[$i])) {
                   11315:                     $result.='<br /><span class="LC_warning">'.
                   11316:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11317:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      11318:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11319:                     $correct[$i]=$input[$i];
                   11320:                  }
                   11321:              }
                   11322:           }
                   11323:        }
1.415     www      11324:        for (my $i=0;$i<$number;$i++) {
1.644     www      11325:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11326:              $result.='<br /><span class="LC_error">'.
                   11327:                       &mt('No correct result given for question "[_1]"!',
                   11328:                           $env{'form.question:'.$i}).'</span>';
                   11329:           }
                   11330:        }
1.644     www      11331:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11332:     }
                   11333: # Start grading
1.415     www      11334:     my $pcorrect=$env{'form.pcorrect'};
                   11335:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11336:     my $storecount=0;
1.632     www      11337:     my %users=();
1.415     www      11338:     foreach my $key (keys(%env)) {
1.420     www      11339:        my $user='';
1.415     www      11340:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11341:           $user=$1;
                   11342:        }
                   11343:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11344:           my $id=$1;
                   11345:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11346:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11347:           } elsif ($env{'form.multi'.$id}) {
                   11348:              $user=$env{'form.multi'.$id};
1.420     www      11349:           }
                   11350:        }
1.632     www      11351:        if ($user) {
                   11352:           if ($users{$user}) {
                   11353:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   11354:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      11355:                       '</span><br />';
                   11356:           }
                   11357:           $users{$user}=1; 
1.415     www      11358:           my @answer=split(/\,/,$env{$key});
                   11359:           my $sum=0;
1.522     www      11360:           my $realnumber=$number;
1.415     www      11361:           for (my $i=0;$i<$number;$i++) {
1.576     www      11362:              if  ($correct[$i] eq '-') {
                   11363:                 $realnumber--;
1.766     raeburn  11364:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11365:                 if ($gradingmechanism eq 'attendance') {
                   11366:                    $sum+=$pcorrect;
1.576     www      11367:                 } elsif ($correct[$i] eq '*') {
1.522     www      11368:                    $sum+=$pcorrect;
1.415     www      11369:                 } else {
1.644     www      11370: # We actually grade if correct or not
                   11371:                    my $increment=$pincorrect;
                   11372: # Special case: numerical answer "0"
                   11373:                    if ($correct[$i] eq '0') {
                   11374:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11375:                          $increment=$pcorrect;
                   11376:                       }
                   11377: # General numerical answer, both evaluate to something non-zero
                   11378:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11379:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11380:                          $increment=$pcorrect;
                   11381:                       }
                   11382: # Must be just alphanumeric
                   11383:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11384:                       $increment=$pcorrect;
1.415     www      11385:                    }
1.644     www      11386:                    $sum+=$increment;
1.415     www      11387:                 }
                   11388:              }
                   11389:           }
1.522     www      11390:           my $ave=$sum/(100*$realnumber);
1.416     www      11391: # Store
                   11392:           my ($username,$domain)=split(/\:/,$user);
                   11393:           my %grades=();
                   11394:           $grades{"resource.$part.solved"}='correct_by_override';
                   11395:           $grades{"resource.$part.awarded"}=$ave;
                   11396:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11397:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11398:                                                  $env{'request.course.id'},
                   11399:                                                  $domain,$username);
                   11400:           if ($returncode ne 'ok') {
                   11401:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11402:           } else {
                   11403:              $storecount++;
                   11404:           }
1.415     www      11405:        }
                   11406:     }
                   11407: # We are done
1.549     hauer    11408:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      11409:              '</td>'.
                   11410:              &Apache::loncommon::end_data_table_row().
                   11411:              &Apache::loncommon::end_data_table();
1.614     www      11412:     return $result;
1.414     www      11413: }
                   11414: 
1.582     raeburn  11415: sub navmap_errormsg {
                   11416:     return '<div class="LC_error">'.
                   11417:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11418:            &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  11419:            '</div>';
                   11420: }
1.607     droeschl 11421: 
1.609     www      11422: sub startpage {
1.777     raeburn  11423:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  11424:     my %args;
                   11425:     if ($onload) {
                   11426:          my %loaditems = (
                   11427:                         'onload' => $onload,
                   11428:                       );
                   11429:          $args{'add_entries'} = \%loaditems;
                   11430:     }
1.671     raeburn  11431:     if ($nomenu) {
1.754     raeburn  11432:         $args{'only_body'} = 1; 
1.777     raeburn  11433:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  11434:     } else {
1.785     raeburn  11435:         if ($env{'request.course.id'}) { 
                   11436:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   11437:         }
1.754     raeburn  11438:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  11439:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  11440:         if ($env{'request.course.id'}) {
                   11441:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   11442:         }
1.671     raeburn  11443:     }
1.613     www      11444:     unless ($nodisplayflag) {
1.773     raeburn  11445:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      11446:     }
1.607     droeschl 11447: }
1.582     raeburn  11448: 
1.622     www      11449: sub select_problem {
                   11450:     my ($r)=@_;
1.632     www      11451:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  11452:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      11453:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11454:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11455: }
                   11456: 
1.1       albertel 11457: sub handler {
1.41      ng       11458:     my $request=$_[0];
1.434     albertel 11459:     &reset_caches();
1.646     raeburn  11460:     if ($request->header_only) {
                   11461:         &Apache::loncommon::content_type($request,'text/html');
                   11462:         $request->send_http_header;
                   11463:         return OK;
                   11464:     }
                   11465:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   11466: 
1.664     raeburn  11467: # see what command we need to execute
                   11468: 
                   11469:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11470:     my $command=$commands[0];
                   11471: 
1.646     raeburn  11472:     &init_perm();
                   11473:     if (!$env{'request.course.id'}) {
1.664     raeburn  11474:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11475:                 ($command =~ /^scantronupload/)) {
                   11476:             # Not in a course.
                   11477:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11478:             return HTTP_NOT_ACCEPTABLE;
                   11479:         }
1.646     raeburn  11480:     } elsif (!%perm) {
                   11481:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  11482:         return OK;
1.41      ng       11483:     }
1.646     raeburn  11484:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       11485:     $request->send_http_header;
1.646     raeburn  11486: 
1.160     albertel 11487:     if ($#commands > 0) {
                   11488: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11489:     }
1.608     www      11490: 
                   11491: # see what the symb is
                   11492: 
                   11493:     my $symb=$env{'form.symb'};
                   11494:     unless ($symb) {
                   11495:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11496:        $symb=&Apache::lonnet::symbread($url);
                   11497:     }
1.646     raeburn  11498:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      11499: 
1.513     foxr     11500:     $ssi_error = 0;
1.637     www      11501:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      11502: #
1.637     www      11503: # Not called from a resource, but inside a course
1.601     www      11504: #    
1.622     www      11505:         &startpage($request,undef,[],1,1);
                   11506:         &select_problem($request);
1.41      ng       11507:     } else {
1.104     albertel 11508: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  11509:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  11510:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11511:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11512:                     &choose_task_version_form($symb,$env{'form.student'},
                   11513:                                               $env{'form.userdom'});
                   11514:             }
1.773     raeburn  11515:             my $divforres;
                   11516:             if ($env{'form.student'} eq '') {
                   11517:                 $js .= &part_selector_js();
                   11518:                 $onload = "toggleParts('gradesub');";
                   11519:             } else {
                   11520:                 $divforres = 1;
                   11521:             }
1.778     raeburn  11522:             my $head_extra = $js;
                   11523:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11524:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11525:                 if ($csslinks) {
                   11526:                     $head_extra .= "\n$csslinks";
                   11527:                 }
                   11528:             }
1.777     raeburn  11529:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   11530:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  11531:             if ($versionform) {
1.775     raeburn  11532:                 if ($divforres) {
                   11533:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   11534:                 }
1.671     raeburn  11535:                 $request->print($versionform);
                   11536:             }
1.773     raeburn  11537: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  11538:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11539:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11540:                 &choose_task_version_form($symb,$env{'form.student'},
                   11541:                                           $env{'form.userdom'},
                   11542:                                           $env{'form.inhibitmenu'});
1.778     raeburn  11543:             my $head_extra = $js;
                   11544:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11545:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11546:                 if ($csslinks) {
                   11547:                     $head_extra .= "\n$csslinks";
                   11548:                 }
                   11549:             }
1.777     raeburn  11550:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   11551:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  11552:             if ($versionform) {
                   11553:                 $request->print($versionform);
                   11554:             }
                   11555:             $request->print('<br clear="all" />');
                   11556:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 11557: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      11558:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11559:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      11560: 	    &pickStudentPage($request,$symb);
1.103     albertel 11561: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  11562:             my $csslinks;
                   11563:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11564:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  11565:             }
1.615     www      11566:             &startpage($request,$symb,
                   11567:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11568:                                        {href=>'',text=>'Select student'},
1.777     raeburn  11569:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      11570: 	    &displayPage($request,$symb);
1.104     albertel 11571: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      11572:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11573:                                        {href=>'',text=>'Select student'},
                   11574:                                        {href=>'',text=>'Grade student'},
                   11575:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      11576: 	    &updateGradeByPage($request,$symb);
1.104     albertel 11577: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  11578:             my $csslinks;
                   11579:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11580:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11581:             }
1.619     www      11582:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  11583:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      11584: 	    &processGroup($request,$symb);
1.104     albertel 11585: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      11586:             &startpage($request,$symb);
                   11587: 	    $request->print(&grading_menu($request,$symb));
1.598     www      11588: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      11589:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      11590: 	    $request->print(&submit_options($request,$symb));
1.598     www      11591:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  11592:             my $js = &part_selector_js();
                   11593:             my $onload = "toggleParts('gradesub');";
                   11594:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11595:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      11596:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      11597:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      11598:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      11599:             $request->print(&submit_options_table($request,$symb));
1.598     www      11600:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      11601:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      11602:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 11603: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      11604:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      11605: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 11606: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      11607:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11608:                                        {href=>'',text=>'Store grades'}]);
1.608     www      11609: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 11610: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      11611:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11612:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11613:                                                                              text=>"Modify grades"},
                   11614:                                        {href=>'', text=>"Store grades"}]);
1.608     www      11615: 	    $request->print(&editgrades($request,$symb));
1.602     www      11616:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      11617:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      11618:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 11619: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      11620:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11621:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      11622: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      11623:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      11624:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      11625:             $request->print(&process_clicker($request,$symb));
1.400     www      11626:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      11627:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11628:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      11629:             $request->print(&process_clicker_file($request,$symb));
1.414     www      11630:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      11631:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11632:                                        {href=>'', text=>'Process clicker file'},
                   11633:                                        {href=>'', text=>'Store grades'}]);
1.608     www      11634:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 11635: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      11636:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11637: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 11638: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      11639:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11640: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 11641: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      11642:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11643: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 11644: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 11645: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      11646:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11647: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       11648: 	    } else {
1.257     albertel 11649: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11650: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       11651: 		} else {
1.257     albertel 11652: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       11653: 		}
1.627     www      11654:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11655: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       11656: 	    }
1.246     albertel 11657: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      11658:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11659: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 11660: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  11661:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11662:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      11663: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 11664:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      11665:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11666:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 11667: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      11668:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11669: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 11670: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      11671:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11672: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 11673:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  11674:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  11675:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11676:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      11677:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 11678:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  11679:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      11680:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11681:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  11682:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      11683:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11684:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  11685:         } elsif ($command eq 'scantronupload_delete' &&
                   11686:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   11687:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11688:             &scantron_upload_delete($request,$symb);
1.523     raeburn  11689:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      11690:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      11691:             $request->print(&checkscantron_results($request,$symb));
                   11692:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  11693:             my $js = &part_selector_js();
                   11694:             my $onload = "toggleParts('gradingMenu');";
                   11695:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11696:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      11697:             $request->print(&submit_options_download($request,$symb));
                   11698:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11699:             &startpage($request,$symb,
                   11700:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  11701:     {href=>'', text=>'Download submitted files'}],
                   11702:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  11703:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      11704:             &submit_download_link($request,$symb);
1.106     albertel 11705: 	} elsif ($command) {
1.620     www      11706:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   11707: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 11708: 	}
1.2       albertel 11709:     }
1.513     foxr     11710:     if ($ssi_error) {
                   11711: 	&ssi_print_error($request);
                   11712:     }
1.671     raeburn  11713:     if ($env{'form.inhibitmenu'}) {
                   11714:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  11715:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  11716:         &Apache::lonquickgrades::endGradeScreen($request);
                   11717:     }
1.434     albertel 11718:     &reset_caches();
1.646     raeburn  11719:     return OK;
1.44      ng       11720: }
                   11721: 
1.1       albertel 11722: 1;
                   11723: 
1.13      albertel 11724: __END__;
1.531     jms      11725: 
                   11726: 
                   11727: =head1 NAME
                   11728: 
                   11729: Apache::grades
                   11730: 
                   11731: =head1 SYNOPSIS
                   11732: 
                   11733: Handles the viewing of grades.
                   11734: 
                   11735: This is part of the LearningOnline Network with CAPA project
                   11736: described at http://www.lon-capa.org.
                   11737: 
                   11738: =head1 OVERVIEW
                   11739: 
                   11740: Do an ssi with retries:
1.715     bisitz   11741: While I'd love to factor out this with the version in lonprintout,
1.531     jms      11742: 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
                   11743: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11744: 
                   11745: At least the logic that drives this has been pulled out into loncommon.
                   11746: 
                   11747: 
                   11748: 
                   11749: ssi_with_retries - Does the server side include of a resource.
                   11750:                      if the ssi call returns an error we'll retry it up to
                   11751:                      the number of times requested by the caller.
1.715     bisitz   11752:                      If we still have a problem, no text is appended to the
1.531     jms      11753:                      output and we set some global variables.
                   11754:                      to indicate to the caller an SSI error occurred.  
                   11755:                      All of this is supposed to deal with the issues described
1.715     bisitz   11756:                      in LON-CAPA BZ 5631 see:
1.531     jms      11757:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11758:                      by informing the user that this happened.
                   11759: 
                   11760: Parameters:
                   11761:   resource   - The resource to include.  This is passed directly, without
                   11762:                interpretation to lonnet::ssi.
                   11763:   form       - The form hash parameters that guide the interpretation of the resource
                   11764:                
                   11765:   retries    - Number of retries allowed before giving up completely.
                   11766: Returns:
                   11767:   On success, returns the rendered resource identified by the resource parameter.
                   11768: Side Effects:
                   11769:   The following global variables can be set:
                   11770:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11771:                               It is up to the caller to initialize this to false
                   11772:                               if desired.
                   11773:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11774:                               of the resource that could not be rendered by the ssi
                   11775:                               call.
                   11776:    ssi_error_message   - The error string fetched from the ssi response
                   11777:                               in the event of an error.
                   11778: 
                   11779: 
                   11780: =head1 HANDLER SUBROUTINE
                   11781: 
                   11782: ssi_with_retries()
                   11783: 
                   11784: =head1 SUBROUTINES
                   11785: 
                   11786: =over
                   11787: 
1.671     raeburn  11788: =head1 Routines to display previous version of a Task for a specific student
                   11789: 
                   11790: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   11791: can receive another opportunity. Access to tasks is slot-based. If a slot
                   11792: requires a proctor to check-in the student, a new version of the Task will
                   11793: be created when the student is checked in to the new opportunity.
                   11794: 
                   11795: If a particular student has tried two or more versions of a particular task,
                   11796: the submission screen provides a user with vgr privileges (e.g., a Course
                   11797: Coordinator) the ability to display a previous version worked on by the
                   11798: student.  By default, the current version is displayed. If a previous version
                   11799: has been selected for display, submission data are only shown that pertain
                   11800: to that particular version, and the interface to submit grades is not shown.
                   11801: 
                   11802: =over 4
                   11803: 
                   11804: =item show_previous_task_version()
                   11805: 
                   11806: Displays a specified version of a student's Task, as the student sees it.
                   11807: 
                   11808: Inputs: 2
                   11809:         request - request object
                   11810:         symb    - unique symb for current instance of resource
                   11811: 
                   11812: Output: None.
                   11813: 
                   11814: Side Effects: calls &show_problem() to print version of Task, with
                   11815:               version contained in form item: $env{'form.previousversion'}
                   11816: 
                   11817: =item choose_task_version_form()
                   11818: 
                   11819: Displays a web form used to select which version of a student's view of a
                   11820: Task should be displayed.  Either launches a pop-up window, or replaces
                   11821: content in existing pop-up, or replaces page in main window.
                   11822: 
                   11823: Inputs: 4
                   11824:         symb    - unique symb for current instance of resource
                   11825:         uname   - username of student
                   11826:         udom    - domain of student
                   11827:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11828:                   breadcrumbs etc., are displayed
                   11829: 
                   11830: Output: 4
                   11831:         current   - student's current version
                   11832:         displayed - student's version being displayed
                   11833:         result    - scalar containing HTML for web form used to switch to
                   11834:                     a different version (or a link to close window, if pop-up).
                   11835:         js        - javascript for processing selection in versions web form
                   11836: 
                   11837: Side Effects: None.
                   11838: 
                   11839: =item previous_display_javascript()
                   11840: 
                   11841: Inputs: 2
                   11842:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11843:                   breadcrumbs etc., are displayed.
                   11844:         current - student's current version number.
                   11845: 
                   11846: Output: 1
                   11847:         js      - javascript for processing selection in versions web form.
                   11848: 
                   11849: Side Effects: None.
                   11850: 
                   11851: =back
                   11852: 
                   11853: =head1 Routines to process bubblesheet data.
                   11854: 
                   11855: =over 4
                   11856: 
1.531     jms      11857: =item scantron_get_correction() : 
                   11858: 
                   11859:    Builds the interface screen to interact with the operator to fix a
                   11860:    specific error condition in a specific scanline
                   11861: 
                   11862:  Arguments:
                   11863:     $r           - Apache request object
                   11864:     $i           - number of the current scanline
                   11865:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  11866:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11867:     $line        - full contents of the current scanline
                   11868:     $error       - error condition, valid values are
                   11869:                    'incorrectCODE', 'duplicateCODE',
                   11870:                    'doublebubble', 'missingbubble',
                   11871:                    'duplicateID', 'incorrectID'
                   11872:     $arg         - extra information needed
                   11873:        For errors:
                   11874:          - duplicateID   - paper number that this studentID was seen before on
                   11875:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11876:                            seen on before
                   11877:          - incorrectCODE - current incorrect CODE 
                   11878:          - doublebubble  - array ref of the bubble lines that have double
                   11879:                            bubble errors
                   11880:          - missingbubble - array ref of the bubble lines that have missing
                   11881:                            bubble errors
                   11882: 
1.691     raeburn  11883:    $randomorder - True if exam folder has randomorder set
                   11884:    $randompick  - True if exam folder has randompick set
                   11885:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11886:                      for current line to question number used for same question
                   11887:                      in "Master Seqence" (as seen by Course Coordinator).
                   11888:    $startline   - Reference to hash where key is question number (0 is first)
                   11889:                   and value is number of first bubble line for current student
                   11890:                   or code-based randompick and/or randomorder.
                   11891: 
                   11892: 
                   11893: 
1.531     jms      11894: =item  scantron_get_maxbubble() : 
                   11895: 
1.582     raeburn  11896:    Arguments:
                   11897:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11898:                       failure to retrieve a navmap object.
                   11899:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11900:        calling routine should trap the error condition and display the warning
                   11901:        found in &navmap_errormsg().
                   11902: 
1.649     raeburn  11903:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11904: 
1.531     jms      11905:    Returns the maximum number of bubble lines that are expected to
                   11906:    occur. Does this by walking the selected sequence rendering the
                   11907:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11908:    for what the current value of the problem counter is.
                   11909: 
                   11910:    Caches the results to $env{'form.scantron_maxbubble'},
                   11911:    $env{'form.scantron.bubble_lines.n'}, 
                   11912:    $env{'form.scantron.first_bubble_line.n'} and
                   11913:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11914:    which are the total number of bubble lines, the number of bubble
1.531     jms      11915:    lines for response n and number of the first bubble line for response n,
                   11916:    and a comma separated list of numbers of bubble lines for sub-questions
                   11917:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11918: 
                   11919: 
                   11920: =item  scantron_validate_missingbubbles() : 
                   11921: 
                   11922:    Validates all scanlines in the selected file to not have any
                   11923:     answers that don't have bubbles that have not been verified
                   11924:     to be bubble free.
                   11925: 
                   11926: =item  scantron_process_students() : 
                   11927: 
1.659     raeburn  11928:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11929: 
                   11930:    The parsed scanline hash is added to %env 
                   11931: 
                   11932:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11933:    foreach resource , with the form data of
                   11934: 
                   11935: 	'submitted'     =>'scantron' 
                   11936: 	'grade_target'  =>'grade',
                   11937: 	'grade_username'=> username of student
                   11938: 	'grade_domain'  => domain of student
                   11939: 	'grade_courseid'=> of course
                   11940: 	'grade_symb'    => symb of resource to grade
                   11941: 
                   11942:     This triggers a grading pass. The problem grading code takes care
                   11943:     of converting the bubbled letter information (now in %env) into a
                   11944:     valid submission.
                   11945: 
                   11946: =item  scantron_upload_scantron_data() :
                   11947: 
1.659     raeburn  11948:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11949: 
                   11950: =item  scantron_upload_scantron_data_save() : 
                   11951: 
                   11952:    Adds a provided bubble information data file to the course if user
1.770     raeburn  11953:    has the correct privileges to do so.
                   11954: 
                   11955: = item scantron_upload_delete() :
                   11956: 
                   11957:    Deletes a previously uploaded bubble information data file, if user
                   11958:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      11959: 
                   11960: =item  valid_file() :
                   11961: 
                   11962:    Validates that the requested bubble data file exists in the course.
                   11963: 
                   11964: =item  scantron_download_scantron_data() : 
                   11965: 
                   11966:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11967:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11968:    course.
                   11969: 
                   11970: =item  scantron_validate_ID() : 
                   11971: 
                   11972:    Validates all scanlines in the selected file to not have any
1.556     weissno  11973:    invalid or underspecified student/employee IDs
1.531     jms      11974: 
1.582     raeburn  11975: =item navmap_errormsg() :
                   11976: 
                   11977:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11978:    Should be called whenever the request to instantiate a navmap object fails.
                   11979: 
                   11980: =back
1.582     raeburn  11981: 
1.531     jms      11982: =back
                   11983: 
                   11984: =cut

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