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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.790   ! raeburn     4: # $Id: grades.pm,v 1.789 2022/06/11 14:20:42 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 {
1.788     raeburn  6735:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
1.691     raeburn  6736:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6737:                    (ref($symb_to_resource) eq 'HASH'));
1.788     raeburn  6738:     if ($need_symb_in_map) {
                   6739:         return unless (ref($symb_for_examcode) eq 'HASH');
                   6740:     }
1.691     raeburn  6741:     my $resource_error;
                   6742:     foreach my $resource (@{$resources}) {
                   6743:         my $ressymb;
                   6744:         if (ref($resource)) {
                   6745:             $ressymb = $resource->symb();
                   6746:             push(@{$master_seq},$ressymb);
                   6747:             $symb_to_resource->{$ressymb} = $resource;
1.788     raeburn  6748:             if ($need_symb_in_map) {
                   6749:                 unless ($resource->is_map()) {
                   6750:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   6751:                     unless (exists($symb_for_examcode->{$map})) {
                   6752:                         $symb_for_examcode->{$map} = $ressymb;
                   6753:                     }
                   6754:                 }
                   6755:             }
1.691     raeburn  6756:         } else {
                   6757:             $resource_error = 1;
                   6758:             last;
                   6759:         }
                   6760:     }
                   6761:     return $resource_error;
                   6762: }
                   6763: 
                   6764: sub get_respnum_lookups {
                   6765:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6766:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6767:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6768:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6769:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6770:                    (ref($startline) eq 'HASH'));
                   6771:     my ($user,$scancode);
                   6772:     if ((exists($record->{'scantron.CODE'})) &&
                   6773:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6774:         $scancode = $record->{'scantron.CODE'};
                   6775:     } else {
                   6776:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6777:     }
                   6778:     my @mapresources =
                   6779:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6780:                      $orderedforcode);
                   6781:     my $total = 0;
                   6782:     my $count = 0;
                   6783:     foreach my $resource (@mapresources) {
                   6784:         my $id = $resource->id();
                   6785:         my $symb = $resource->symb();
                   6786:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6787:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6788:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6789:                 if ($respnum ne '') {
                   6790:                     $respnumlookup->{$count} = $respnum;
                   6791:                     $startline->{$count} = $total;
                   6792:                     $total += $bubble_lines_per_response{$respnum};
                   6793:                     $count ++;
                   6794:                 }
                   6795:             }
                   6796:         }
                   6797:     }
                   6798:     return $total;
                   6799: }
                   6800: 
1.503     raeburn  6801: sub scantron_validator_lettnum {
                   6802:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6803:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6804:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6805: 
                   6806:     # Qon 'letter' implies for each slot in currquest we have:
                   6807:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6808:     #    about anything else (esp. a value of Qoff) for missing
                   6809:     #    bubbles.
                   6810:     #
                   6811:     # Qon 'number' implies each slot gives a digit that indexes the
                   6812:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6813:     #    and * or ? for double bubbles on a single line.
                   6814:     #
1.447     foxr     6815: 
1.503     raeburn  6816:     my $matchon;
                   6817:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6818:         $matchon = '[A-Z]';
                   6819:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6820:         $matchon = '\d';
                   6821:     }
                   6822:     my $occurrences = 0;
1.691     raeburn  6823:     my $responsenum = $questnum-1;
                   6824:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6825:        $responsenum = $respnumlookup->{$questnum-1} 
                   6826:     }
                   6827:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6828:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6829:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6830:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6831:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6832:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6833:         my @singlelines = split('',$currquest);
                   6834:         foreach my $entry (@singlelines) {
                   6835:             $occurrences = &occurence_count($entry,$matchon);
                   6836:             if ($occurrences > 1) {
                   6837:                 last;
                   6838:             }
1.691     raeburn  6839:         }
1.503     raeburn  6840:     } else {
                   6841:         $occurrences = &occurence_count($currquest,$matchon); 
                   6842:     }
                   6843:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6844:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6845:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6846:             my $bubble = substr($currquest,$ans,1);
                   6847:             if ($bubble =~ /$matchon/ ) {
                   6848:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6849:                     if ($bubble == 0) {
                   6850:                         $bubble = 10; 
                   6851:                     }
                   6852:                     $record->{"scantron.$ansnum.answer"} = 
                   6853:                         $alphabet->[$bubble-1];
                   6854:                 } else {
                   6855:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6856:                 }
                   6857:             } else {
                   6858:                 $record->{"scantron.$ansnum.answer"}='';
                   6859:             }
                   6860:             $ansnum++;
                   6861:         }
                   6862:     } elsif (!defined($currquest)
                   6863:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6864:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6865:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6866:             $record->{"scantron.$ansnum.answer"}='';
                   6867:             $ansnum++;
                   6868:         }
                   6869:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6870:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6871:         }
                   6872:     } else {
                   6873:         if ($$scantron_config{'Qon'} eq 'number') {
                   6874:             $currquest = &digits_to_letters($currquest);            
                   6875:         }
                   6876:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6877:             my $bubble = substr($currquest,$ans,1);
                   6878:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6879:             $ansnum++;
                   6880:         }
                   6881:     }
                   6882:     return $ansnum;
                   6883: }
1.447     foxr     6884: 
1.503     raeburn  6885: sub scantron_validator_positional {
                   6886:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6887:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6888:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6889: 
1.503     raeburn  6890:     # Otherwise there's a positional notation;
                   6891:     # each bubble line requires Qlength items, and there are filled in
                   6892:     # bubbles for each case where there 'Qon' characters.
                   6893:     #
1.447     foxr     6894: 
1.503     raeburn  6895:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6896: 
1.503     raeburn  6897:     # If the split only gives us one element.. the full length of the
                   6898:     # answer string, no bubbles are filled in:
1.447     foxr     6899: 
1.507     raeburn  6900:     if ($answers_needed eq '') {
                   6901:         return;
                   6902:     }
                   6903: 
1.503     raeburn  6904:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6905:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6906:             $record->{"scantron.$ansnum.answer"}='';
                   6907:             $ansnum++;
                   6908:         }
                   6909:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6910:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6911:         }
                   6912:     } elsif (scalar(@array) == 2) {
                   6913:         my $location = length($array[0]);
                   6914:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6915:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6916:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6917:             if ($ans eq $line_num) {
                   6918:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6919:             } else {
                   6920:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6921:             }
                   6922:             $ansnum++;
                   6923:          }
                   6924:     } else {
                   6925:         #  If there's more than one instance of a bubble character
                   6926:         #  That's a double bubble; with positional notation we can
                   6927:         #  record all the bubbles filled in as well as the
                   6928:         #  fact this response consists of multiple bubbles.
                   6929:         #
1.691     raeburn  6930:         my $responsenum = $questnum-1;
                   6931:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6932:             $responsenum = $respnumlookup->{$questnum-1}
                   6933:         }
                   6934:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6935:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6936:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6937:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6938:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6939:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6940:             my $doubleerror = 0;
                   6941:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6942:                    (!$doubleerror)) {
                   6943:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6944:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6945:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6946:                if (length(@currarray) > 2) {
                   6947:                    $doubleerror = 1;
                   6948:                } 
                   6949:             }
                   6950:             if ($doubleerror) {
                   6951:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6952:             }
                   6953:         } else {
                   6954:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6955:         }
                   6956:         my $item = $ansnum;
                   6957:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6958:             $record->{"scantron.$item.answer"} = '';
                   6959:             $item ++;
                   6960:         }
1.447     foxr     6961: 
1.503     raeburn  6962:         my @ans=@array;
                   6963:         my $i=0;
                   6964:         my $increment = 0;
                   6965:         while ($#ans) {
                   6966:             $i+=length($ans[0]) + $increment;
                   6967:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6968:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6969:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6970:             shift(@ans);
                   6971:             $increment = 1;
                   6972:         }
                   6973:         $ansnum += $answers_needed;
1.82      albertel 6974:     }
1.503     raeburn  6975:     return $ansnum;
1.82      albertel 6976: }
                   6977: 
1.423     albertel 6978: =pod
                   6979: 
                   6980: =item scantron_add_delay
                   6981: 
                   6982:    Adds an error message that occurred during the grading phase to a
                   6983:    queue of messages to be shown after grading pass is complete
                   6984: 
                   6985:  Arguments:
1.424     albertel 6986:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6987:    $scanline    - the scanline that caused the error
                   6988:    $errormesage - the error message
                   6989:    $errorcode   - a numeric code for the error
                   6990: 
                   6991:  Side Effects:
1.424     albertel 6992:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6993: 
                   6994: =cut
                   6995: 
1.82      albertel 6996: sub scantron_add_delay {
1.140     albertel 6997:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6998:     push(@$delayqueue,
                   6999: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   7000: 	  'ecode' => $errorcode }
                   7001: 	 );
1.82      albertel 7002: }
                   7003: 
1.423     albertel 7004: =pod
                   7005: 
                   7006: =item scantron_find_student
                   7007: 
1.424     albertel 7008:    Finds the username for the current scanline
                   7009: 
                   7010:   Arguments:
                   7011:    $scantron_record - hash result from scantron_parse_scanline
                   7012:    $scan_data       - hash of correction information 
                   7013:                       (see &scantron_getfile() form more information)
                   7014:    $idmap           - hash from &username_to_idmap()
                   7015:    $line            - number of current scanline
                   7016:  
                   7017:   Returns:
                   7018:    Either 'username:domain' or undef if unknown
                   7019: 
1.423     albertel 7020: =cut
                   7021: 
1.82      albertel 7022: sub scantron_find_student {
1.157     albertel 7023:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 7024:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 7025:     if ($scanID =~ /^\s*$/) {
                   7026:  	return &scan_data($scan_data,"$line.user");
                   7027:     }
1.83      albertel 7028:     foreach my $id (keys(%$idmap)) {
1.157     albertel 7029:  	if (lc($id) eq lc($scanID)) {
                   7030:  	    return $$idmap{$id};
                   7031:  	}
1.83      albertel 7032:     }
                   7033:     return undef;
                   7034: }
                   7035: 
1.423     albertel 7036: =pod
                   7037: 
                   7038: =item scantron_filter
                   7039: 
1.424     albertel 7040:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   7041:    hidden resources was selected
                   7042: 
1.423     albertel 7043: =cut
                   7044: 
1.83      albertel 7045: sub scantron_filter {
                   7046:     my ($curres)=@_;
1.331     albertel 7047: 
                   7048:     if (ref($curres) && $curres->is_problem()) {
                   7049: 	# if the user has asked to not have either hidden
                   7050: 	# or 'randomout' controlled resources to be graded
                   7051: 	# don't include them
                   7052: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7053: 	    && $curres->randomout) {
                   7054: 	    return 0;
                   7055: 	}
1.83      albertel 7056: 	return 1;
                   7057:     }
                   7058:     return 0;
1.82      albertel 7059: }
                   7060: 
1.423     albertel 7061: =pod
                   7062: 
                   7063: =item scantron_process_corrections
                   7064: 
1.424     albertel 7065:    Gets correction information out of submitted form data and corrects
                   7066:    the scanline
                   7067: 
1.423     albertel 7068: =cut
                   7069: 
1.157     albertel 7070: sub scantron_process_corrections {
                   7071:     my ($r) = @_;
1.754     raeburn  7072:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7073:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7074:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 7075:     my $which=$env{'form.scantron_line'};
1.200     albertel 7076:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 7077:     my ($skip,$err,$errmsg);
1.257     albertel 7078:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 7079: 	$skip=1;
1.257     albertel 7080:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   7081: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   7082: 	    $env{'form.scantron_domain'};
1.157     albertel 7083: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   7084: 	($line,$err,$errmsg)=
                   7085: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   7086: 				     'ID',{'newid'=>$newid,
1.257     albertel 7087: 				    'username'=>$env{'form.scantron_username'},
                   7088: 				    'domain'=>$env{'form.scantron_domain'}});
                   7089:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   7090: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 7091: 	my $newCODE;
1.192     albertel 7092: 	my %args;
1.190     albertel 7093: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 7094: 	    $newCODE='use_unfound';
1.190     albertel 7095: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 7096: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 7097: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 7098: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 7099: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 7100: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 7101: 	}
1.257     albertel 7102: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 7103: 	    $args{'CODE_ignore_dup'}=1;
                   7104: 	}
                   7105: 	$args{'CODE'}=$newCODE;
1.186     albertel 7106: 	($line,$err,$errmsg)=
                   7107: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7108: 				     'CODE',\%args);
1.257     albertel 7109:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7110: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7111: 	    ($line,$err,$errmsg)=
                   7112: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7113: 					 $which,'answer',
                   7114: 					 { 'question'=>$question,
1.503     raeburn  7115: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7116:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7117: 	    if ($err) { last; }
                   7118: 	}
                   7119:     }
                   7120:     if ($err) {
1.703     bisitz   7121:         $r->print(
                   7122:             '<p class="LC_error">'
                   7123:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7124:                 $errmsg)
1.704     raeburn  7125:            .'</p>');
1.157     albertel 7126:     } else {
1.200     albertel 7127: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7128: 	&scantron_putfile($scanlines,$scan_data);
                   7129:     }
                   7130: }
                   7131: 
1.423     albertel 7132: =pod
                   7133: 
                   7134: =item reset_skipping_status
                   7135: 
1.424     albertel 7136:    Forgets the current set of remember skipped scanlines (and thus
                   7137:    reverts back to considering all lines in the
                   7138:    scantron_skipped_<filename> file)
                   7139: 
1.423     albertel 7140: =cut
                   7141: 
1.200     albertel 7142: sub reset_skipping_status {
                   7143:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7144:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7145:     &scantron_putfile(undef,$scan_data);
                   7146: }
                   7147: 
1.423     albertel 7148: =pod
                   7149: 
                   7150: =item start_skipping
                   7151: 
1.424     albertel 7152:    Marks a scanline to be skipped. 
                   7153: 
1.423     albertel 7154: =cut
                   7155: 
1.376     albertel 7156: sub start_skipping {
1.200     albertel 7157:     my ($scan_data,$i)=@_;
                   7158:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7159:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7160: 	$remembered{$i}=2;
                   7161:     } else {
                   7162: 	$remembered{$i}=1;
                   7163:     }
1.200     albertel 7164:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7165: }
                   7166: 
1.423     albertel 7167: =pod
                   7168: 
                   7169: =item should_be_skipped
                   7170: 
1.424     albertel 7171:    Checks whether a scanline should be skipped.
                   7172: 
1.423     albertel 7173: =cut
                   7174: 
1.200     albertel 7175: sub should_be_skipped {
1.376     albertel 7176:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7177:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7178: 	# not redoing old skips
1.376     albertel 7179: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7180: 	return 0;
                   7181:     }
                   7182:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7183: 
                   7184:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7185: 	return 0;
                   7186:     }
1.200     albertel 7187:     return 1;
                   7188: }
                   7189: 
1.423     albertel 7190: =pod
                   7191: 
                   7192: =item remember_current_skipped
                   7193: 
1.424     albertel 7194:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7195:    file and remembers them into scan_data for later use.
                   7196: 
1.423     albertel 7197: =cut
                   7198: 
1.200     albertel 7199: sub remember_current_skipped {
                   7200:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7201:     my %to_remember;
                   7202:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7203: 	if ($scanlines->{'skipped'}[$i]) {
                   7204: 	    $to_remember{$i}=1;
                   7205: 	}
                   7206:     }
1.376     albertel 7207: 
1.200     albertel 7208:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7209:     &scantron_putfile(undef,$scan_data);
                   7210: }
                   7211: 
1.423     albertel 7212: =pod
                   7213: 
                   7214: =item check_for_error
                   7215: 
1.424     albertel 7216:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  7217:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7218:     something went wrong.
                   7219: 
1.423     albertel 7220: =cut
                   7221: 
1.200     albertel 7222: sub check_for_error {
                   7223:     my ($r,$result)=@_;
                   7224:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7225: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7226:     }
                   7227: }
1.157     albertel 7228: 
1.423     albertel 7229: =pod
                   7230: 
                   7231: =item scantron_warning_screen
                   7232: 
1.424     albertel 7233:    Interstitial screen to make sure the operator has selected the
                   7234:    correct options before we start the validation phase.
                   7235: 
1.423     albertel 7236: =cut
                   7237: 
1.203     albertel 7238: sub scantron_warning_screen {
1.650     raeburn  7239:     my ($button_text,$symb)=@_;
1.257     albertel 7240:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  7241:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7242:     my $CODElist;
1.284     albertel 7243:     if ($scantron_config{'CODElocation'} &&
                   7244: 	$scantron_config{'CODEstart'} &&
                   7245: 	$scantron_config{'CODElength'}) {
                   7246: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   7247: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7248: 	$CODElist=
1.492     albertel 7249: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7250: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7251:     }
1.663     raeburn  7252:     my $lastbubblepoints;
                   7253:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7254:         $lastbubblepoints =
                   7255:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7256:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7257:     }
1.770     raeburn  7258:     return '
1.203     albertel 7259: <p>
1.492     albertel 7260: <span class="LC_warning">
1.705     raeburn  7261: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7262: </p>
                   7263: <table>
1.492     albertel 7264: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7265: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  7266: '.$CODElist.$lastbubblepoints.'
1.203     albertel 7267: </table>
1.680     raeburn  7268: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  7269: '.&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  7270: ';
1.203     albertel 7271: }
                   7272: 
1.423     albertel 7273: =pod
                   7274: 
                   7275: =item scantron_do_warning
                   7276: 
1.424     albertel 7277:    Check if the operator has picked something for all required
                   7278:    fields. Error out if something is missing.
                   7279: 
1.423     albertel 7280: =cut
                   7281: 
1.203     albertel 7282: sub scantron_do_warning {
1.608     www      7283:     my ($r,$symb)=@_;
1.203     albertel 7284:     if (!$symb) {return '';}
1.324     albertel 7285:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7286:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7287:     if ( $env{'form.selectpage'} eq '' ||
                   7288: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7289: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7290: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7291: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7292: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7293: 	} 
1.257     albertel 7294: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7295: 	    $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  7296: 	}
1.257     albertel 7297: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7298: 	    $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  7299: 	}
1.237     albertel 7300:     } else {
1.650     raeburn  7301: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  7302:         my ($checksec,@possibles) = &gradable_sections();
                   7303:         my $gradesections;
                   7304:         if ($checksec) {
                   7305:             my $file=$env{'form.scantron_selectfile'};
                   7306:             if (&valid_file($file)) {
                   7307:                 my %bysec = &scantron_get_sections();
                   7308:                 my $table;
                   7309:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   7310:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   7311:                     $table = &Apache::loncommon::start_data_table()."\n".
                   7312:                              &Apache::loncommon::start_data_table_header_row().
                   7313:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   7314:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   7315:                     if ($bysec{'none'}) {
                   7316:                         $table .= &Apache::loncommon::start_data_table_row().
                   7317:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   7318:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7319:                     }
                   7320:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   7321:                         next if ($sec eq 'none');
                   7322:                         $table .= &Apache::loncommon::start_data_table_row().
                   7323:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   7324:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7325:                     }
                   7326:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   7327:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   7328:                                       '<p>'.$table.'</p>';
                   7329:                     if (@possibles) {
                   7330:                         $gradesections .= '<p>'.
                   7331:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   7332:                                               scalar(@possibles)).'<br />'.
                   7333:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   7334:                                               '<i>'.$checksec.'</i>').' ';
                   7335:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   7336:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   7337:                         }
                   7338:                         $gradesections .= '</p>';
                   7339:                     }
                   7340:                 }
                   7341:             } else {
                   7342:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   7343:             }
                   7344:         }
1.663     raeburn  7345:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7346: 	$r->print('
1.770     raeburn  7347: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 7348: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7349: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7350: ');
1.237     albertel 7351:     }
1.614     www      7352:     $r->print("</form><br />");
1.203     albertel 7353:     return '';
                   7354: }
                   7355: 
1.423     albertel 7356: =pod
                   7357: 
                   7358: =item scantron_form_start
                   7359: 
1.424     albertel 7360:     html hidden input for remembering all selected grading options
                   7361: 
1.423     albertel 7362: =cut
                   7363: 
1.203     albertel 7364: sub scantron_form_start {
                   7365:     my ($max_bubble)=@_;
                   7366:     my $result= <<SCANTRONFORM;
                   7367: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7368:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7369:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7370:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7371:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7372:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7373:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7374:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7375:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7376:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7377: SCANTRONFORM
1.447     foxr     7378: 
                   7379:   my $line = 0;
                   7380:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7381:        my $chunk =
                   7382: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7383:        $chunk .=
                   7384: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7385:        $chunk .= 
                   7386:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7387:        $chunk .=
                   7388:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7389:        $chunk .=
                   7390:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7391:        $result .= $chunk;
                   7392:        $line++;
1.691     raeburn  7393:     }
1.203     albertel 7394:     return $result;
                   7395: }
                   7396: 
1.423     albertel 7397: =pod
                   7398: 
                   7399: =item scantron_validate_file
                   7400: 
1.659     raeburn  7401:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7402: 
                   7403:     Also processes any necessary information resets that need to
                   7404:     occur before validation begins (ignore previous corrections,
                   7405:     restarting the skipped records processing)
                   7406: 
1.423     albertel 7407: =cut
                   7408: 
1.157     albertel 7409: sub scantron_validate_file {
1.608     www      7410:     my ($r,$symb) = @_;
1.157     albertel 7411:     if (!$symb) {return '';}
1.324     albertel 7412:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7413:     
1.703     bisitz   7414:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7415:     # them when doing the corrections reset
1.257     albertel 7416:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7417: 	&reset_skipping_status();
                   7418:     }
1.257     albertel 7419:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7420: 	&remember_current_skipped();
1.257     albertel 7421: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7422:     }
                   7423: 
1.257     albertel 7424:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7425: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7426: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7427: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7428: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7429:     }
1.200     albertel 7430: 
1.257     albertel 7431:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7432: 	&scantron_process_corrections($r);
                   7433:     }
1.770     raeburn  7434: 
                   7435:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   7436:     my ($checksec,@gradable);
                   7437:     if ($env{'request.course.sec'}) {
                   7438:         ($checksec,my @possibles) = &gradable_sections();
                   7439:         if ($checksec) {
                   7440:             if (@possibles) {
                   7441:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   7442:                 if (@chosensecs) {
                   7443:                     foreach my $sec (@chosensecs) {
                   7444:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   7445:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   7446:                                 push(@gradable,$sec);
                   7447:                             }
                   7448:                         }
                   7449:                     }
                   7450:                 }
                   7451:             }
                   7452:             $r->print('<p><table>');
                   7453:             if (@gradable) {
                   7454:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   7455:                 $r->print(
                   7456:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   7457:             } else {
                   7458:                 $r->print(
                   7459:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   7460:             }
                   7461:             $r->print('</table></p>');
                   7462:         }
                   7463:     }
                   7464:     $r->rflush();
                   7465: 
1.157     albertel 7466:     #get the student pick code ready
                   7467:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7468:     my $nav_error;
1.754     raeburn  7469:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7470:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7471:     if ($nav_error) {
                   7472:         $r->print(&navmap_errormsg());
                   7473:         return '';
                   7474:     }
1.203     albertel 7475:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7476:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7477:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7478:     }
1.157     albertel 7479:     $r->print($result);
                   7480:     
1.334     albertel 7481:     my @validate_phases=( 'sequence',
                   7482: 			  'ID',
1.157     albertel 7483: 			  'CODE',
                   7484: 			  'doublebubble',
                   7485: 			  'missingbubbles');
1.257     albertel 7486:     if (!$env{'form.validatepass'}) {
                   7487: 	$env{'form.validatepass'} = 0;
1.157     albertel 7488:     }
1.257     albertel 7489:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  7490:     my %skipbysec=();
1.448     foxr     7491: 
1.157     albertel 7492:     my $stop=0;
                   7493:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7494: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7495: 	$r->rflush();
1.691     raeburn  7496:      
1.157     albertel 7497: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7498: 	{
                   7499: 	    no strict 'refs';
1.770     raeburn  7500:             my @extras=();
                   7501:             if ($validate_phases[$currentphase] eq 'ID') {
                   7502:                 @extras = (\%skipbysec,$checksec,@gradable);
                   7503:             }
                   7504: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 7505: 	}
                   7506:     }
                   7507:     if (!$stop) {
1.650     raeburn  7508: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  7509:         my $secinfo;
                   7510:         if (keys(%skipbysec) > 0) {
                   7511:             my $seclist = '<ul>';
                   7512:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   7513:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   7514:             }
                   7515:             $seclist .= '</ul>';
                   7516:             $secinfo = '<p class="LC_info">'.
                   7517:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   7518:                            $seclist).
                   7519:                        '</p>';
                   7520:         }
1.542     raeburn  7521: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  7522:                   $secinfo.$warning.
1.542     raeburn  7523:                   &mt('Perform verification for each student after storage of submissions?').
                   7524:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7525:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7526:                   ('&nbsp;'x3).'<label>'.
                   7527:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7528:                   '</label></span><br />'.
                   7529:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7530:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7531:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7532:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7533:     } else {
                   7534: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7535: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7536:     }
                   7537:     if ($stop) {
1.334     albertel 7538: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7539: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7540: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7541: 
1.650     raeburn  7542: 	    $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 7543: 	} else {
1.503     raeburn  7544:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7545: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7546:             } else {
1.539     riegler  7547:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7548:             }
1.492     albertel 7549: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7550: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7551: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7552: 	}
1.157     albertel 7553:     }
1.614     www      7554:     $r->print(" </form><br />");
1.157     albertel 7555:     return '';
                   7556: }
                   7557: 
1.423     albertel 7558: 
                   7559: =pod
                   7560: 
                   7561: =item scantron_remove_file
                   7562: 
1.659     raeburn  7563:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7564:    scantron_original_<filename> is never removed
                   7565: 
                   7566: 
1.423     albertel 7567: =cut
                   7568: 
1.200     albertel 7569: sub scantron_remove_file {
1.192     albertel 7570:     my ($which)=@_;
1.257     albertel 7571:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7572:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7573:     my $file='scantron_';
1.200     albertel 7574:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7575: 	$file.=$which.'_';
1.192     albertel 7576:     } else {
                   7577: 	return 'refused';
                   7578:     }
1.257     albertel 7579:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7580:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7581: }
                   7582: 
1.423     albertel 7583: 
                   7584: =pod
                   7585: 
                   7586: =item scantron_remove_scan_data
                   7587: 
1.659     raeburn  7588:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7589:    data file.  (In the case that both the are doing skipped records we need
                   7590:    to remember the old skipped lines for the time being so that element
                   7591:    persists for a while.)
                   7592: 
1.423     albertel 7593: =cut
                   7594: 
1.200     albertel 7595: sub scantron_remove_scan_data {
1.257     albertel 7596:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7597:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7598:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7599:     my @todelete;
1.257     albertel 7600:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7601:     foreach my $key (@keys) {
                   7602: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7603: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7604: 		$key=~/remember_skipping/) {
                   7605: 		next;
                   7606: 	    }
1.192     albertel 7607: 	    push(@todelete,$key);
                   7608: 	}
                   7609:     }
1.200     albertel 7610:     my $result;
1.192     albertel 7611:     if (@todelete) {
1.491     albertel 7612: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7613: 				       \@todelete,$cdom,$cname);
                   7614:     } else {
                   7615: 	$result = 'ok';
1.192     albertel 7616:     }
                   7617:     return $result;
                   7618: }
                   7619: 
1.423     albertel 7620: 
                   7621: =pod
                   7622: 
                   7623: =item scantron_getfile
                   7624: 
1.659     raeburn  7625:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7626:     the scan_data hash
                   7627:   
                   7628:   Arguments:
                   7629:     None
                   7630: 
                   7631:   Returns:
                   7632:     2 hash references
                   7633: 
                   7634:      - first one has 
                   7635:          orig      -
                   7636:          corrected -
                   7637:          skipped   -  each of which points to an array ref of the specified
                   7638:                       file broken up into individual lines
                   7639:          count     - number of scanlines
                   7640:  
                   7641:      - second is the scan_data hash possible keys are
1.425     albertel 7642:        ($number refers to scanline numbered $number and thus the key affects
                   7643:         only that scanline
                   7644:         $bubline refers to the specific bubble line element and the aspects
                   7645:         refers to that specific bubble line element)
                   7646: 
                   7647:        $number.user - username:domain to use
                   7648:        $number.CODE_ignore_dup 
                   7649:                     - ignore the duplicate CODE error 
                   7650:        $number.useCODE
                   7651:                     - use the CODE in the scanline as is
                   7652:        $number.no_bubble.$bubline
                   7653:                     - it is valid that there is no bubbled in bubble
                   7654:                       at $number $bubline
                   7655:        remember_skipping
                   7656:                     - a frozen hash containing keys of $number and values
                   7657:                       of either 
                   7658:                         1 - we are on a 'do skipped records pass' and plan
                   7659:                             on processing this line
                   7660:                         2 - we are on a 'do skipped records pass' and this
                   7661:                             scanline has been marked to skip yet again
1.424     albertel 7662: 
1.423     albertel 7663: =cut
                   7664: 
1.157     albertel 7665: sub scantron_getfile {
1.200     albertel 7666:     #FIXME really would prefer a scantron directory
1.257     albertel 7667:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7668:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7669:     my $lines;
                   7670:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7671: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7672:     my %scanlines;
                   7673:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7674:     my $temp=$scanlines{'orig'};
                   7675:     $scanlines{'count'}=$#$temp;
                   7676: 
                   7677:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7678: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7679:     if ($lines eq '-1') {
                   7680: 	$scanlines{'corrected'}=[];
                   7681:     } else {
                   7682: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7683:     }
                   7684:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7685: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7686:     if ($lines eq '-1') {
                   7687: 	$scanlines{'skipped'}=[];
                   7688:     } else {
                   7689: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7690:     }
1.175     albertel 7691:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7692:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7693:     my %scan_data = @tmp;
                   7694:     return (\%scanlines,\%scan_data);
                   7695: }
                   7696: 
1.423     albertel 7697: =pod
                   7698: 
                   7699: =item lonnet_putfile
                   7700: 
1.424     albertel 7701:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7702: 
                   7703:  Arguments:
                   7704:    $contents - data to store
                   7705:    $filename - filename to store $contents into
                   7706: 
                   7707:  Returns:
                   7708:    result value from &Apache::lonnet::finishuserfileupload
                   7709: 
1.423     albertel 7710: =cut
                   7711: 
1.157     albertel 7712: sub lonnet_putfile {
                   7713:     my ($contents,$filename)=@_;
1.257     albertel 7714:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7715:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7716:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7717:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7718: 
                   7719: }
                   7720: 
1.423     albertel 7721: =pod
                   7722: 
                   7723: =item scantron_putfile
                   7724: 
1.659     raeburn  7725:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7726:     scan_data hash. (Does not modify the original version only the
                   7727:     corrected and skipped versions.
                   7728: 
                   7729:  Arguments:
                   7730:     $scanlines - hash ref that looks like the first return value from
                   7731:                  &scantron_getfile()
                   7732:     $scan_data - hash ref that looks like the second return value from
                   7733:                  &scantron_getfile()
                   7734: 
1.423     albertel 7735: =cut
                   7736: 
1.157     albertel 7737: sub scantron_putfile {
                   7738:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7739:     #FIXME really would prefer a scantron directory
1.257     albertel 7740:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7741:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7742:     if ($scanlines) {
                   7743: 	my $prefix='scantron_';
1.157     albertel 7744: # no need to update orig, shouldn't change
                   7745: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7746: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7747: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7748: 			$prefix.'corrected_'.
1.257     albertel 7749: 			$env{'form.scantron_selectfile'});
1.200     albertel 7750: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7751: 			$prefix.'skipped_'.
1.257     albertel 7752: 			$env{'form.scantron_selectfile'});
1.200     albertel 7753:     }
1.175     albertel 7754:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7755: }
                   7756: 
1.423     albertel 7757: =pod
                   7758: 
                   7759: =item scantron_get_line
                   7760: 
1.424     albertel 7761:    Returns the correct version of the scanline
                   7762: 
                   7763:  Arguments:
                   7764:     $scanlines - hash ref that looks like the first return value from
                   7765:                  &scantron_getfile()
                   7766:     $scan_data - hash ref that looks like the second return value from
                   7767:                  &scantron_getfile()
                   7768:     $i         - number of the requested line (starts at 0)
                   7769: 
                   7770:  Returns:
                   7771:    A scanline, (either the original or the corrected one if it
                   7772:    exists), or undef if the requested scanline should be
                   7773:    skipped. (Either because it's an skipped scanline, or it's an
                   7774:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7775:    pass.
                   7776: 
1.423     albertel 7777: =cut
                   7778: 
1.157     albertel 7779: sub scantron_get_line {
1.200     albertel 7780:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7781:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7782:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7783:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7784:     return $scanlines->{'orig'}[$i]; 
                   7785: }
                   7786: 
1.423     albertel 7787: =pod
                   7788: 
                   7789: =item scantron_todo_count
                   7790: 
1.424     albertel 7791:     Counts the number of scanlines that need processing.
                   7792: 
                   7793:  Arguments:
                   7794:     $scanlines - hash ref that looks like the first return value from
                   7795:                  &scantron_getfile()
                   7796:     $scan_data - hash ref that looks like the second return value from
                   7797:                  &scantron_getfile()
                   7798: 
                   7799:  Returns:
                   7800:     $count - number of scanlines to process
                   7801: 
1.423     albertel 7802: =cut
                   7803: 
1.200     albertel 7804: sub get_todo_count {
                   7805:     my ($scanlines,$scan_data)=@_;
                   7806:     my $count=0;
                   7807:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7808: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7809: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7810: 	$count++;
                   7811:     }
                   7812:     return $count;
                   7813: }
                   7814: 
1.423     albertel 7815: =pod
                   7816: 
                   7817: =item scantron_put_line
                   7818: 
1.659     raeburn  7819:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7820:     data file.
                   7821: 
                   7822:  Arguments:
                   7823:     $scanlines - hash ref that looks like the first return value from
                   7824:                  &scantron_getfile()
                   7825:     $scan_data - hash ref that looks like the second return value from
                   7826:                  &scantron_getfile()
                   7827:     $i         - line number to update
                   7828:     $newline   - contents of the updated scanline
                   7829:     $skip      - if true make the line for skipping and update the
                   7830:                  'skipped' file
                   7831: 
1.423     albertel 7832: =cut
                   7833: 
1.157     albertel 7834: sub scantron_put_line {
1.200     albertel 7835:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7836:     if ($skip) {
                   7837: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7838: 	&start_skipping($scan_data,$i);
1.157     albertel 7839: 	return;
                   7840:     }
                   7841:     $scanlines->{'corrected'}[$i]=$newline;
                   7842: }
                   7843: 
1.423     albertel 7844: =pod
                   7845: 
                   7846: =item scantron_clear_skip
                   7847: 
1.424     albertel 7848:    Remove a line from the 'skipped' file
                   7849: 
                   7850:  Arguments:
                   7851:     $scanlines - hash ref that looks like the first return value from
                   7852:                  &scantron_getfile()
                   7853:     $scan_data - hash ref that looks like the second return value from
                   7854:                  &scantron_getfile()
                   7855:     $i         - line number to update
                   7856: 
1.423     albertel 7857: =cut
                   7858: 
1.376     albertel 7859: sub scantron_clear_skip {
                   7860:     my ($scanlines,$scan_data,$i)=@_;
                   7861:     if (exists($scanlines->{'skipped'}[$i])) {
                   7862: 	undef($scanlines->{'skipped'}[$i]);
                   7863: 	return 1;
                   7864:     }
                   7865:     return 0;
                   7866: }
                   7867: 
1.423     albertel 7868: =pod
                   7869: 
                   7870: =item scantron_filter_not_exam
                   7871: 
1.424     albertel 7872:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7873:    filter out resources that are not marked as 'exam' mode
                   7874: 
1.423     albertel 7875: =cut
                   7876: 
1.334     albertel 7877: sub scantron_filter_not_exam {
                   7878:     my ($curres)=@_;
                   7879:     
                   7880:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7881: 	# if the user has asked to not have either hidden
                   7882: 	# or 'randomout' controlled resources to be graded
                   7883: 	# don't include them
                   7884: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7885: 	    && $curres->randomout) {
                   7886: 	    return 0;
                   7887: 	}
                   7888: 	return 1;
                   7889:     }
                   7890:     return 0;
                   7891: }
                   7892: 
1.423     albertel 7893: =pod
                   7894: 
                   7895: =item scantron_validate_sequence
                   7896: 
1.424     albertel 7897:     Validates the selected sequence, checking for resource that are
                   7898:     not set to exam mode.
                   7899: 
1.423     albertel 7900: =cut
                   7901: 
1.334     albertel 7902: sub scantron_validate_sequence {
                   7903:     my ($r,$currentphase) = @_;
                   7904: 
                   7905:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7906:     unless (ref($navmap)) {
                   7907:         $r->print(&navmap_errormsg());
                   7908:         return (1,$currentphase);
                   7909:     }
1.334     albertel 7910:     my (undef,undef,$sequence)=
                   7911: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7912: 
                   7913:     my $map=$navmap->getResourceByUrl($sequence);
                   7914: 
                   7915:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7916:                                     value="ignore" />');
                   7917:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7918: 	my @resources=
                   7919: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7920: 	if (@resources) {
1.675     bisitz   7921: 	    $r->print(
                   7922:                 '<p class="LC_warning">'
                   7923:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7924:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7925:                    .' work correctly.')
                   7926:                .'</p>'
                   7927:             );
1.334     albertel 7928: 	    return (1,$currentphase);
                   7929: 	}
                   7930:     }
                   7931: 
                   7932:     return (0,$currentphase+1);
                   7933: }
                   7934: 
1.423     albertel 7935: 
                   7936: 
1.157     albertel 7937: sub scantron_validate_ID {
1.770     raeburn  7938:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 7939:     
                   7940:     #get student info
                   7941:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7942:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  7943:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 7944: 
                   7945:     #get scantron line setup
1.754     raeburn  7946:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7947:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7948: 
                   7949:     my $nav_error;
1.649     raeburn  7950:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7951:     if ($nav_error) {
                   7952:         $r->print(&navmap_errormsg());
                   7953:         return(1,$currentphase);
                   7954:     }
1.157     albertel 7955: 
                   7956:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  7957:     my $unsavedskips = 0;
1.157     albertel 7958:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7959: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7960: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7961: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7962: 						 $scan_data);
                   7963: 	my $id=$$scan_record{'scantron.ID'};
                   7964: 	my $found;
                   7965: 	foreach my $checkid (keys(%idmap)) {
                   7966: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7967: 	}
                   7968: 	if ($found) {
                   7969: 	    my $username=$idmap{$found};
1.770     raeburn  7970:             if ($checksec) {
                   7971:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   7972:                     my $stusec = $classlist->{$username}->[$secidx];
                   7973:                     if ($stusec ne $checksec) {
                   7974:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7975:                             my $skip=1;
                   7976:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7977:                             if (ref($skipbysec) eq 'HASH') {
                   7978:                                 if ($stusec eq '') {
                   7979:                                     $skipbysec->{'none'} ++;
                   7980:                                 } else {
                   7981:                                     $skipbysec->{$stusec} ++;
                   7982:                                 }
                   7983:                             }
                   7984:                             $unsavedskips ++;
                   7985:                             next;
                   7986:                         }
                   7987:                     }
                   7988:                 }
                   7989:             }
1.157     albertel 7990: 	    if ($found{'ids'}{$found}) {
                   7991: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7992: 					 $line,'duplicateID',$found);
1.770     raeburn  7993:                 if ($unsavedskips) {
                   7994:                     &scantron_putfile($scanlines,$scan_data);
                   7995:                     $unsavedskips = 0;
                   7996:                 }
1.194     albertel 7997: 		return(1,$currentphase);
1.157     albertel 7998: 	    } elsif ($found{'usernames'}{$username}) {
                   7999: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   8000: 					 $line,'duplicateID',$username);
1.770     raeburn  8001:                 if ($unsavedskips) {
                   8002:                     &scantron_putfile($scanlines,$scan_data);
                   8003:                     $unsavedskips = 0;
                   8004:                 }
1.194     albertel 8005: 		return(1,$currentphase);
1.157     albertel 8006: 	    }
1.186     albertel 8007: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 8008: 	    $found{'ids'}{$found}++;
                   8009: 	    $found{'usernames'}{$username}++;
                   8010: 	} else {
                   8011: 	    if ($id =~ /^\s*$/) {
1.158     albertel 8012: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  8013:                 if (($checksec && $username ne '')) {
                   8014:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   8015:                         my $stusec = $classlist->{$username}->[$secidx];
                   8016:                         if ($stusec ne $checksec) {
                   8017:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   8018:                                 my $skip=1;
                   8019:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   8020:                                 if (ref($skipbysec) eq 'HASH') {
                   8021:                                     if ($stusec eq '') {
                   8022:                                         $skipbysec->{'none'} ++;
                   8023:                                     } else {
                   8024:                                         $skipbysec->{$stusec} ++;
                   8025:                                     }
                   8026:                                 }
                   8027:                                 $unsavedskips ++;
                   8028:                                 next;
                   8029:                             }
                   8030:                         }
                   8031:                     }
                   8032: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 8033: 		    &scantron_get_correction($r,$i,$scan_record,
                   8034: 					     \%scantron_config,
                   8035: 					     $line,'duplicateID',$username);
1.770     raeburn  8036:                     if ($unsavedskips) {
                   8037:                         &scantron_putfile($scanlines,$scan_data);
                   8038:                         $unsavedskips = 0;
                   8039:                     }
1.194     albertel 8040: 		    return(1,$currentphase);
1.157     albertel 8041: 		} elsif (!defined($username)) {
                   8042: 		    &scantron_get_correction($r,$i,$scan_record,
                   8043: 					     \%scantron_config,
                   8044: 					     $line,'incorrectID');
1.770     raeburn  8045:                     if ($unsavedskips) {
                   8046:                         &scantron_putfile($scanlines,$scan_data);
                   8047:                         $unsavedskips = 0;
                   8048:                     }
1.194     albertel 8049: 		    return(1,$currentphase);
1.157     albertel 8050: 		}
                   8051: 		$found{'usernames'}{$username}++;
                   8052: 	    } else {
                   8053: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   8054: 					 $line,'incorrectID');
1.770     raeburn  8055:                 if ($unsavedskips) {
                   8056:                     &scantron_putfile($scanlines,$scan_data);
                   8057:                     $unsavedskips = 0;
                   8058:                 }
1.194     albertel 8059: 		return(1,$currentphase);
1.157     albertel 8060: 	    }
                   8061: 	}
                   8062:     }
1.770     raeburn  8063:     if ($unsavedskips) {
                   8064:         &scantron_putfile($scanlines,$scan_data);
                   8065:         $unsavedskips = 0;
                   8066:     }
1.157     albertel 8067:     return (0,$currentphase+1);
                   8068: }
                   8069: 
1.770     raeburn  8070: sub scantron_get_sections {
                   8071:     my %bysec;
                   8072:     if ($env{'form.scantron_format'} ne '') {
                   8073:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   8074:         my ($scanlines,$scan_data)=&scantron_getfile();
                   8075:         my $classlist=&Apache::loncoursedata::get_classlist();
                   8076:         my %idmap=&username_to_idmap($classlist);
                   8077:         foreach my $key (keys(%idmap)) {
                   8078:             my $lckey = lc($key);
                   8079:             $idmap{$lckey} = $idmap{$key};
                   8080:         }
                   8081:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   8082:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8083:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   8084:             if ($line=~/^[\s\cz]*$/) { next; }
                   8085:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8086:                                                      $scan_data);
                   8087:             my $id=lc($$scan_record{'scantron.ID'});
                   8088:             if (exists($idmap{$id})) {
                   8089:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   8090:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   8091:                     if ($stusec eq '') {
                   8092:                         $bysec{'none'} ++;
                   8093:                     } else {
                   8094:                         $bysec{$stusec} ++;
                   8095:                     }
                   8096:                 }
                   8097:             }
                   8098:         }
                   8099:     }
                   8100:     return %bysec;
                   8101: }
1.423     albertel 8102: 
1.157     albertel 8103: sub scantron_get_correction {
1.691     raeburn  8104:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   8105:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 8106: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 8107: #to show both the current line and the previous one and allow skipping
                   8108: #the previous one or the current one
                   8109: 
1.333     albertel 8110:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   8111:         $r->print(
                   8112:             '<p class="LC_warning">'
                   8113:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   8114:                 "<b>$error</b>",
                   8115:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   8116:            ."</p> \n");
1.157     albertel 8117:     } else {
1.658     bisitz   8118:         $r->print(
                   8119:             '<p class="LC_warning">'
                   8120:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8121:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8122:            ."</p> \n");
                   8123:     }
                   8124:     my $message =
                   8125:         '<p>'
                   8126:        .&mt('The ID on the form is [_1]',
                   8127:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8128:        .'<br />'
1.665     raeburn  8129:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   8130:             $$scan_record{'scantron.LastName'},
                   8131:             $$scan_record{'scantron.FirstName'})
                   8132:        .'</p>';
1.242     albertel 8133: 
1.157     albertel 8134:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8135:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8136:                            # Array populated for doublebubble or
                   8137:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8138:                            # to validate radio button checking   
                   8139: 
1.157     albertel 8140:     if ($error =~ /ID$/) {
1.186     albertel 8141: 	if ($error eq 'incorrectID') {
1.658     bisitz   8142:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8143: 		      "</p>\n");
1.157     albertel 8144: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   8145:             $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 8146: 	}
1.242     albertel 8147: 	$r->print($message);
1.492     albertel 8148: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8149: 	$r->print("\n<ul><li> ");
                   8150: 	#FIXME it would be nice if this sent back the user ID and
                   8151: 	#could do partial userID matches
                   8152: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8153: 				       'scantron_username','scantron_domain'));
                   8154: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   8155: 	$r->print("\n:\n".
1.257     albertel 8156: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8157: 
                   8158: 	$r->print('</li>');
1.186     albertel 8159:     } elsif ($error =~ /CODE$/) {
                   8160: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   8161: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8162: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   8163: 	    $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 8164: 	}
1.658     bisitz   8165: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   8166: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8167:                  ."</p>\n");
1.242     albertel 8168: 	$r->print($message);
1.658     bisitz   8169: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8170: 	$r->print("\n<br /> ");
1.194     albertel 8171: 	my $i=0;
1.273     albertel 8172: 	if ($error eq 'incorrectCODE' 
                   8173: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8174: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8175: 	    if ($closest > 0) {
                   8176: 		foreach my $testcode (@{$closest}) {
                   8177: 		    my $checked='';
1.569     bisitz   8178: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8179: 		    $r->print("
                   8180:    <label>
1.569     bisitz   8181:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8182:        ".&mt("Use the similar CODE [_1] instead.",
                   8183: 	    "<b><tt>".$testcode."</tt></b>")."
                   8184:     </label>
                   8185:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8186: 		    $r->print("\n<br />");
                   8187: 		    $i++;
                   8188: 		}
1.194     albertel 8189: 	    }
                   8190: 	}
1.273     albertel 8191: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8192: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8193: 	    $r->print("
                   8194:     <label>
1.569     bisitz   8195:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  8196:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8197: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8198:     </label>");
1.273     albertel 8199: 	    $r->print("\n<br />");
                   8200: 	}
1.194     albertel 8201: 
1.597     wenzelju 8202: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8203: function change_radio(field) {
1.190     albertel 8204:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8205:     var i;
                   8206:     for (i=0;i<slct.length;i++) {
                   8207:         if (slct[i].value==field) { slct[i].checked=true; }
                   8208:     }
                   8209: }
                   8210: ENDSCRIPT
1.187     albertel 8211: 	my $href="/adm/pickcode?".
1.359     www      8212: 	   "form=".&escape("scantronupload").
                   8213: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8214: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8215: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8216: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8217: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8218: 	    $r->print("
                   8219:     <label>
                   8220:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8221:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8222: 	     "<a target='_blank' href='$href'>","</a>")."
                   8223:     </label> 
1.558     bisitz   8224:     ".&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 8225: 	    $r->print("\n<br />");
                   8226: 	}
1.492     albertel 8227: 	$r->print("
                   8228:     <label>
                   8229:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8230:        ".&mt("Use [_1] as the CODE.",
                   8231: 	     "</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 8232: 	$r->print("\n<br /><br />");
1.157     albertel 8233:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   8234: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8235: 
                   8236: 	# The form field scantron_questions is acutally a list of line numbers.
                   8237: 	# represented by this form so:
                   8238: 
1.691     raeburn  8239: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8240:                                                 $respnumlookup,$startline);
1.497     foxr     8241: 
1.157     albertel 8242: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8243: 		  $line_list.'" />');
1.242     albertel 8244: 	$r->print($message);
1.492     albertel 8245: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8246: 	foreach my $question (@{$arg}) {
1.503     raeburn  8247: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8248:                                                    $scan_record, $error,
                   8249:                                                    $randomorder,$randompick,
                   8250:                                                    $respnumlookup,$startline);
1.524     raeburn  8251:             push(@lines_to_correct,@linenums);
1.157     albertel 8252: 	}
1.503     raeburn  8253:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8254:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   8255: 	$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 8256: 	$r->print($message);
1.492     albertel 8257: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8258: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8259: 
1.503     raeburn  8260: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8261: 	# a list of question numbers. Therefore:
                   8262: 	#
1.691     raeburn  8263: 
                   8264: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8265:                                                 $respnumlookup,$startline);
1.497     foxr     8266: 
1.157     albertel 8267: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8268: 		  $line_list.'" />');
1.157     albertel 8269: 	foreach my $question (@{$arg}) {
1.503     raeburn  8270: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8271:                                                    $scan_record, $error,
                   8272:                                                    $randomorder,$randompick,
                   8273:                                                    $respnumlookup,$startline);
1.524     raeburn  8274:             push(@lines_to_correct,@linenums);
1.157     albertel 8275: 	}
1.503     raeburn  8276:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8277:     } else {
                   8278: 	$r->print("\n<ul>");
                   8279:     }
                   8280:     $r->print("\n</li></ul>");
1.497     foxr     8281: }
                   8282: 
1.503     raeburn  8283: sub verify_bubbles_checked {
                   8284:     my (@ansnums) = @_;
                   8285:     my $ansnumstr = join('","',@ansnums);
                   8286:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  8287:     &js_escape(\$warning);
1.767     raeburn  8288:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8289: function verify_bubble_radio(form) {
                   8290:     var ansnumArray = new Array ("$ansnumstr");
                   8291:     var need_bubble_count = 0;
                   8292:     for (var i=0; i<ansnumArray.length; i++) {
                   8293:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8294:             var bubble_picked = 0; 
                   8295:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8296:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8297:                     bubble_picked = 1;
                   8298:                 }
                   8299:             }
                   8300:             if (bubble_picked == 0) {
                   8301:                 need_bubble_count ++;
                   8302:             }
                   8303:         }
                   8304:     }
                   8305:     if (need_bubble_count) {
                   8306:         alert("$warning");
                   8307:         return;
                   8308:     }
                   8309:     form.submit(); 
                   8310: }
                   8311: ENDSCRIPT
                   8312:     return $output;
                   8313: }
                   8314: 
1.497     foxr     8315: =pod
                   8316: 
                   8317: =item  questions_to_line_list
1.157     albertel 8318: 
1.497     foxr     8319: Converts a list of questions into a string of comma separated
                   8320: line numbers in the answer sheet used by the questions.  This is
                   8321: used to fill in the scantron_questions form field.
                   8322: 
                   8323:   Arguments:
                   8324:      questions    - Reference to an array of questions.
1.691     raeburn  8325:      randomorder  - True if randomorder in use.
                   8326:      randompick   - True if randompick in use.
                   8327:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8328:                      for current line to question number used for same question
                   8329:                      in "Master Seqence" (as seen by Course Coordinator).
                   8330:      startline    - Reference to hash where key is question number (0 is first)
                   8331:                     and key is number of first bubble line for current student
                   8332:                     or code-based randompick and/or randomorder.
1.693     raeburn  8333: 
1.497     foxr     8334: =cut
                   8335: 
                   8336: 
                   8337: sub questions_to_line_list {
1.691     raeburn  8338:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8339:     my @lines;
                   8340: 
1.503     raeburn  8341:     foreach my $item (@{$questions}) {
                   8342:         my $question = $item;
                   8343:         my ($first,$count,$last);
                   8344:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8345:             $question = $1;
                   8346:             my $subquestion = $2;
1.691     raeburn  8347:             my $responsenum = $question-1;
                   8348:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8349:                 $responsenum = $respnumlookup->{$question-1};
                   8350:                 if (ref($startline) eq 'HASH') {
                   8351:                     $first = $startline->{$question-1} + 1;
                   8352:                 }
                   8353:             } else {
                   8354:                 $first = $first_bubble_line{$responsenum} + 1;
                   8355:             }
                   8356:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8357:             my $subcount = 1;
                   8358:             while ($subcount<$subquestion) {
                   8359:                 $first += $subans[$subcount-1];
                   8360:                 $subcount ++;
                   8361:             }
                   8362:             $count = $subans[$subquestion-1];
                   8363:         } else {
1.691     raeburn  8364:             my $responsenum = $question-1;
                   8365:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8366:                 $responsenum = $respnumlookup->{$question-1};
                   8367:                 if (ref($startline) eq 'HASH') {
                   8368:                     $first = $startline->{$question-1} + 1;
                   8369:                 }
                   8370:             } else {
                   8371:                 $first = $first_bubble_line{$responsenum} + 1;
                   8372:             }
                   8373: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8374:         }
1.506     raeburn  8375:         $last = $first+$count-1;
1.503     raeburn  8376:         push(@lines, ($first..$last));
1.497     foxr     8377:     }
                   8378:     return join(',', @lines);
                   8379: }
                   8380: 
                   8381: =pod 
                   8382: 
                   8383: =item prompt_for_corrections
                   8384: 
                   8385: Prompts for a potentially multiline correction to the
                   8386: user's bubbling (factors out common code from scantron_get_correction
                   8387: for multi and missing bubble cases).
                   8388: 
                   8389:  Arguments:
                   8390:    $r           - Apache request object.
                   8391:    $question    - The question number to prompt for.
                   8392:    $scan_config - The scantron file configuration hash.
                   8393:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8394:    $error       - Type of error
1.691     raeburn  8395:    $randomorder - True if randomorder in use.
                   8396:    $randompick  - True if randompick in use.
                   8397:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8398:                     for current line to question number used for same question
                   8399:                     in "Master Seqence" (as seen by Course Coordinator).
                   8400:    $startline   - Reference to hash where key is question number (0 is first)
                   8401:                   and value is number of first bubble line for current student
                   8402:                   or code-based randompick and/or randomorder.
                   8403: 
1.497     foxr     8404: 
                   8405:  Implicit inputs:
                   8406:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8407:                                   Numbered from 0 (but question numbers are from
                   8408:                                   1.
                   8409:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8410:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8411:                                   type problems render as separate sub-questions, 
1.503     raeburn  8412:                                   in exam mode. This hash contains a 
                   8413:                                   comma-separated list of the lines per 
                   8414:                                   sub-question.
1.510     raeburn  8415:    %responsetype_per_response   - essayresponse, formularesponse,
                   8416:                                   stringresponse, imageresponse, reactionresponse,
                   8417:                                   and organicresponse type problem parts can have
1.503     raeburn  8418:                                   multiple lines per response if the weight
                   8419:                                   assigned exceeds 10.  In this case, only
                   8420:                                   one bubble per line is permitted, but more 
                   8421:                                   than one line might contain bubbles, e.g.
                   8422:                                   bubbling of: line 1 - J, line 2 - J, 
                   8423:                                   line 3 - B would assign 22 points.  
1.497     foxr     8424: 
                   8425: =cut
                   8426: 
                   8427: sub prompt_for_corrections {
1.691     raeburn  8428:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8429:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8430:     my ($current_line,$lines);
                   8431:     my @linenums;
                   8432:     my $questionnum = $question;
1.691     raeburn  8433:     my ($first,$responsenum);
1.503     raeburn  8434:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8435:         $question = $1;
                   8436:         my $subquestion = $2;
1.691     raeburn  8437:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8438:             $responsenum = $respnumlookup->{$question-1};
                   8439:             if (ref($startline) eq 'HASH') {
                   8440:                 $first = $startline->{$question-1};
                   8441:             }
                   8442:         } else {
                   8443:             $responsenum = $question-1;
1.714     raeburn  8444:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8445:         }
                   8446:         $current_line = $first + 1 ;
                   8447:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8448:         my $subcount = 1;
                   8449:         while ($subcount<$subquestion) {
                   8450:             $current_line += $subans[$subcount-1];
                   8451:             $subcount ++;
                   8452:         }
                   8453:         $lines = $subans[$subquestion-1];
                   8454:     } else {
1.691     raeburn  8455:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8456:             $responsenum = $respnumlookup->{$question-1};
                   8457:             if (ref($startline) eq 'HASH') { 
                   8458:                 $first = $startline->{$question-1};
                   8459:             }
                   8460:         } else {
                   8461:             $responsenum = $question-1;
                   8462:             $first = $first_bubble_line{$responsenum};
                   8463:         }
                   8464:         $current_line = $first + 1;
                   8465:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8466:     }
1.497     foxr     8467:     if ($lines > 1) {
1.503     raeburn  8468:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8469:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8470:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8471:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8472:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8473:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8474:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8475:             $r->print(
                   8476:                 &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)
                   8477:                .'<br /><br />'
                   8478:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8479:                .'<br />'
                   8480:                .&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.')
                   8481:                .'<br />'
                   8482:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8483:                .'<br /><br />'
                   8484:             );
1.503     raeburn  8485:         } else {
                   8486:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8487:         }
1.497     foxr     8488:     }
                   8489:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8490:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8491: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8492: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8493:         push(@linenums,$current_line);
1.497     foxr     8494: 	$current_line++;
                   8495:     }
                   8496:     if ($lines > 1) {
                   8497: 	$r->print("<hr /><br />");
                   8498:     }
1.503     raeburn  8499:     return @linenums;
1.157     albertel 8500: }
1.423     albertel 8501: 
                   8502: =pod
                   8503: 
                   8504: =item scantron_bubble_selector
                   8505:   
                   8506:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8507:    possibly showing the existing the selected bubbles if known
1.423     albertel 8508: 
                   8509:  Arguments:
                   8510:     $r           - Apache request object
1.754     raeburn  8511:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8512:     $line        - Number of the line being displayed.
1.503     raeburn  8513:     $questionnum - Question number (may include subquestion)
                   8514:     $error       - Type of error.
1.497     foxr     8515:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8516: 
                   8517: =cut
                   8518: 
1.157     albertel 8519: sub scantron_bubble_selector {
1.503     raeburn  8520:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8521:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8522: 
                   8523:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8524:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8525:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8526:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8527:             $max=$$scan_config{'BubblesPerRow'};
                   8528:             if (($scmode eq 'number') && ($max > 10)) {
                   8529:                 $max = 10;
                   8530:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8531:                 $max = 26;
                   8532:             }
                   8533:         } else {
                   8534:             $max = 10;
                   8535:         }
                   8536:     }
1.274     albertel 8537: 
1.157     albertel 8538:     my @alphabet=('A'..'Z');
1.503     raeburn  8539:     $r->print(&Apache::loncommon::start_data_table().
                   8540:               &Apache::loncommon::start_data_table_row());
                   8541:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8542:     for (my $i=0;$i<$max+1;$i++) {
                   8543: 	$r->print("\n".'<td align="center">');
                   8544: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8545: 	else { $r->print('&nbsp;'); }
                   8546: 	$r->print('</td>');
                   8547:     }
1.503     raeburn  8548:     $r->print(&Apache::loncommon::end_data_table_row().
                   8549:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8550:     for (my $i=0;$i<$max;$i++) {
                   8551: 	$r->print("\n".
                   8552: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8553: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8554:     }
1.503     raeburn  8555:     my $nobub_checked = ' ';
                   8556:     if ($error eq 'missingbubble') {
                   8557:         $nobub_checked = ' checked = "checked" ';
                   8558:     }
                   8559:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8560: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8561:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8562:               $line.'" value="'.$questionnum.'" /></td>');
                   8563:     $r->print(&Apache::loncommon::end_data_table_row().
                   8564:               &Apache::loncommon::end_data_table());
1.157     albertel 8565: }
                   8566: 
1.423     albertel 8567: =pod
                   8568: 
                   8569: =item num_matches
                   8570: 
1.424     albertel 8571:    Counts the number of characters that are the same between the two arguments.
                   8572: 
                   8573:  Arguments:
                   8574:    $orig - CODE from the scanline
                   8575:    $code - CODE to match against
                   8576: 
                   8577:  Returns:
                   8578:    $count - integer count of the number of same characters between the
                   8579:             two arguments
                   8580: 
1.423     albertel 8581: =cut
                   8582: 
1.194     albertel 8583: sub num_matches {
                   8584:     my ($orig,$code) = @_;
                   8585:     my @code=split(//,$code);
                   8586:     my @orig=split(//,$orig);
                   8587:     my $same=0;
                   8588:     for (my $i=0;$i<scalar(@code);$i++) {
                   8589: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8590:     }
                   8591:     return $same;
                   8592: }
                   8593: 
1.423     albertel 8594: =pod
                   8595: 
                   8596: =item scantron_get_closely_matching_CODEs
                   8597: 
1.424     albertel 8598:    Cycles through all CODEs and finds the set that has the greatest
                   8599:    number of same characters as the provided CODE
                   8600: 
                   8601:  Arguments:
                   8602:    $allcodes - hash ref returned by &get_codes()
                   8603:    $CODE     - CODE from the current scanline
                   8604: 
                   8605:  Returns:
                   8606:    2 element list
                   8607:     - first elements is number of how closely matching the best fit is 
                   8608:       (5 means best set has 5 matching characters)
                   8609:     - second element is an arrary ref containing the set of valid CODEs
                   8610:       that best fit the passed in CODE
                   8611: 
1.423     albertel 8612: =cut
                   8613: 
1.194     albertel 8614: sub scantron_get_closely_matching_CODEs {
                   8615:     my ($allcodes,$CODE)=@_;
                   8616:     my @CODEs;
                   8617:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8618: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8619:     }
                   8620: 
                   8621:     return ($#CODEs,$CODEs[-1]);
                   8622: }
                   8623: 
1.423     albertel 8624: =pod
                   8625: 
                   8626: =item get_codes
                   8627: 
1.424     albertel 8628:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8629:    set of remembered CODEs.
                   8630: 
                   8631:  Arguments:
                   8632:   $old_name - name of the set of remembered CODEs
                   8633:   $cdom     - domain of the course
                   8634:   $cnum     - internal course name
                   8635: 
                   8636:  Returns:
                   8637:   %allcodes - keys are the valid CODEs, values are all 1
                   8638: 
1.423     albertel 8639: =cut
                   8640: 
1.194     albertel 8641: sub get_codes {
1.280     foxr     8642:     my ($old_name, $cdom, $cnum) = @_;
                   8643:     if (!$old_name) {
                   8644: 	$old_name=$env{'form.scantron_CODElist'};
                   8645:     }
                   8646:     if (!$cdom) {
                   8647: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8648:     }
                   8649:     if (!$cnum) {
                   8650: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8651:     }
1.278     albertel 8652:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8653: 				    $cdom,$cnum);
                   8654:     my %allcodes;
                   8655:     if ($result{"type\0$old_name"} eq 'number') {
                   8656: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8657:     } else {
                   8658: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8659:     }
1.194     albertel 8660:     return %allcodes;
                   8661: }
                   8662: 
1.423     albertel 8663: =pod
                   8664: 
                   8665: =item scantron_validate_CODE
                   8666: 
1.424     albertel 8667:    Validates all scanlines in the selected file to not have any
                   8668:    invalid or underspecified CODEs and that none of the codes are
                   8669:    duplicated if this was requested.
                   8670: 
1.423     albertel 8671: =cut
                   8672: 
1.157     albertel 8673: sub scantron_validate_CODE {
                   8674:     my ($r,$currentphase) = @_;
1.754     raeburn  8675:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8676:     if ($scantron_config{'CODElocation'} &&
                   8677: 	$scantron_config{'CODEstart'} &&
                   8678: 	$scantron_config{'CODElength'}) {
1.257     albertel 8679: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8680: 	    &FIXME_blow_up()
                   8681: 	}
                   8682:     } else {
                   8683: 	return (0,$currentphase+1);
                   8684:     }
                   8685:     
                   8686:     my %usedCODEs;
                   8687: 
1.194     albertel 8688:     my %allcodes=&get_codes();
1.186     albertel 8689: 
1.582     raeburn  8690:     my $nav_error;
1.649     raeburn  8691:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8692:     if ($nav_error) {
                   8693:         $r->print(&navmap_errormsg());
                   8694:         return(1,$currentphase);
                   8695:     }
1.447     foxr     8696: 
1.186     albertel 8697:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8698:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8699: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8700: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8701: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8702: 						 $scan_data);
                   8703: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8704: 	my $error=0;
1.224     albertel 8705: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8706: 	    &scantron_get_correction($r,$i,$scan_record,
                   8707: 				     \%scantron_config,
                   8708: 				     $line,'incorrectCODE',\%allcodes);
                   8709: 	    return(1,$currentphase);
                   8710: 	}
1.221     albertel 8711: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8712: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8713: 	    &scantron_get_correction($r,$i,$scan_record,
                   8714: 				     \%scantron_config,
1.194     albertel 8715: 				     $line,'incorrectCODE',\%allcodes);
                   8716: 	    return(1,$currentphase);
1.186     albertel 8717: 	}
1.214     albertel 8718: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8719: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8720: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8721: 	    &scantron_get_correction($r,$i,$scan_record,
                   8722: 				     \%scantron_config,
1.194     albertel 8723: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8724: 	    return(1,$currentphase);
1.186     albertel 8725: 	}
1.524     raeburn  8726: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8727:     }
1.157     albertel 8728:     return (0,$currentphase+1);
                   8729: }
                   8730: 
1.423     albertel 8731: =pod
                   8732: 
                   8733: =item scantron_validate_doublebubble
                   8734: 
1.424     albertel 8735:    Validates all scanlines in the selected file to not have any
                   8736:    bubble lines with multiple bubbles marked.
                   8737: 
1.423     albertel 8738: =cut
                   8739: 
1.157     albertel 8740: sub scantron_validate_doublebubble {
                   8741:     my ($r,$currentphase) = @_;
                   8742:     #get student info
                   8743:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8744:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8745:     my (undef,undef,$sequence)=
                   8746:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8747: 
                   8748:     #get scantron line setup
1.754     raeburn  8749:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8750:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8751: 
                   8752:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8753:     unless (ref($navmap)) {
                   8754:         $r->print(&navmap_errormsg());
                   8755:         return(1,$currentphase);
                   8756:     }
                   8757:     my $map=$navmap->getResourceByUrl($sequence);
                   8758:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8759:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8760:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8761:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8762: 
1.583     raeburn  8763:     my $nav_error;
1.691     raeburn  8764:     if (ref($map)) {
                   8765:         $randomorder = $map->randomorder();
                   8766:         $randompick = $map->randompick();
1.788     raeburn  8767:         unless ($randomorder || $randompick) {
                   8768:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8769:                 if ($res->randomorder()) {
                   8770:                     $randomorder = 1;
                   8771:                 }
                   8772:                 if ($res->randompick()) {
                   8773:                     $randompick = 1;
                   8774:                 }
                   8775:                 last if ($randomorder || $randompick);
                   8776:             }
                   8777:         }
1.691     raeburn  8778:         if ($randomorder || $randompick) {
                   8779:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8780:             if ($nav_error) {
                   8781:                 $r->print(&navmap_errormsg());
                   8782:                 return(1,$currentphase);
                   8783:             }
                   8784:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8785:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8786:         }
                   8787:     } else {
                   8788:         $r->print(&navmap_errormsg());
                   8789:         return(1,$currentphase);
                   8790:     }
                   8791: 
1.649     raeburn  8792:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8793:     if ($nav_error) {
                   8794:         $r->print(&navmap_errormsg());
                   8795:         return(1,$currentphase);
                   8796:     }
1.447     foxr     8797: 
1.157     albertel 8798:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8799: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8800: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8801: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8802: 						 $scan_data,undef,\%idmap,$randomorder,
                   8803:                                                  $randompick,$sequence,\@master_seq,
                   8804:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8805:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8806: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8807: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8808: 				 'doublebubble',
1.691     raeburn  8809: 				 $$scan_record{'scantron.doubleerror'},
                   8810:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8811:     	return (1,$currentphase);
                   8812:     }
                   8813:     return (0,$currentphase+1);
                   8814: }
                   8815: 
1.423     albertel 8816: 
1.503     raeburn  8817: sub scantron_get_maxbubble {
1.649     raeburn  8818:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8819:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8820: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8821: 	&restore_bubble_lines();
1.257     albertel 8822: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8823:     }
1.330     albertel 8824: 
1.447     foxr     8825:     my (undef, undef, $sequence) =
1.257     albertel 8826: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8827: 
1.447     foxr     8828:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8829:     unless (ref($navmap)) {
                   8830:         if (ref($nav_error)) {
                   8831:             $$nav_error = 1;
                   8832:         }
1.591     raeburn  8833:         return;
1.582     raeburn  8834:     }
1.191     albertel 8835:     my $map=$navmap->getResourceByUrl($sequence);
                   8836:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8837:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8838: 
                   8839:     &Apache::lonxml::clear_problem_counter();
                   8840: 
1.557     raeburn  8841:     my $uname       = $env{'user.name'};
                   8842:     my $udom        = $env{'user.domain'};
1.435     foxr     8843:     my $cid         = $env{'request.course.id'};
                   8844:     my $total_lines = 0;
                   8845:     %bubble_lines_per_response = ();
1.447     foxr     8846:     %first_bubble_line         = ();
1.503     raeburn  8847:     %subdivided_bubble_lines   = ();
                   8848:     %responsetype_per_response = ();
1.691     raeburn  8849:     %masterseq_id_responsenum  = ();
1.554     raeburn  8850: 
1.447     foxr     8851:     my $response_number = 0;
                   8852:     my $bubble_line     = 0;
1.191     albertel 8853:     foreach my $resource (@resources) {
1.691     raeburn  8854:         my $resid = $resource->id(); 
1.672     raeburn  8855:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8856:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8857:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8858: 	    foreach my $part_id (@{$parts}) {
                   8859:                 my $lines;
                   8860: 
                   8861: 	        # TODO - make this a persistent hash not an array.
                   8862: 
                   8863:                 # optionresponse, matchresponse and rankresponse type items 
                   8864:                 # render as separate sub-questions in exam mode.
                   8865:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8866:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8867:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8868:                     my ($numbub,$numshown);
                   8869:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8870:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8871:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8872:                         }
                   8873:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8874:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8875:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8876:                         }
                   8877:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8878:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8879:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8880:                         }
                   8881:                     }
                   8882:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8883:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8884:                     }
1.649     raeburn  8885:                     my $bubbles_per_row =
                   8886:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8887:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8888:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8889:                         $inner_bubble_lines++;
                   8890:                     }
                   8891:                     for (my $i=0; $i<$numshown; $i++) {
                   8892:                         $subdivided_bubble_lines{$response_number} .= 
                   8893:                             $inner_bubble_lines.',';
                   8894:                     }
                   8895:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8896:                     $lines = $numshown * $inner_bubble_lines;
                   8897:                 } else {
                   8898:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8899:                 }
1.542     raeburn  8900: 
                   8901:                 $first_bubble_line{$response_number} = $bubble_line;
                   8902: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8903:                 $responsetype_per_response{$response_number} = 
                   8904:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8905:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8906: 	        $response_number++;
                   8907: 
                   8908: 	        $bubble_line +=  $lines;
                   8909: 	        $total_lines +=  $lines;
                   8910: 	    }
                   8911:         }
                   8912:     }
1.552     raeburn  8913:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8914: 
                   8915:     &save_bubble_lines();
                   8916:     $env{'form.scantron_maxbubble'} =
                   8917: 	$total_lines;
                   8918:     return $env{'form.scantron_maxbubble'};
                   8919: }
1.523     raeburn  8920: 
1.649     raeburn  8921: sub bubblesheet_bubbles_per_row {
                   8922:     my ($scantron_config) = @_;
                   8923:     my $bubbles_per_row;
                   8924:     if (ref($scantron_config) eq 'HASH') {
                   8925:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8926:     }
                   8927:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8928:         $bubbles_per_row = 10;
                   8929:     }
                   8930:     return $bubbles_per_row;
                   8931: }
                   8932: 
1.157     albertel 8933: sub scantron_validate_missingbubbles {
                   8934:     my ($r,$currentphase) = @_;
                   8935:     #get student info
                   8936:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8937:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8938:     my (undef,undef,$sequence)=
                   8939:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8940: 
                   8941:     #get scantron line setup
1.754     raeburn  8942:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8943:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8944: 
                   8945:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8946:     unless (ref($navmap)) {
                   8947:         $r->print(&navmap_errormsg());
                   8948:         return(1,$currentphase);
                   8949:     }
                   8950: 
                   8951:     my $map=$navmap->getResourceByUrl($sequence);
                   8952:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8953:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8954:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8955:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8956: 
1.582     raeburn  8957:     my $nav_error;
1.691     raeburn  8958:     if (ref($map)) {
                   8959:         $randomorder = $map->randomorder();
                   8960:         $randompick = $map->randompick();
1.788     raeburn  8961:         unless ($randomorder || $randompick) {
                   8962:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8963:                 if ($res->randomorder()) {
                   8964:                     $randomorder = 1;
                   8965:                 }
                   8966:                 if ($res->randompick()) {
                   8967:                     $randompick = 1;
                   8968:                 }
                   8969:                 last if ($randomorder || $randompick);
                   8970:             }
                   8971:         }
1.691     raeburn  8972:         if ($randomorder || $randompick) {
                   8973:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8974:             if ($nav_error) {
                   8975:                 $r->print(&navmap_errormsg());
                   8976:                 return(1,$currentphase);
                   8977:             }
                   8978:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8979:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8980:         }
                   8981:     } else {
                   8982:         $r->print(&navmap_errormsg());
                   8983:         return(1,$currentphase);
                   8984:     }
                   8985: 
                   8986: 
1.649     raeburn  8987:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8988:     if ($nav_error) {
1.691     raeburn  8989:         $r->print(&navmap_errormsg());
1.693     raeburn  8990:         return(1,$currentphase);
1.582     raeburn  8991:     }
1.691     raeburn  8992: 
1.157     albertel 8993:     if (!$max_bubble) { $max_bubble=2**31; }
                   8994:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8995: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8996: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8997: 	my $scan_record =
                   8998:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8999: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   9000:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   9001:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 9002: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   9003: 	my @to_correct;
1.470     foxr     9004: 	
                   9005: 	# Probably here's where the error is...
                   9006: 
1.157     albertel 9007: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  9008:             my $lastbubble;
                   9009:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   9010:                my $question = $1;
                   9011:                my $subquestion = $2;
1.691     raeburn  9012:                my ($first,$responsenum);
                   9013:                if ($randomorder || $randompick) {
                   9014:                    $responsenum = $respnumlookup{$question-1};
                   9015:                    $first = $startline{$question-1};
                   9016:                } else {
                   9017:                    $responsenum = $question-1; 
                   9018:                    $first = $first_bubble_line{$responsenum};
                   9019:                }
                   9020:                if (!defined($first)) { next; }
                   9021:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  9022:                my $subcount = 1;
                   9023:                while ($subcount<$subquestion) {
                   9024:                    $first += $subans[$subcount-1];
                   9025:                    $subcount ++;
                   9026:                }
                   9027:                my $count = $subans[$subquestion-1];
                   9028:                $lastbubble = $first + $count;
                   9029:             } else {
1.691     raeburn  9030:                my ($first,$responsenum);
                   9031:                if ($randomorder || $randompick) {
                   9032:                    $responsenum = $respnumlookup{$missing-1};
                   9033:                    $first = $startline{$missing-1};
                   9034:                } else {
                   9035:                    $responsenum = $missing-1;
                   9036:                    $first = $first_bubble_line{$responsenum};
                   9037:                }
                   9038:                if (!defined($first)) { next; }
                   9039:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  9040:             }
                   9041:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 9042: 	    push(@to_correct,$missing);
                   9043: 	}
                   9044: 	if (@to_correct) {
                   9045: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  9046: 				     $line,'missingbubble',\@to_correct,
                   9047:                                      $randomorder,$randompick,\%respnumlookup,
                   9048:                                      \%startline);
1.157     albertel 9049: 	    return (1,$currentphase);
                   9050: 	}
                   9051: 
                   9052:     }
                   9053:     return (0,$currentphase+1);
                   9054: }
                   9055: 
1.663     raeburn  9056: sub hand_bubble_option {
                   9057:     my (undef, undef, $sequence) =
                   9058:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9059:     return if ($sequence eq '');
                   9060:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9061:     unless (ref($navmap)) {
                   9062:         return;
                   9063:     }
                   9064:     my $needs_hand_bubbles;
                   9065:     my $map=$navmap->getResourceByUrl($sequence);
                   9066:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   9067:     foreach my $res (@resources) {
                   9068:         if (ref($res)) {
                   9069:             if ($res->is_problem()) {
                   9070:                 my $partlist = $res->parts();
                   9071:                 foreach my $part (@{ $partlist }) {
                   9072:                     my @types = $res->responseType($part);
                   9073:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   9074:                         $needs_hand_bubbles = 1;
                   9075:                         last;
                   9076:                     }
                   9077:                 }
                   9078:             }
                   9079:         }
                   9080:     }
                   9081:     if ($needs_hand_bubbles) {
1.754     raeburn  9082:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  9083:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9084:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   9085:                &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 />').
                   9086:                '<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  9087:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  9088:     }
                   9089:     return;
                   9090: }
1.423     albertel 9091: 
1.82      albertel 9092: sub scantron_process_students {
1.608     www      9093:     my ($r,$symb) = @_;
1.513     foxr     9094: 
1.257     albertel 9095:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     9096:     if (!$symb) {
                   9097: 	return '';
                   9098:     }
1.324     albertel 9099:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 9100: 
1.754     raeburn  9101:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  9102:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 9103:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 9104:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9105:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 9106:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9107:     unless (ref($navmap)) {
                   9108:         $r->print(&navmap_errormsg());
                   9109:         return '';
1.691     raeburn  9110:     }
1.83      albertel 9111:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9112:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.788     raeburn  9113:         %grader_randomlists_by_symb,%symb_for_examcode);
1.677     raeburn  9114:     if (ref($map)) {
                   9115:         $randomorder = $map->randomorder();
1.689     raeburn  9116:         $randompick = $map->randompick();
1.788     raeburn  9117:         unless ($randomorder || $randompick) {
                   9118:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9119:                 if ($res->randomorder()) {
                   9120:                     $randomorder = 1;
                   9121:                 }
                   9122:                 if ($res->randompick()) {
                   9123:                     $randompick = 1;
                   9124:                 }
                   9125:                 last if ($randomorder || $randompick);
                   9126:             }
                   9127:         }
1.691     raeburn  9128:     } else {
                   9129:         $r->print(&navmap_errormsg());
                   9130:         return '';
1.677     raeburn  9131:     }
1.691     raeburn  9132:     my $nav_error;
1.83      albertel 9133:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9134:     if ($randomorder || $randompick) {
1.788     raeburn  9135:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
1.691     raeburn  9136:         if ($nav_error) {
                   9137:             $r->print(&navmap_errormsg());
                   9138:             return '';
                   9139:         }
                   9140:     }
1.557     raeburn  9141:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  9142:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  9143: 
1.554     raeburn  9144:     my ($uname,$udom);
1.82      albertel 9145:     my $result= <<SCANTRONFORM;
1.81      albertel 9146: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   9147:   <input type="hidden" name="command" value="scantron_configphase" />
                   9148:   $default_form_data
                   9149: SCANTRONFORM
1.82      albertel 9150:     $r->print($result);
                   9151: 
1.770     raeburn  9152:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 9153:     my @delayqueue;
1.542     raeburn  9154:     my (%completedstudents,%scandata);
1.770     raeburn  9155: 
1.520     www      9156:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9157:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9158:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   9159:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9160:     $r->print('<br />');
1.140     albertel 9161:     my $start=&Time::HiRes::time();
1.158     albertel 9162:     my $i=-1;
1.542     raeburn  9163:     my $started;
1.447     foxr     9164: 
1.649     raeburn  9165:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9166:     if ($nav_error) {
                   9167:         $r->print(&navmap_errormsg());
                   9168:         return '';
                   9169:     }
                   9170: 
1.513     foxr     9171:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9172:     # the user and return.
                   9173: 
                   9174:     if ($ssi_error) {
                   9175: 	$r->print("</form>");
                   9176: 	&ssi_print_error($r);
1.520     www      9177:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9178: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9179:     }
1.447     foxr     9180: 
1.755     raeburn  9181:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9182:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  9183:     my %orderedforcode;
1.542     raeburn  9184: 
1.157     albertel 9185:     while ($i<$scanlines->{'count'}) {
                   9186:  	($uname,$udom)=('','');
                   9187:  	$i++;
1.200     albertel 9188:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9189:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9190: 	if ($started) {
1.667     www      9191: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9192: 	}
                   9193: 	$started=1;
1.691     raeburn  9194:         my %respnumlookup = ();
                   9195:         my %startline = ();
                   9196:         my $total;
1.157     albertel 9197:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9198:                                                  $scan_data,undef,\%idmap,$randomorder,
                   9199:                                                  $randompick,$sequence,\@master_seq,
                   9200:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9201:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9202:                                                  \$total);
1.157     albertel 9203:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9204:  					      \%idmap,$i)) {
                   9205:   	    &scantron_add_delay(\@delayqueue,$line,
                   9206:  				'Unable to find a student that matches',1);
                   9207:  	    next;
                   9208:   	}
                   9209:  	if (exists $completedstudents{$uname}) {
                   9210:  	    &scantron_add_delay(\@delayqueue,$line,
                   9211:  				'Student '.$uname.' has multiple sheets',2);
                   9212:  	    next;
                   9213:  	}
1.677     raeburn  9214:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  9215:         if (($checksec ne '') && ($checksec ne $usec)) {
                   9216:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   9217:                 &scantron_add_delay(\@delayqueue,$line,
                   9218:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   9219:                 next;
                   9220:             }
                   9221:         }
1.677     raeburn  9222:         my $user = $uname.':'.$usec;
1.157     albertel 9223:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9224: 
1.677     raeburn  9225:         my $scancode;
                   9226:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9227:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9228:             $scancode = $scan_record->{'scantron.CODE'};
                   9229:         } else {
                   9230:             $scancode = '';
                   9231:         }
                   9232: 
                   9233:         my @mapresources = @resources;
1.689     raeburn  9234:         if ($randomorder || $randompick) {
1.678     raeburn  9235:             @mapresources = 
1.691     raeburn  9236:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9237:                              \%orderedforcode);
1.677     raeburn  9238:         }
1.586     raeburn  9239:         my (%partids_by_symb,$res_error);
1.677     raeburn  9240:         foreach my $resource (@mapresources) {
1.586     raeburn  9241:             my $ressymb;
                   9242:             if (ref($resource)) {
                   9243:                 $ressymb = $resource->symb();
                   9244:             } else {
                   9245:                 $res_error = 1;
                   9246:                 last;
                   9247:             }
1.557     raeburn  9248:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9249:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9250:                 my $currcode;
                   9251:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9252:                     $currcode = $scancode;
                   9253:                 }
1.557     raeburn  9254:                 my ($analysis,$parts) =
1.672     raeburn  9255:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  9256:                                               $uname,$udom,undef,$bubbles_per_row,
                   9257:                                               $currcode);
1.557     raeburn  9258:                 $partids_by_symb{$ressymb} = $parts;
                   9259:             } else {
                   9260:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9261:             }
1.554     raeburn  9262:         }
                   9263: 
1.586     raeburn  9264:         if ($res_error) {
                   9265:             &scantron_add_delay(\@delayqueue,$line,
                   9266:                                 'An error occurred while grading student '.$uname,2);
                   9267:             next;
                   9268:         }
                   9269: 
1.330     albertel 9270: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9271:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9272: 
                   9273: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9274: 	    &scantron_putfile($scanlines,$scan_data);
                   9275: 	}
1.161     albertel 9276: 	
1.542     raeburn  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.542     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:             return '';      # Why return ''?  Beats me.
                   9287:         }
1.513     foxr     9288: 
1.692     raeburn  9289:         if (($scancode) && ($randomorder || $randompick)) {
1.788     raeburn  9290:             foreach my $key (keys(%symb_for_examcode)) {
                   9291:                 my $symb_in_map = $symb_for_examcode{$key};
                   9292:                 if ($symb_in_map ne '') {
                   9293:                     my $parmresult =
                   9294:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   9295:                                                                '0_examcode',2,$scancode,
                   9296:                                                                'string_examcode',$uname,
                   9297:                                                                $udom);
                   9298:                 }
                   9299:             }
1.692     raeburn  9300:         }
1.140     albertel 9301: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9302:         if ($env{'form.verifyrecord'}) {
                   9303:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  9304:             if ($randompick) {
                   9305:                 if ($total) {
                   9306:                     $lastpos = $total*$scantron_config{'Qlength'};
                   9307:                 }
                   9308:             }
                   9309: 
1.542     raeburn  9310:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9311:             chomp($studentdata);
                   9312:             $studentdata =~ s/\r$//;
                   9313:             my $studentrecord = '';
                   9314:             my $counter = -1;
1.677     raeburn  9315:             foreach my $resource (@mapresources) {
1.554     raeburn  9316:                 my $ressymb = $resource->symb();
1.542     raeburn  9317:                 ($counter,my $recording) =
                   9318:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9319:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9320:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9321:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9322:                 $studentrecord .= $recording;
                   9323:             }
                   9324:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9325:                 &Apache::lonxml::clear_problem_counter();
                   9326:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9327:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  9328:                                            $bubbles_per_row,$randomorder,$randompick,
                   9329:                                            \%respnumlookup,\%startline) 
                   9330:                     eq 'ssi_error') {
1.554     raeburn  9331:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9332:                     $r->print("</form>");
                   9333:                     &ssi_print_error($r);
                   9334:                     &Apache::lonnet::remove_lock($lock);
                   9335:                     delete($completedstudents{$uname});
                   9336:                     return '';
                   9337:                 }
1.542     raeburn  9338:                 $counter = -1;
                   9339:                 $studentrecord = '';
1.677     raeburn  9340:                 foreach my $resource (@mapresources) {
1.554     raeburn  9341:                     my $ressymb = $resource->symb();
1.542     raeburn  9342:                     ($counter,my $recording) =
                   9343:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9344:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9345:                                                  \%scantron_config,\%lettdig,$numletts,
                   9346:                                                  $randomorder,$randompick,\%respnumlookup,
                   9347:                                                  \%startline);
1.542     raeburn  9348:                     $studentrecord .= $recording;
                   9349:                 }
                   9350:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   9351:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9352:                     if ($scancode eq '') {
1.658     bisitz   9353:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9354:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9355:                     } else {
1.658     bisitz   9356:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9357:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9358:                     }
                   9359:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9360:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9361:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9362:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9363:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9364:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   9365:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9366:                               &Apache::loncommon::end_data_table_row().
                   9367:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9368:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   9369:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9370:                               &Apache::loncommon::end_data_table_row().
                   9371:                               &Apache::loncommon::end_data_table().'</p>');
                   9372:                 } else {
                   9373:                     $r->print('<br /><span class="LC_warning">'.
                   9374:                              &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 />'.
                   9375:                              &mt("As a consequence, this user's submission history records two tries.").
                   9376:                                  '</span><br />');
                   9377:                 }
                   9378:             }
                   9379:         }
1.543     raeburn  9380:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9381:     } continue {
1.330     albertel 9382: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9383: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9384:     }
1.140     albertel 9385:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9386:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9387: #    my $lasttime = &Time::HiRes::time()-$start;
                   9388: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9389: 
1.200     albertel 9390:     $r->print("</form>");
1.157     albertel 9391:     return '';
1.75      albertel 9392: }
1.157     albertel 9393: 
1.557     raeburn  9394: sub graders_resources_pass {
1.649     raeburn  9395:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9396:         $bubbles_per_row) = @_;
1.557     raeburn  9397:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9398:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9399:         foreach my $resource (@{$resources}) {
                   9400:             my $ressymb = $resource->symb();
                   9401:             my ($analysis,$parts) =
                   9402:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  9403:                                           $env{'user.name'},$env{'user.domain'},
                   9404:                                           1,$bubbles_per_row);
1.557     raeburn  9405:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9406:             if (ref($analysis) eq 'HASH') {
                   9407:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9408:                     $grader_randomlists_by_symb->{$ressymb} =
                   9409:                         $analysis->{'parts_withrandomlist'};
                   9410:                 }
                   9411:             }
                   9412:         }
                   9413:     }
                   9414:     return;
                   9415: }
                   9416: 
1.678     raeburn  9417: =pod
                   9418: 
                   9419: =item users_order
                   9420: 
                   9421:   Returns array of resources in current map, ordered based on either CODE,
                   9422:   if this is a CODEd exam, or based on student's identity if this is a 
                   9423:   "NAMEd" exam.
                   9424: 
1.691     raeburn  9425:   Should be used when randomorder and/or randompick applied when the 
                   9426:   corresponding exam was printed, prior to students completing bubblesheets 
                   9427:   for the version of the exam the student received.
1.678     raeburn  9428: 
                   9429: =cut
                   9430: 
                   9431: sub users_order  {
1.691     raeburn  9432:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9433:     my @mapresources;
1.691     raeburn  9434:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9435:         return @mapresources;
1.691     raeburn  9436:     }
                   9437:     if ($scancode) {
                   9438:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9439:             @mapresources = @{$orderedforcode->{$scancode}};
                   9440:         } else {
                   9441:             $env{'form.CODE'} = $scancode;
                   9442:             my $actual_seq =
                   9443:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9444:                                                                $master_seq,
                   9445:                                                                $user,$scancode,1);
                   9446:             if (ref($actual_seq) eq 'ARRAY') {
                   9447:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9448:                 if (ref($orderedforcode) eq 'HASH') {
                   9449:                     if (@mapresources > 0) { 
                   9450:                         $orderedforcode->{$scancode} = \@mapresources;
                   9451:                     }
                   9452:                 }
                   9453:             }
                   9454:             delete($env{'form.CODE'});
1.678     raeburn  9455:         }
                   9456:     } else {
                   9457:         my $actual_seq =
                   9458:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9459:                                                            $master_seq,
1.688     raeburn  9460:                                                            $user,undef,1);
1.678     raeburn  9461:         if (ref($actual_seq) eq 'ARRAY') {
                   9462:             @mapresources = 
                   9463:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9464:         }
1.691     raeburn  9465:     }
                   9466:     return @mapresources;
1.678     raeburn  9467: }
                   9468: 
1.542     raeburn  9469: sub grade_student_bubbles {
1.691     raeburn  9470:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9471:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9472:     my $uselookup = 0;
                   9473:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9474:         (ref($startline) eq 'HASH')) {
                   9475:         $uselookup = 1;
                   9476:     }
                   9477: 
1.554     raeburn  9478:     if (ref($resources) eq 'ARRAY') {
                   9479:         my $count = 0;
                   9480:         foreach my $resource (@{$resources}) {
                   9481:             my $ressymb = $resource->symb();
                   9482:             my %form = ('submitted'      => 'scantron',
                   9483:                         'grade_target'   => 'grade',
                   9484:                         'grade_username' => $uname,
                   9485:                         'grade_domain'   => $udom,
                   9486:                         'grade_courseid' => $env{'request.course.id'},
                   9487:                         'grade_symb'     => $ressymb,
                   9488:                         'CODE'           => $scancode
                   9489:                        );
1.649     raeburn  9490:             if ($bubbles_per_row ne '') {
                   9491:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9492:             }
1.663     raeburn  9493:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9494:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9495:             }
1.554     raeburn  9496:             if (ref($parts) eq 'HASH') {
                   9497:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9498:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9499:                         if ($uselookup) {
                   9500:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9501:                         } else {
                   9502:                             $form{'scantron_questnum_start.'.$part} =
                   9503:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9504:                         }
1.554     raeburn  9505:                         $count++;
                   9506:                     }
                   9507:                 }
                   9508:             }
                   9509:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9510:             return 'ssi_error' if ($ssi_error);
                   9511:             last if (&Apache::loncommon::connection_aborted($r));
                   9512:         }
1.542     raeburn  9513:     }
                   9514:     return;
                   9515: }
                   9516: 
1.157     albertel 9517: sub scantron_upload_scantron_data {
1.767     raeburn  9518:     my ($r,$symb) = @_;
1.565     raeburn  9519:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9520:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9521:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9522:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9523:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9524: 							  'domainid',
1.565     raeburn  9525: 							  'coursename',$dom);
                   9526:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9527:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9528:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9529:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9530:     &js_escape(\$nofile_alert);
1.579     raeburn  9531:     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  9532:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9533:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9534:     function checkUpload(formname) {
                   9535: 	if (formname.upfile.value == "") {
1.579     raeburn  9536: 	    alert("'.$nofile_alert.'");
1.157     albertel 9537: 	    return false;
                   9538: 	}
1.565     raeburn  9539:         if (formname.courseid.value == "") {
1.579     raeburn  9540:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9541:             return false;
                   9542:         }
1.157     albertel 9543: 	formname.submit();
                   9544:     }
1.565     raeburn  9545: 
                   9546:     function ToSyllabus() {
                   9547:         var cdom = '."'$dom'".';
                   9548:         var cnum = document.rules.courseid.value;
                   9549:         if (cdom == "" || cdom == null) {
                   9550:             return;
                   9551:         }
                   9552:         if (cnum == "" || cnum == null) {
                   9553:            return;
                   9554:         }
                   9555:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9556:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9557:         return;
                   9558:     }
                   9559: 
1.754     raeburn  9560:     '.$formatjs.'
1.597     wenzelju 9561: '));
                   9562:     $r->print('
1.648     bisitz   9563: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9564: 
1.492     albertel 9565: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9566: '.$default_form_data.
                   9567:   &Apache::lonhtmlcommon::start_pick_box().
                   9568:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9569:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9570:   &Apache::lonhtmlcommon::row_closure().
                   9571:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9572:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9573:   &Apache::lonhtmlcommon::row_closure().
                   9574:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9575:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9576:   &Apache::lonhtmlcommon::row_closure());
                   9577:     if ($formatoptions) {
                   9578:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9579:                   &Apache::lonhtmlcommon::row_closure());
                   9580:     }
                   9581:     $r->print(
1.565     raeburn  9582:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9583:   '<input type="file" name="upfile" size="50" />'.
                   9584:   &Apache::lonhtmlcommon::row_closure(1).
                   9585:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9586: 
1.492     albertel 9587: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9588: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9589: </form>
1.492     albertel 9590: ');
1.157     albertel 9591:     return '';
                   9592: }
                   9593: 
1.754     raeburn  9594: sub scantron_upload_dataformat {
                   9595:     my ($dom) = @_;
                   9596:     my ($formatoptions,$formattitle,$formatjs);
                   9597:     $formatjs = <<'END';
                   9598: function toggleScantab(form) {
                   9599:    return;
                   9600: }
                   9601: END
                   9602:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9603:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9604:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9605:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9606:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9607:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  9608:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   9609:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9610:                             my ($onclick,$formatextra,$singleline);
                   9611:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9612:                             my $count = 0;
                   9613:                             foreach my $line (@lines) {
1.790   ! raeburn  9614:                                 next if (($line =~ /^\#/) || ($line eq ''));
1.756     raeburn  9615:                                 $singleline = $line;
                   9616:                                 $count ++;
                   9617:                             }
                   9618:                             if ($count > 1) {
                   9619:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  9620:                                                '<span class="LC_nobreak">'.
1.776     raeburn  9621:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  9622:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  9623:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9624:                                 $formatjs = <<"END";
1.754     raeburn  9625: function toggleScantab(form) {
                   9626:     var divid = 'bubbletype';
                   9627:     if (document.getElementById(divid)) {
                   9628:         var radioname = 'fileformat';
                   9629:         var num = form.elements[radioname].length;
                   9630:         if (num) {
                   9631:             for (var i=0; i<num; i++) {
                   9632:                 if (form.elements[radioname][i].checked) {
                   9633:                     var chosen = form.elements[radioname][i].value;
                   9634:                     if (chosen == 'dat') {
                   9635:                         document.getElementById(divid).style.display = 'none';
                   9636:                     } else if (chosen == 'csv') {
1.757     raeburn  9637:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  9638:                     }
                   9639:                 }
                   9640:             }
                   9641:         }
                   9642:     }
                   9643:     return;
                   9644: }
                   9645: 
                   9646: END
1.756     raeburn  9647:                             } elsif ($count == 1) {
                   9648:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9649:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9650:                             }
                   9651:                             $formattitle = &mt('File format');
                   9652:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9653:                                              &mt('Plain Text (no delimiters)').
                   9654:                                              '</label>'.('&nbsp;'x2).
                   9655:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9656:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9657:                         }
                   9658:                     }
                   9659:                 }
                   9660:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  9661:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9662:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  9663:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  9664:                         $formatoptions = &scantron_scantab();
                   9665:                     }
1.754     raeburn  9666:                 }
                   9667:             }
                   9668:         }
                   9669:     }
                   9670:     return ($formatoptions,$formattitle,$formatjs);
                   9671: }
1.423     albertel 9672: 
1.157     albertel 9673: sub scantron_upload_scantron_data_save {
1.767     raeburn  9674:     my ($r,$symb) = @_;
1.182     albertel 9675:     my $doanotherupload=
                   9676: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9677: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9678: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9679: 	'</form>'."\n";
1.257     albertel 9680:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9681: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  9682: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   9683:         !&Apache::lonnet::allowed('usc',
                   9684:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      9685: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9686: 	unless ($symb) {
1.182     albertel 9687: 	    $r->print($doanotherupload);
                   9688: 	}
1.162     albertel 9689: 	return '';
                   9690:     }
1.257     albertel 9691:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9692:     my $uploadedfile;
1.710     bisitz   9693:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9694:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9695:         $r->print(
                   9696:             &Apache::lonhtmlcommon::confirm_success(
                   9697:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9698:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9699:     } else {
1.754     raeburn  9700:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9701:         my $parser;
                   9702:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9703:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9704:                 my $is_csv;
                   9705:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9706:                 if (@possibles > 1) {
                   9707:                     if ($env{'form.fileformat'} eq 'csv') {
                   9708:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9709:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9710:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9711:                                     $is_csv = 1;
                   9712:                                 }
1.754     raeburn  9713:                             }
                   9714:                         }
                   9715:                     }
                   9716:                 } elsif (@possibles == 1) {
                   9717:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9718:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9719:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9720:                                 $is_csv = 1;
                   9721:                             }
1.754     raeburn  9722:                         }
                   9723:                     }
                   9724:                 }
                   9725:                 if ($is_csv) {
                   9726:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9727:                 }
                   9728:             }
                   9729:         }
                   9730:         my $result =
                   9731:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9732:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9733:         if ($result =~ m{^/uploaded/}) {
                   9734:             $r->print(
                   9735:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9736:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9737:                         (length($env{'form.upfile'})-1),
                   9738:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9739:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  9740:             if ($uploadedfile =~ /^scantron_orig_/) {
                   9741:                 my $logname = $uploadedfile;
                   9742:                 $logname =~ s/^scantron_orig_//;
                   9743:                 if ($logname ne '') {
                   9744:                     my $now = time;
                   9745:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   9746:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9747:                 }
                   9748:             }
1.567     raeburn  9749:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  9750:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   9751:         } else {
                   9752:             $r->print(
                   9753:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9754:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9755:                           $result,
1.568     raeburn  9756: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9757: 	}
                   9758:     }
1.174     albertel 9759:     if ($symb) {
1.612     www      9760: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9761:     } else {
1.182     albertel 9762: 	$r->print($doanotherupload);
1.174     albertel 9763:     }
1.157     albertel 9764:     return '';
                   9765: }
                   9766: 
1.567     raeburn  9767: sub validate_uploaded_scantron_file {
1.770     raeburn  9768:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   9769: 
1.567     raeburn  9770:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9771:     my @lines;
                   9772:     if ($scanlines ne '-1') {
                   9773:         @lines=split("\n",$scanlines,-1);
                   9774:     }
1.770     raeburn  9775:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   9776:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   9777:     if ($context eq 'download') {
                   9778:         $priv = 'mgr';
                   9779:     } else {
                   9780:         $priv = 'usc';
                   9781:     }
                   9782:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   9783:             (($env{'request.course.id'}) &&
                   9784:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   9785:         if ($env{'request.course.sec'} ne '') {
                   9786:             unless (&Apache::lonnet::allowed($priv,
                   9787:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   9788:                 unless ($context eq 'download') {
                   9789:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   9790:                 }
                   9791:                 return $output;
                   9792:             }
                   9793:             ($checksec,@possibles)=&gradable_sections();
                   9794:         }
                   9795:     }
1.567     raeburn  9796:     if (@lines) {
                   9797:         my (%counts,$max_match_format);
1.710     bisitz   9798:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9799:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9800:         my %idmap = &username_to_idmap($classlist);
                   9801:         foreach my $key (keys(%idmap)) {
                   9802:             my $lckey = lc($key);
                   9803:             $idmap{$lckey} = $idmap{$key};
                   9804:         }
                   9805:         my %unique_formats;
1.754     raeburn  9806:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9807:         foreach my $line (@formatlines) {
1.790   ! raeburn  9808:             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  9809:             my @config = split(/:/,$line);
                   9810:             my $idstart = $config[5];
                   9811:             my $idlength = $config[6];
                   9812:             if (($idstart ne '') && ($idlength > 0)) {
                   9813:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9814:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9815:                 } else {
                   9816:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9817:                 }
                   9818:             }
                   9819:         }
                   9820:         foreach my $key (keys(%unique_formats)) {
                   9821:             my ($idstart,$idlength) = split(':',$key);
                   9822:             %{$counts{$key}} = (
                   9823:                                'found'   => 0,
                   9824:                                'total'   => 0,
1.770     raeburn  9825:                                'totalanysec' => 0,
                   9826:                                'othersec' => 0,
1.567     raeburn  9827:                               );
                   9828:             foreach my $line (@lines) {
                   9829:                 next if ($line =~ /^#/);
                   9830:                 next if ($line =~ /^[\s\cz]*$/);
                   9831:                 my $id = substr($line,$idstart-1,$idlength);
                   9832:                 $id = lc($id);
                   9833:                 if (exists($idmap{$id})) {
1.770     raeburn  9834:                     if ($checksec ne '') {
                   9835:                         $counts{$key}{'totalanysec'} ++;
                   9836:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9837:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9838:                             if ($stusec ne $checksec) {
                   9839:                                 if (@possibles) {
                   9840:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   9841:                                         $counts{$key}{'othersec'} ++;
                   9842:                                         next;
                   9843:                                     }
                   9844:                                 } else {
                   9845:                                     $counts{$key}{'othersec'} ++;
                   9846:                                     next;
                   9847:                                 }
                   9848:                             }
                   9849:                         }
                   9850:                     }
1.567     raeburn  9851:                     $counts{$key}{'found'} ++;
                   9852:                 }
                   9853:                 $counts{$key}{'total'} ++;
                   9854:             }
                   9855:             if ($counts{$key}{'total'}) {
                   9856:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9857:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9858:                     $max_match_pct = $percent_match;
                   9859:                     $max_match_format = $key;
1.710     bisitz   9860:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9861:                     $max_match_count = $counts{$key}{'total'};
                   9862:                 }
                   9863:             }
                   9864:         }
1.770     raeburn  9865:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  9866:             my $format_descs;
                   9867:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9868:             for (my $i=0; $i<$numwithformat; $i++) {
                   9869:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9870:                 if ($i<$numwithformat-2) {
                   9871:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9872:                 } elsif ($i==$numwithformat-2) {
                   9873:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9874:                 } elsif ($i==$numwithformat-1) {
                   9875:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9876:                 }
                   9877:             }
                   9878:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9879:             $output .= '<br />';
                   9880:             if ($found_match_count == $max_match_count) {
                   9881:                 # 100% matching entries
                   9882:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9883:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9884:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9885:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9886:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9887:                     ' in the file (for the format defined for [_3]).',
                   9888:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9889:             } else {
                   9890:                 # Not all entries matching? -> Show warning and additional info
                   9891:                 $output .=
                   9892:                     &Apache::lonhtmlcommon::confirm_success(
                   9893:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9894:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9895:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9896:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9897:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9898:                         ' in the file (for the format defined for [_3]).',
                   9899:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9900:                     '<p class="LC_info">'.
                   9901:                     &mt('A low percentage of matches results from one of the following:').
                   9902:                     '</p><ul>'.
                   9903:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9904:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9905:                                '<i>'.$cdom.'</i>').'</li>'.
                   9906:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9907:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9908:                     '</ul>';
                   9909:             }
1.770     raeburn  9910:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9911:                 if ($counts{$max_match_format}{'othersec'}) {
                   9912:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   9913:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   9914:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   9915:                     &js_escape(\$confirmdel);
                   9916:                     $output .= '<p class="LC_warning">'.
                   9917:                                &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',
                   9918:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   9919:                                '<br />'.
                   9920:                                &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>').
                   9921:                                '</p><p>'.
                   9922:                                &mt('If you prefer to delete the file now, use: [_1]').
                   9923:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   9924:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   9925:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   9926:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   9927:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   9928:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   9929:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   9930:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   9931:                                '</form></p>';
                   9932:                 }
                   9933:             }
1.567     raeburn  9934:         }
1.770     raeburn  9935:         if (($context eq 'download') && ($checksec ne '')) {
                   9936:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9937:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   9938:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   9939:             }
                   9940:         } 
                   9941:     } elsif ($context ne 'download') {
1.710     bisitz   9942:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9943:     }
                   9944:     return $output;
                   9945: }
                   9946: 
1.770     raeburn  9947: sub gradable_sections {
                   9948:     my $checksec = $env{'request.course.sec'};
                   9949:     my @oksecs;
                   9950:     if ($checksec) {
                   9951:         my %availablesecs = &sections_grade_privs();
                   9952:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   9953:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   9954:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   9955:                     push(@oksecs,$sec);
                   9956:                 }
                   9957:             }
                   9958:             if (grep(/^all$/,@oksecs)) {
                   9959:                 undef($checksec);
                   9960:             }
                   9961:         }
                   9962:     }
                   9963:     return($checksec,@oksecs);
                   9964: }
                   9965: 
                   9966: sub sections_grade_privs {
                   9967:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9968:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9969:     my %availablesecs = (
                   9970:                           mgr => [],
                   9971:                           vgr => [],
                   9972:                           usc => [],
                   9973:                         );
                   9974:     my $ccrole = 'cc';
                   9975:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   9976:         $ccrole = 'co';
                   9977:     }
                   9978:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   9979:                                                      'userroles',['active'],
                   9980:                                                      [$ccrole,'in','cr'],$cdom,1);
                   9981:     my $crsid = $cnum.':'.$cdom;
                   9982:     foreach my $item (keys(%crsroleshash)) {
                   9983:         next unless ($item =~ /^$crsid\:/);
                   9984:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   9985:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   9986:         if ($sec ne '') {
                   9987:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   9988:         }
                   9989:         if (($role eq $ccrole) || ($role eq 'in')) {
                   9990:             foreach my $priv ('mgr','vgr','usc') { 
                   9991:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9992:                     if ($sec eq '') {
                   9993:                         $availablesecs{$priv} = ['all'];
                   9994:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   9995:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9996:                             push(@{$availablesecs{$priv}},$sec);
                   9997:                         }
                   9998:                     }
                   9999:                 }
                   10000:             }
                   10001:         } elsif ($role =~ m{^cr/}) {
                   10002:             foreach my $priv ('mgr','vgr','usc') {
                   10003:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   10004:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   10005:                         if ($sec eq '') {
                   10006:                             $availablesecs{$priv} = ['all'];
                   10007:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   10008:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   10009:                                 push(@{$availablesecs{$priv}},$sec);
                   10010:                             }
                   10011:                         }
                   10012:                     }
                   10013:                 }
                   10014:             }
                   10015:         }
                   10016:     }
                   10017:     return %availablesecs;
                   10018: }
                   10019: 
                   10020: sub scantron_upload_delete {
                   10021:     my ($r,$symb) = @_;
                   10022:     my $filename = $env{'form.uploadedfile'};
                   10023:     if ($filename =~ /^scantron_orig_/) {
                   10024:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   10025:             &Apache::lonnet::allowed('usc',
                   10026:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   10027:             &Apache::lonnet::allowed('usc',
                   10028:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   10029:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   10030:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   10031:             if ($retrieval eq '-1') {
                   10032:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10033:                           &mt('File requested for deletion not found.'));
                   10034:             } else {
                   10035:                 $filename =~ s/^scantron_orig_//;
                   10036:                 if ($filename ne '') {
                   10037:                     my ($is_valid,$numleft);
                   10038:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   10039:                     if (keys(%info)) {
                   10040:                         if (ref($info{$filename}) eq 'HASH') {
                   10041:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   10042:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   10043:                                     $is_valid = 1;
                   10044:                                     delete($info{$filename}{$timestamp}); 
                   10045:                                 }
                   10046:                             }
                   10047:                             $numleft = scalar(keys(%{$info{$filename}}));
                   10048:                         }
                   10049:                     }
                   10050:                     if ($is_valid) {
                   10051:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   10052:                         if ($result eq 'ok') {
                   10053:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   10054:                             if ($numleft) {
                   10055:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   10056:                             } else {
                   10057:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   10058:                             }
                   10059:                         } else {
                   10060:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10061:                                       &mt('Result was [_1]',$result));
                   10062:                         }
                   10063:                     } else {
                   10064:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10065:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   10066:                     }
                   10067:                 } else {
                   10068:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10069:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   10070:                 }
                   10071:             }
                   10072:         } else {
                   10073:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   10074:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   10075:         }
                   10076:     } else {
                   10077:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   10078:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   10079:     }
                   10080:     return;
                   10081: }
                   10082: 
1.202     albertel 10083: sub valid_file {
                   10084:     my ($requested_file)=@_;
                   10085:     foreach my $filename (sort(&scantron_filenames())) {
                   10086: 	if ($requested_file eq $filename) { return 1; }
                   10087:     }
                   10088:     return 0;
                   10089: }
                   10090: 
                   10091: sub scantron_download_scantron_data {
1.767     raeburn  10092:     my ($r,$symb) = @_;
1.608     www      10093:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 10094:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10095:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10096:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 10097:     if (! &valid_file($file)) {
1.492     albertel 10098: 	$r->print('
1.202     albertel 10099: 	<p>
1.686     bisitz   10100: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 10101:         </p>
1.492     albertel 10102: ');
1.202     albertel 10103: 	return;
                   10104:     }
1.770     raeburn  10105:     my (%uploader,$is_owner,%counts,$percent);
                   10106:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   10107:     if (ref($uploader{$file}) eq 'HASH') {
                   10108:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   10109:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   10110:                 $is_owner = 1;
                   10111:                 last;
                   10112:             }
                   10113:         }
                   10114:     }
                   10115:     unless ($is_owner) {
                   10116:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   10117:         if ($counts{'totalanysec'}) {
                   10118:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   10119:             if ($percent_othersec >= 10) {
                   10120:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   10121:                 $r->print('<p class="LC_warning">'.
                   10122:                           &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).
                   10123:                           '</p>');
                   10124:                 return;
                   10125:             }
                   10126:         }
                   10127:     }
1.202     albertel 10128:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   10129:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   10130:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   10131:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   10132:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   10133:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 10134:     $r->print('
1.202     albertel 10135:     <p>
1.723     raeburn  10136: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 10137: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 10138:     </p>
                   10139:     <p>
1.492     albertel 10140: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   10141: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 10142:     </p>
                   10143:     <p>
1.492     albertel 10144: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   10145: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 10146:     </p>
1.492     albertel 10147: ');
1.202     albertel 10148:     return '';
                   10149: }
1.157     albertel 10150: 
1.523     raeburn  10151: sub checkscantron_results {
1.608     www      10152:     my ($r,$symb) = @_;
1.523     raeburn  10153:     if (!$symb) {return '';}
                   10154:     my $cid = $env{'request.course.id'};
1.755     raeburn  10155:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  10156:     my $numletts = scalar(keys(%lettdig));
                   10157:     my $cnum = $env{'course.'.$cid.'.num'};
                   10158:     my $cdom = $env{'course.'.$cid.'.domain'};
                   10159:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10160:     my %record;
                   10161:     my %scantron_config =
1.754     raeburn  10162:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  10163:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  10164:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  10165:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10166:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   10167:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10168:     unless (ref($navmap)) {
                   10169:         $r->print(&navmap_errormsg());
                   10170:         return '';
                   10171:     }
1.523     raeburn  10172:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10173:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10174:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  10175:     if (ref($map)) { 
                   10176:         $randomorder=$map->randomorder();
1.689     raeburn  10177:         $randompick=$map->randompick();
1.788     raeburn  10178:         unless ($randomorder || $randompick) {
                   10179:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   10180:                 if ($res->randomorder()) {
                   10181:                     $randomorder = 1;
                   10182:                 }
                   10183:                 if ($res->randompick()) {
                   10184:                     $randompick = 1;
                   10185:                 }
                   10186:                 last if ($randomorder || $randompick);
                   10187:             }
                   10188:         }
1.677     raeburn  10189:     }
1.557     raeburn  10190:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10191:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10192:     if ($nav_error) {
                   10193:         $r->print(&navmap_errormsg());
                   10194:         return '';
1.678     raeburn  10195:     }
1.673     raeburn  10196:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10197:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  10198:     my ($uname,$udom);
1.523     raeburn  10199:     my (%scandata,%lastname,%bylast);
                   10200:     $r->print('
                   10201: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   10202: 
                   10203:     my @delayqueue;
                   10204:     my %completedstudents;
                   10205: 
1.691     raeburn  10206:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10207:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  10208:     my ($username,$domain,$started);
1.649     raeburn  10209:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10210:     if ($nav_error) {
                   10211:         $r->print(&navmap_errormsg());
                   10212:         return '';
                   10213:     }
1.523     raeburn  10214: 
1.667     www      10215:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  10216:     my $start=&Time::HiRes::time();
                   10217:     my $i=-1;
                   10218: 
                   10219:     while ($i<$scanlines->{'count'}) {
                   10220:         ($username,$domain,$uname)=('','','');
                   10221:         $i++;
                   10222:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   10223:         if ($line=~/^[\s\cz]*$/) { next; }
                   10224:         if ($started) {
1.667     www      10225:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  10226:         }
                   10227:         $started=1;
                   10228:         my $scan_record=
                   10229:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   10230:                                                      $scan_data);
1.693     raeburn  10231:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10232:                                               \%idmap,$i)) {
1.523     raeburn  10233:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10234:                                 'Unable to find a student that matches',1);
                   10235:             next;
                   10236:         }
                   10237:         if (exists $completedstudents{$uname}) {
                   10238:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10239:                                 'Student '.$uname.' has multiple sheets',2);
                   10240:             next;
                   10241:         }
                   10242:         my $pid = $scan_record->{'scantron.ID'};
                   10243:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   10244:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  10245:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   10246:         my $user = $uname.':'.$usec;
1.523     raeburn  10247:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  10248: 
1.678     raeburn  10249:         my $scancode;
1.677     raeburn  10250:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10251:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10252:             $scancode = $scan_record->{'scantron.CODE'};
                   10253:         } else {
                   10254:             $scancode = '';
                   10255:         }
                   10256: 
                   10257:         my @mapresources = @resources;
1.691     raeburn  10258:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   10259:         my %respnumlookup=();
                   10260:         my %startline=();
1.689     raeburn  10261:         if ($randomorder || $randompick) {
1.678     raeburn  10262:             @mapresources =
1.691     raeburn  10263:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10264:                              \%orderedforcode);
                   10265:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   10266:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   10267:                                              \%grader_partids_by_symb,\%orderedforcode,
                   10268:                                              \%respnumlookup,\%startline);
                   10269:             if ($randompick && $total) {
                   10270:                 $lastpos = $total*$scantron_config{'Qlength'};
                   10271:             }
1.677     raeburn  10272:         }
1.691     raeburn  10273:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10274:         chomp($scandata{$pid});
                   10275:         $scandata{$pid} =~ s/\r$//;
                   10276: 
1.523     raeburn  10277:         my $counter = -1;
1.677     raeburn  10278:         foreach my $resource (@mapresources) {
1.557     raeburn  10279:             my $parts;
1.554     raeburn  10280:             my $ressymb = $resource->symb();
1.557     raeburn  10281:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10282:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10283:                 my $currcode;
                   10284:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10285:                     $currcode = $scancode;
                   10286:                 }
1.557     raeburn  10287:                 (my $analysis,$parts) =
1.672     raeburn  10288:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   10289:                                               $username,$domain,undef,
1.741     raeburn  10290:                                               $bubbles_per_row,$currcode);
1.557     raeburn  10291:             } else {
                   10292:                 $parts = $grader_partids_by_symb{$ressymb};
                   10293:             }
1.542     raeburn  10294:             ($counter,my $recording) =
                   10295:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  10296:                                          $scandata{$pid},$parts,
1.691     raeburn  10297:                                          \%scantron_config,\%lettdig,$numletts,
                   10298:                                          $randomorder,$randompick,
                   10299:                                          \%respnumlookup,\%startline);
1.542     raeburn  10300:             $record{$pid} .= $recording;
1.523     raeburn  10301:         }
                   10302:     }
                   10303:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   10304:     $r->print('<br />');
                   10305:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   10306:     $passed = 0;
                   10307:     $failed = 0;
                   10308:     $numstudents = 0;
                   10309:     foreach my $last (sort(keys(%bylast))) {
                   10310:         if (ref($bylast{$last}) eq 'ARRAY') {
                   10311:             foreach my $pid (sort(@{$bylast{$last}})) {
                   10312:                 my $showscandata = $scandata{$pid};
                   10313:                 my $showrecord = $record{$pid};
                   10314:                 $showscandata =~ s/\s/&nbsp;/g;
                   10315:                 $showrecord =~ s/\s/&nbsp;/g;
                   10316:                 if ($scandata{$pid} eq $record{$pid}) {
                   10317:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   10318:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      10319: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  10320: '</tr>'."\n".
                   10321: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10322: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  10323:                     $passed ++;
                   10324:                 } else {
                   10325:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      10326:                     $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  10327: '</tr>'."\n".
                   10328: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10329: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  10330: '</tr>'."\n";
                   10331:                     $failed ++;
                   10332:                 }
                   10333:                 $numstudents ++;
                   10334:             }
                   10335:         }
                   10336:     }
1.648     bisitz   10337:     $r->print(
                   10338:         '<p>'
                   10339:        .&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).',
                   10340:             '<b>',
                   10341:             $numstudents,
                   10342:             '</b>',
                   10343:             $env{'form.scantron_maxbubble'})
                   10344:        .'</p>'
                   10345:     );
1.682     raeburn  10346:     $r->print('<p>'
1.683     raeburn  10347:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  10348:              .'<br />'
                   10349:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10350:              .'</p>'
                   10351:     );
1.523     raeburn  10352:     if ($passed) {
1.572     www      10353:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10354:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10355:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10356:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10357:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10358:                  $okstudents."\n".
                   10359:                  &Apache::loncommon::end_data_table().'<br />');
                   10360:     }
                   10361:     if ($failed) {
1.572     www      10362:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10363:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10364:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10365:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10366:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10367:                  $badstudents."\n".
                   10368:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10369:                  &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  10370:     }
1.614     www      10371:     $r->print('</form><br />');
1.523     raeburn  10372:     return;
                   10373: }
                   10374: 
1.542     raeburn  10375: sub verify_scantron_grading {
1.554     raeburn  10376:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  10377:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10378:         $respnumlookup,$startline) = @_;
1.542     raeburn  10379:     my ($record,%expected,%startpos);
                   10380:     return ($counter,$record) if (!ref($resource));
                   10381:     return ($counter,$record) if (!$resource->is_problem());
                   10382:     my $symb = $resource->symb();
1.554     raeburn  10383:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10384:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10385:         $counter ++;
                   10386:         $expected{$part_id} = 0;
1.691     raeburn  10387:         my $respnum = $counter;
                   10388:         if ($randomorder || $randompick) {
                   10389:             $respnum = $respnumlookup->{$counter};
                   10390:             $startpos{$part_id} = $startline->{$counter} + 1;
                   10391:         } else {
                   10392:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10393:         }
                   10394:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10395:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10396:             foreach my $item (@sub_lines) {
                   10397:                 $expected{$part_id} += $item;
                   10398:             }
                   10399:         } else {
1.691     raeburn  10400:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10401:         }
                   10402:     }
                   10403:     if ($symb) {
                   10404:         my %recorded;
                   10405:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10406:         if ($returnhash{'version'}) {
                   10407:             my %lasthash=();
                   10408:             my $version;
                   10409:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10410:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10411:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10412:                 }
                   10413:             }
                   10414:             foreach my $key (keys(%lasthash)) {
                   10415:                 if ($key =~ /\.scantron$/) {
                   10416:                     my $value = &unescape($lasthash{$key});
                   10417:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10418:                     if ($value eq '') {
                   10419:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10420:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10421:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10422:                             }
                   10423:                         }
                   10424:                     } else {
                   10425:                         my @tocheck;
                   10426:                         my @items = split(//,$value);
                   10427:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10428:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10429:                             if (@items < $expected{$part_id}) {
                   10430:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10431:                                 my @singles = split(//,$fragment);
                   10432:                                 foreach my $pos (@singles) {
                   10433:                                     if ($pos eq ' ') {
                   10434:                                         push(@tocheck,$pos);
                   10435:                                     } else {
                   10436:                                         my $next = shift(@items);
                   10437:                                         push(@tocheck,$next);
                   10438:                                     }
                   10439:                                 }
                   10440:                             } else {
                   10441:                                 @tocheck = @items;
                   10442:                             }
                   10443:                             foreach my $letter (@tocheck) {
                   10444:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10445:                                     if ($letter !~ /^[A-J]$/) {
                   10446:                                         $letter = $scantron_config->{'Qoff'};
                   10447:                                     }
                   10448:                                     $recorded{$part_id} .= $letter;
                   10449:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10450:                                     my $digit;
                   10451:                                     if ($letter !~ /^[A-J]$/) {
                   10452:                                         $digit = $scantron_config->{'Qoff'};
                   10453:                                     } else {
                   10454:                                         $digit = $lettdig->{$letter};
                   10455:                                     }
                   10456:                                     $recorded{$part_id} .= $digit;
                   10457:                                 }
                   10458:                             }
                   10459:                         } else {
                   10460:                             @tocheck = @items;
                   10461:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10462:                                 my $curr_sub = shift(@tocheck);
                   10463:                                 my $digit;
                   10464:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10465:                                     $digit = $lettdig->{$curr_sub}-1;
                   10466:                                 }
                   10467:                                 if ($curr_sub eq 'J') {
                   10468:                                     $digit += scalar($numletts);
                   10469:                                 }
                   10470:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10471:                                     if ($j == $digit) {
                   10472:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10473:                                     } else {
                   10474:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10475:                                     }
                   10476:                                 }
                   10477:                             }
                   10478:                         }
                   10479:                     }
                   10480:                 }
                   10481:             }
                   10482:         }
1.554     raeburn  10483:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10484:             if ($recorded{$part_id} eq '') {
                   10485:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10486:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10487:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10488:                     }
                   10489:                 }
                   10490:             }
                   10491:             $record .= $recorded{$part_id};
                   10492:         }
                   10493:     }
                   10494:     return ($counter,$record);
                   10495: }
                   10496: 
1.75      albertel 10497: #-------- end of section for handling grading scantron forms -------
                   10498: #
                   10499: #-------------------------------------------------------------------
                   10500: 
1.72      ng       10501: #-------------------------- Menu interface -------------------------
                   10502: #
1.614     www      10503: #--- Href with symb and command ---
                   10504: 
                   10505: sub href_symb_cmd {
                   10506:     my ($symb,$cmd)=@_;
1.669     raeburn  10507:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       10508: }
                   10509: 
1.443     banghart 10510: sub grading_menu {
1.608     www      10511:     my ($request,$symb) = @_;
1.443     banghart 10512:     if (!$symb) {return '';}
                   10513: 
                   10514:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      10515:                   'command'=>'individual');
1.538     schulted 10516:     
1.598     www      10517:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10518: 
                   10519:     $fields{'command'}='ungraded';
                   10520:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10521: 
                   10522:     $fields{'command'}='table';
                   10523:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10524: 
                   10525:     $fields{'command'}='all_for_one';
                   10526:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10527: 
1.621     www      10528:     $fields{'command'}='downloadfilesselect';
                   10529:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10530: 
1.443     banghart 10531:     $fields{'command'} = 'csvform';
1.538     schulted 10532:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10533:     
1.443     banghart 10534:     $fields{'command'} = 'processclicker';
1.538     schulted 10535:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10536:     
1.443     banghart 10537:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10538:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      10539: 
                   10540:     $fields{'command'} = 'initialverifyreceipt';
                   10541:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  10542: 
                   10543:     my %permissions;
                   10544:     if ($perm{'mgr'}) {
                   10545:         $permissions{'either'} = 'F';
                   10546:         $permissions{'mgr'} = 'F';
                   10547:     }
                   10548:     if ($perm{'vgr'}) {
                   10549:         $permissions{'either'} = 'F';
                   10550:         $permissions{'vgr'} = 'F';
                   10551:     }
                   10552: 
1.598     www      10553:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10554:             items =>[
1.598     www      10555:                         {	linktext => 'Select individual students to grade',
                   10556:                     		url => $url1a,
1.781     raeburn  10557:                     		permission => $permissions{'either'},
1.636     wenzelju 10558:                     		icon => 'grade_students.png',
1.598     www      10559:                     		linktitle => 'Grade current resource for a selection of students.'
                   10560:                         }, 
1.764     raeburn  10561:                         {       linktext => 'Grade ungraded submissions',
1.598     www      10562:                                 url => $url1b,
1.781     raeburn  10563:                                 permission => $permissions{'either'},
1.636     wenzelju 10564:                                 icon => 'ungrade_sub.png',
1.598     www      10565:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 10566:                         },
1.598     www      10567: 
                   10568:                         {       linktext => 'Grading table',
                   10569:                                 url => $url1c,
1.781     raeburn  10570:                                 permission => $permissions{'either'},
1.636     wenzelju 10571:                                 icon => 'grading_table.png',
1.598     www      10572:                                 linktitle => 'Grade current resource for all students.'
                   10573:                         },
1.615     www      10574:                         {       linktext => 'Grade page/folder for one student',
1.598     www      10575:                                 url => $url1d,
1.781     raeburn  10576:                                 permission => $permissions{'either'},
1.636     wenzelju 10577:                                 icon => 'grade_PageFolder.png',
1.598     www      10578:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      10579:                         },
                   10580:                         {       linktext => 'Download submissions',
                   10581:                                 url => $url1e,
1.781     raeburn  10582:                                 permission => $permissions{'either'},
1.636     wenzelju 10583:                                 icon => 'download_sub.png',
1.621     www      10584:                                 linktitle => 'Download all students submissions.'
1.598     www      10585:                         }]},
                   10586:                          { categorytitle=>'Automated Grading',
                   10587:                items =>[
                   10588: 
1.538     schulted 10589:                 	    {	linktext => 'Upload Scores',
                   10590:                     		url => $url2,
1.780     raeburn  10591:                     		permission => $permissions{'mgr'},
1.538     schulted 10592:                     		icon => 'uploadscores.png',
                   10593:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10594:                 	    },
                   10595:                 	    {	linktext => 'Process Clicker',
                   10596:                     		url => $url3,
1.780     raeburn  10597:                     		permission => $permissions{'mgr'},
1.538     schulted 10598:                     		icon => 'addClickerInfoFile.png',
                   10599:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10600:                 	    },
1.587     raeburn  10601:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10602:                     		url => $url4,
1.780     raeburn  10603:                     		permission => $permissions{'mgr'},
1.636     wenzelju 10604:                     		icon => 'bubblesheet.png',
1.648     bisitz   10605:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      10606:                 	    },
1.616     www      10607:                             {   linktext => 'Verify Receipt Number',
1.602     www      10608:                                 url => $url5,
1.780     raeburn  10609:                                 permission => $permissions{'either'},
1.636     wenzelju 10610:                                 icon => 'receipt_number.png',
1.602     www      10611:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10612:                             }
                   10613: 
1.538     schulted 10614:                     ]
                   10615:             });
                   10616: 
1.443     banghart 10617:     # Create the menu
                   10618:     my $Str;
1.445     banghart 10619:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10620:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      10621:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 10622: 
1.602     www      10623:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10624:     return $Str;    
                   10625: }
                   10626: 
1.598     www      10627: sub ungraded {
                   10628:     my ($request)=@_;
                   10629:     &submit_options($request);
                   10630: }
                   10631: 
1.599     www      10632: sub submit_options_sequence {
1.608     www      10633:     my ($request,$symb) = @_;
1.599     www      10634:     if (!$symb) {return '';}
1.600     www      10635:     &commonJSfunctions($request);
                   10636:     my $result;
1.599     www      10637: 
1.600     www      10638:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10639:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      10640:     $result.=&selectfield(0).
1.601     www      10641:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      10642:             <div>
                   10643:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10644:             </div>
                   10645:         </div>
                   10646:   </form>';
                   10647:     return $result;
                   10648: }
                   10649: 
                   10650: sub submit_options_table {
1.608     www      10651:     my ($request,$symb) = @_;
1.600     www      10652:     if (!$symb) {return '';}
1.599     www      10653:     &commonJSfunctions($request);
1.746     raeburn  10654:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      10655:     my $result;
                   10656: 
                   10657:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10658:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      10659: 
1.745     raeburn  10660:     $result.=&selectfield(1,$is_tool).
1.601     www      10661:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      10662:             <div>
                   10663:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10664:             </div>
                   10665:         </div>
                   10666:   </form>';
                   10667:     return $result;
                   10668: }
1.443     banghart 10669: 
1.621     www      10670: sub submit_options_download {
                   10671:     my ($request,$symb) = @_;
                   10672:     if (!$symb) {return '';}
                   10673: 
1.773     raeburn  10674:     my $res_error;
                   10675:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10676:         &response_type($symb,\$res_error);
                   10677:     if ($res_error) {
                   10678:         $request->print(&mt('An error occurred retrieving response types'));
                   10679:         return;
                   10680:     }
                   10681:     unless ($numessay) {
                   10682:         $request->print(&mt('No essayresponse items found'));
                   10683:         return;
                   10684:     }
                   10685:     my $table;
                   10686:     if (ref($partlist) eq 'ARRAY') {
                   10687:         if (scalar(@$partlist) > 1 ) {
                   10688:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   10689:         }
                   10690:     }
                   10691: 
1.746     raeburn  10692:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      10693:     &commonJSfunctions($request);
                   10694: 
                   10695:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  10696:                $table."\n".
                   10697:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      10698:     $result.='
                   10699: <h2>
1.750     raeburn  10700:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  10701: </h2>'.&selectfield(1,$is_tool).'
1.621     www      10702:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   10703:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10704:             </div>
                   10705:           </div>
1.600     www      10706: 
                   10707: 
1.621     www      10708:   </form>';
                   10709:     return $result;
                   10710: }
                   10711: 
1.443     banghart 10712: #--- Displays the submissions first page -------
                   10713: sub submit_options {
1.608     www      10714:     my ($request,$symb) = @_;
1.72      ng       10715:     if (!$symb) {return '';}
                   10716: 
1.746     raeburn  10717:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       10718:     &commonJSfunctions($request);
1.473     albertel 10719:     my $result;
1.533     bisitz   10720: 
1.72      ng       10721:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10722: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  10723:     $result.=&selectfield(1,$is_tool).'
1.601     www      10724:                 <input type="hidden" name="command" value="submission" /> 
                   10725: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10726:             </div>
                   10727:           </div>
                   10728:   </form>';
                   10729:     return $result;
                   10730: }
1.533     bisitz   10731: 
1.601     www      10732: sub selectfield {
1.745     raeburn  10733:    my ($full,$is_tool)=@_;
                   10734:    my %options;
                   10735:    if ($is_tool) {
                   10736:        %options =
                   10737:            (&transtatus_options,
                   10738:             'select_form_order' => ['yes','incorrect','all']);
                   10739:    } else {
                   10740:        %options = 
                   10741:            (&substatus_options,
                   10742:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10743:    }
1.782     raeburn  10744: 
                   10745:   #
                   10746:   # PrepareClasslist() needs to be called to avoid getting a sections list
                   10747:   # for a different course from the @Sections global in lonstatistics.pm, 
                   10748:   # populated by an earlier request.
                   10749:   #
                   10750:    &Apache::lonstatistics::PrepareClasslist();
                   10751: 
1.601     www      10752:    my $result='<div class="LC_columnSection">
1.537     harmsja  10753:   
1.533     bisitz   10754:     <fieldset>
                   10755:       <legend>
                   10756:        '.&mt('Sections').'
                   10757:       </legend>
1.601     www      10758:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10759:     </fieldset>
1.537     harmsja  10760:   
1.533     bisitz   10761:     <fieldset>
                   10762:       <legend>
                   10763:         '.&mt('Groups').'
                   10764:       </legend>
                   10765:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10766:     </fieldset>
1.537     harmsja  10767:   
1.533     bisitz   10768:     <fieldset>
                   10769:       <legend>
                   10770:         '.&mt('Access Status').'
                   10771:       </legend>
1.601     www      10772:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10773:     </fieldset>';
                   10774:     if ($full) {
1.745     raeburn  10775:         my $heading = &mt('Submission Status');
                   10776:         if ($is_tool) {
                   10777:             $heading = &mt('Transaction Status');
                   10778:         }
                   10779:         $result.='
1.533     bisitz   10780:     <fieldset>
                   10781:       <legend>
1.745     raeburn  10782:         '.$heading.'
1.601     www      10783:       </legend>'.
1.635     raeburn  10784:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      10785:    '</fieldset>';
                   10786:     }
                   10787:     $result.='</div><br />';
1.44      ng       10788:     return $result;
1.2       albertel 10789: }
                   10790: 
1.738     raeburn  10791: sub substatus_options {
                   10792:     return &Apache::lonlocal::texthash(
                   10793:                                       'yes'       => 'with submissions',
                   10794:                                       'queued'    => 'in grading queue',
                   10795:                                       'graded'    => 'with ungraded submissions',
                   10796:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10797:                                       'all'       => 'with any status',
                   10798:                                       );
1.738     raeburn  10799: }
                   10800: 
1.745     raeburn  10801: sub transtatus_options {
                   10802:     return &Apache::lonlocal::texthash(
                   10803:                                        'yes'       => 'with score transactions',
                   10804:                                        'incorrect' => 'with less than full credit',
                   10805:                                        'all'       => 'with any status',
                   10806:                                       );
                   10807: }
                   10808: 
1.285     albertel 10809: sub reset_perm {
                   10810:     undef(%perm);
                   10811: }
                   10812: 
                   10813: sub init_perm {
                   10814:     &reset_perm();
1.770     raeburn  10815:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 10816: 
                   10817: 	my $scope = $env{'request.course.id'};
                   10818: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10819: 
                   10820: 	    $scope .= '/'.$env{'request.course.sec'};
                   10821: 	    if ( $perm{$test_perm}=
                   10822: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10823: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10824: 	    } else {
                   10825: 		delete($perm{$test_perm});
                   10826: 	    }
1.285     albertel 10827: 	}
                   10828:     }
                   10829: }
                   10830: 
1.674     raeburn  10831: sub init_old_essays {
                   10832:     my ($symb,$apath,$adom,$aname) = @_;
                   10833:     if ($symb ne '') {
                   10834:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10835:         if (keys(%essays) > 0) {
                   10836:             $old_essays{$symb} = \%essays;
                   10837:         }
                   10838:     }
                   10839:     return;
                   10840: }
                   10841: 
                   10842: sub reset_old_essays {
                   10843:     undef(%old_essays);
                   10844: }
                   10845: 
1.400     www      10846: sub gather_clicker_ids {
1.408     albertel 10847:     my %clicker_ids;
1.400     www      10848: 
                   10849:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10850: 
                   10851:     # Set up a couple variables.
1.407     albertel 10852:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10853:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10854:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10855: 
1.407     albertel 10856:     foreach my $student (keys(%$classlist)) {
1.438     www      10857:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10858:         my $username = $classlist->{$student}->[$username_idx];
                   10859:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10860:         my $clickers =
1.408     albertel 10861: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10862:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10863:             $id=~s/^[\#0]+//;
1.421     www      10864:             $id=~s/[\-\:]//g;
1.407     albertel 10865:             if (exists($clicker_ids{$id})) {
1.408     albertel 10866: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10867:             } else {
1.408     albertel 10868: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10869:             }
                   10870:         }
                   10871:     }
1.407     albertel 10872:     return %clicker_ids;
1.400     www      10873: }
                   10874: 
1.402     www      10875: sub gather_adv_clicker_ids {
1.408     albertel 10876:     my %clicker_ids;
1.402     www      10877:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10878:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10879:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10880:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10881:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10882:             my ($puname,$pudom)=split(/\:/,$person);
                   10883:             my $clickers =
1.408     albertel 10884: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10885:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10886: 		$id=~s/^[\#0]+//;
1.421     www      10887:                 $id=~s/[\-\:]//g;
1.408     albertel 10888: 		if (exists($clicker_ids{$id})) {
                   10889: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10890: 		} else {
                   10891: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10892: 		}
1.405     www      10893:             }
1.402     www      10894:         }
                   10895:     }
1.407     albertel 10896:     return %clicker_ids;
1.402     www      10897: }
                   10898: 
1.413     www      10899: sub clicker_grading_parameters {
                   10900:     return ('gradingmechanism' => 'scalar',
                   10901:             'upfiletype' => 'scalar',
                   10902:             'specificid' => 'scalar',
                   10903:             'pcorrect' => 'scalar',
                   10904:             'pincorrect' => 'scalar');
                   10905: }
                   10906: 
1.400     www      10907: sub process_clicker {
1.608     www      10908:     my ($r,$symb)=@_;
1.400     www      10909:     if (!$symb) {return '';}
                   10910:     my $result=&checkforfile_js();
1.632     www      10911:     $result.=&Apache::loncommon::start_data_table().
                   10912:              &Apache::loncommon::start_data_table_header_row().
                   10913:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10914:              &Apache::loncommon::end_data_table_header_row().
                   10915:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10916: # Attempt to restore parameters from last session, set defaults if not present
                   10917:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10918:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10919:                                                  \%Saveable_Parameters);
                   10920:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10921:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10922:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10923:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10924: 
                   10925:     my %checked;
1.521     www      10926:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10927:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10928:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10929:        }
                   10930:     }
                   10931: 
1.632     www      10932:     my $upload=&mt("Evaluate File");
1.400     www      10933:     my $type=&mt("Type");
1.402     www      10934:     my $attendance=&mt("Award points just for participation");
                   10935:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10936:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10937:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10938:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10939:     my $pcorrect=&mt("Percentage points for correct solution");
                   10940:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10941:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10942: 						   {'iclicker' => 'i>clicker',
1.666     www      10943:                                                     'interwrite' => 'interwrite PRS',
                   10944:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10945:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10946:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10947: function sanitycheck() {
                   10948: // Accept only integer percentages
                   10949:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10950:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10951: // Find out grading choice
                   10952:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10953:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10954:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10955:       }
                   10956:    }
                   10957: // By default, new choice equals user selection
                   10958:    newgradingchoice=gradingchoice;
                   10959: // Not good to give more points for false answers than correct ones
                   10960:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10961:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10962:    }
                   10963: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10964:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10965:       document.forms.gradesupload.pcorrect.value=100;
                   10966:       document.forms.gradesupload.pincorrect.value=100;
                   10967:    }
                   10968: // If the values are different, cannot be attendance only
                   10969:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10970:        (gradingchoice=='attendance')) {
                   10971:        newgradingchoice='personnel';
                   10972:    }
                   10973: // Change grading choice to new one
                   10974:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10975:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10976:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10977:       } else {
                   10978:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10979:       }
                   10980:    }
                   10981: // Remember the old state
                   10982:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10983: }
1.597     wenzelju 10984: ENDUPFORM
                   10985:     $result.= <<ENDUPFORM;
1.400     www      10986: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10987: <input type="hidden" name="symb" value="$symb" />
                   10988: <input type="hidden" name="command" value="processclickerfile" />
                   10989: <input type="file" name="upfile" size="50" />
                   10990: <br /><label>$type: $selectform</label>
1.632     www      10991: ENDUPFORM
                   10992:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10993:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10994:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10995: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10996: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10997: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10998: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10999: <br />&nbsp;&nbsp;&nbsp;
                   11000: <input type="text" name="givenanswer" size="50" />
1.413     www      11001: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      11002: ENDGRADINGFORM
1.766     raeburn  11003:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      11004:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   11005:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   11006: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   11007: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  11008: </form>
1.632     www      11009: ENDPERCFORM
                   11010:     $result.='</td>'.
                   11011:              &Apache::loncommon::end_data_table_row().
                   11012:              &Apache::loncommon::end_data_table();
1.400     www      11013:     return $result;
                   11014: }
                   11015: 
                   11016: sub process_clicker_file {
1.766     raeburn  11017:     my ($r,$symb) = @_;
1.400     www      11018:     if (!$symb) {return '';}
1.413     www      11019: 
                   11020:     my %Saveable_Parameters=&clicker_grading_parameters();
                   11021:     &Apache::loncommon::store_course_settings('grades_clicker',
                   11022:                                               \%Saveable_Parameters);
1.598     www      11023:     my $result='';
1.404     www      11024:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 11025: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      11026: 	return $result;
1.404     www      11027:     }
1.522     www      11028:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      11029:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      11030:         return $result;
1.521     www      11031:     }
1.522     www      11032:     my $foundgiven=0;
1.521     www      11033:     if ($env{'form.gradingmechanism'} eq 'given') {
                   11034:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   11035:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      11036:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      11037:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      11038:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   11039:         $foundgiven=$#answers+1;
1.521     www      11040:     }
1.407     albertel 11041:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 11042:     my %correct_ids;
1.404     www      11043:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 11044: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      11045:     }
                   11046:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      11047: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   11048: 	   $correct_id=~tr/a-z/A-Z/;
                   11049: 	   $correct_id=~s/\s//gs;
                   11050: 	   $correct_id=~s/^[\#0]+//;
1.421     www      11051:            $correct_id=~s/[\-\:]//g;
1.414     www      11052:            if ($correct_id) {
                   11053: 	      $correct_ids{$correct_id}='specified';
                   11054:            }
                   11055:         }
1.400     www      11056:     }
1.404     www      11057:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 11058: 	$result.=&mt('Score based on attendance only');
1.521     www      11059:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      11060:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      11061:     } else {
1.408     albertel 11062: 	my $number=0;
1.411     www      11063: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 11064: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      11065: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 11066: 	    if ($correct_ids{$id} eq 'specified') {
                   11067: 		$result.=&mt('specified');
                   11068: 	    } else {
                   11069: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   11070: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   11071: 	    }
                   11072: 	    $number++;
                   11073: 	}
1.411     www      11074:         $result.="</p>\n";
1.710     bisitz   11075:         if ($number==0) {
                   11076:             $result .=
                   11077:                  &Apache::lonhtmlcommon::confirm_success(
                   11078:                      &mt('No IDs found to determine correct answer'),1);
                   11079:             return $result;
                   11080:         }
1.404     www      11081:     }
1.405     www      11082:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   11083:         $result .=
                   11084:             &Apache::lonhtmlcommon::confirm_success(
                   11085:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   11086:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      11087:         return $result;
1.405     www      11088:     }
1.760     raeburn  11089:     my $mimetype;
                   11090:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   11091:         my $mm = new File::MMagic;
                   11092:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   11093:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   11094:             $result.= '<p>'.
                   11095:                 &Apache::lonhtmlcommon::confirm_success(
                   11096:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   11097:             return $result;
                   11098:         }
                   11099:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   11100:         $result .= '<p>'.
                   11101:             &Apache::lonhtmlcommon::confirm_success(
                   11102:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   11103:         return $result;
                   11104:     }
1.410     www      11105: 
                   11106: # Were able to get all the info needed, now analyze the file
                   11107: 
1.411     www      11108:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 11109:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      11110:     $result.=&Apache::loncommon::start_data_table().
                   11111:              &Apache::loncommon::start_data_table_header_row().
                   11112:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   11113:              &Apache::loncommon::end_data_table_header_row().
                   11114:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   11115: <td>
1.410     www      11116: <form method="post" action="/adm/grades" name="clickeranalysis">
                   11117: <input type="hidden" name="symb" value="$symb" />
                   11118: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      11119: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   11120: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   11121: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      11122: ENDHEADER
1.522     www      11123:     if ($env{'form.gradingmechanism'} eq 'given') {
                   11124:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   11125:     } 
1.408     albertel 11126:     my %responses;
                   11127:     my @questiontitles;
1.405     www      11128:     my $errormsg='';
                   11129:     my $number=0;
                   11130:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  11131:         if ($mimetype eq 'text/plain') {
                   11132:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   11133:         } elsif ($mimetype eq 'text/html') {
                   11134:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   11135:         }
                   11136:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      11137:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  11138:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      11139:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   11140:     }
1.411     www      11141:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   11142:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   11143:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   11144:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   11145:              '<br />';
1.522     www      11146:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   11147:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      11148:        return $result;
1.522     www      11149:     } 
1.414     www      11150: # Remember Question Titles
                   11151: # FIXME: Possibly need delimiter other than ":"
                   11152:     for (my $i=0;$i<$number;$i++) {
                   11153:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   11154:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   11155:     }
1.411     www      11156:     my $correct_count=0;
                   11157:     my $student_count=0;
                   11158:     my $unknown_count=0;
1.414     www      11159: # Match answers with usernames
                   11160: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 11161:     foreach my $id (keys(%responses)) {
1.410     www      11162:        if ($correct_ids{$id}) {
1.414     www      11163:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      11164:           $correct_count++;
1.410     www      11165:        } elsif ($clicker_ids{$id}) {
1.437     www      11166:           if ($clicker_ids{$id}=~/\,/) {
                   11167: # More than one user with the same clicker!
1.632     www      11168:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11169:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11170:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      11171:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11172:                            "<select name='multi".$id."'>";
                   11173:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   11174:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   11175:              }
                   11176:              $result.='</select>';
                   11177:              $unknown_count++;
                   11178:           } else {
                   11179: # Good: found one and only one user with the right clicker
                   11180:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   11181:              $student_count++;
                   11182:           }
1.410     www      11183:        } else {
1.632     www      11184:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11185:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11186:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      11187:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11188:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   11189:                    "\n".&mt("Domain").": ".
                   11190:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  11191:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      11192:           $unknown_count++;
1.410     www      11193:        }
1.405     www      11194:     }
1.412     www      11195:     $result.='<hr />'.
                   11196:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      11197:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      11198:        if ($correct_count==0) {
1.696     bisitz   11199:           $errormsg.="Found no correct answers for grading!";
1.412     www      11200:        } elsif ($correct_count>1) {
1.414     www      11201:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      11202:        }
                   11203:     }
1.428     www      11204:     if ($number<1) {
                   11205:        $errormsg.="Found no questions.";
                   11206:     }
1.412     www      11207:     if ($errormsg) {
                   11208:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   11209:     } else {
                   11210:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   11211:     }
1.632     www      11212:     $result.='</form></td>'.
                   11213:              &Apache::loncommon::end_data_table_row().
                   11214:              &Apache::loncommon::end_data_table();
1.614     www      11215:     return $result;
1.400     www      11216: }
                   11217: 
1.405     www      11218: sub iclicker_eval {
1.406     www      11219:     my ($questiontitles,$responses)=@_;
1.405     www      11220:     my $number=0;
                   11221:     my $errormsg='';
                   11222:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      11223:         my %components=&Apache::loncommon::record_sep($line);
                   11224:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 11225: 	if ($entries[0] eq 'Question') {
                   11226: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   11227: 		$$questiontitles[$number]=$entries[$i];
                   11228: 		$number++;
                   11229: 	    }
                   11230: 	}
                   11231: 	if ($entries[0]=~/^\#/) {
                   11232: 	    my $id=$entries[0];
                   11233: 	    my @idresponses;
                   11234: 	    $id=~s/^[\#0]+//;
                   11235: 	    for (my $i=0;$i<$number;$i++) {
                   11236: 		my $idx=3+$i*6;
1.644     www      11237:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 11238: 		push(@idresponses,$entries[$idx]);
                   11239: 	    }
                   11240: 	    $$responses{$id}=join(',',@idresponses);
                   11241: 	}
1.405     www      11242:     }
                   11243:     return ($errormsg,$number);
                   11244: }
                   11245: 
1.760     raeburn  11246: sub iclickerxml_eval {
                   11247:     my ($questiontitles,$responses)=@_;
                   11248:     my $number=0;
                   11249:     my $errormsg='';
                   11250:     my @state;
                   11251:     my %respbyid;
                   11252:     my $p = HTML::Parser->new
                   11253:     (
                   11254:         xml_mode => 1,
                   11255:         start_h =>
                   11256:             [sub {
                   11257:                  my ($tagname,$attr) = @_;
                   11258:                  push(@state,$tagname);
                   11259:                  if ("@state" eq "ssn p") {
                   11260:                      my $title = $attr->{qn};
                   11261:                      $title =~ s/(^\s+|\s+$)//g;
                   11262:                      $questiontitles->[$number]=$title;
                   11263:                  } elsif ("@state" eq "ssn p v") {
                   11264:                      my $id = $attr->{id};
                   11265:                      my $entry = $attr->{ans};
                   11266:                      $id=~s/^[\#0]+//;
                   11267:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   11268:                      $respbyid{$id}[$number] = $entry;
                   11269:                  }
                   11270:             }, "tagname, attr"],
                   11271:          end_h =>
                   11272:                [sub {
                   11273:                    my ($tagname) = @_;
                   11274:                    if ("@state" eq "ssn p") {
                   11275:                        $number++;
                   11276:                    }
                   11277:                    pop(@state);
                   11278:                 }, "tagname"],
                   11279:     );
                   11280: 
                   11281:     $p->parse($env{'form.upfile'});
                   11282:     $p->eof;
                   11283:     foreach my $id (keys(%respbyid)) {
                   11284:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   11285:     }
                   11286:     return ($errormsg,$number);
                   11287: }
                   11288: 
1.419     www      11289: sub interwrite_eval {
                   11290:     my ($questiontitles,$responses)=@_;
                   11291:     my $number=0;
                   11292:     my $errormsg='';
1.420     www      11293:     my $skipline=1;
                   11294:     my $questionnumber=0;
                   11295:     my %idresponses=();
1.419     www      11296:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11297:         my %components=&Apache::loncommon::record_sep($line);
                   11298:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      11299:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   11300:         if ($entries[1] eq 'Response') { $skipline=1; }
                   11301:         next if $skipline;
                   11302:         if ($entries[0]!=$questionnumber) {
                   11303:            $questionnumber=$entries[0];
                   11304:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   11305:            $number++;
1.419     www      11306:         }
1.420     www      11307:         my $id=$entries[4];
                   11308:         $id=~s/^[\#0]+//;
1.421     www      11309:         $id=~s/^v\d*\://i;
                   11310:         $id=~s/[\-\:]//g;
1.420     www      11311:         $idresponses{$id}[$number]=$entries[6];
                   11312:     }
1.524     raeburn  11313:     foreach my $id (keys(%idresponses)) {
1.420     www      11314:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   11315:        $$responses{$id}=~s/^\s*\,//;
1.419     www      11316:     }
                   11317:     return ($errormsg,$number);
                   11318: }
                   11319: 
1.666     www      11320: sub turning_eval {
                   11321:     my ($questiontitles,$responses)=@_;
                   11322:     my $number=0;
                   11323:     my $errormsg='';
                   11324:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11325:         my %components=&Apache::loncommon::record_sep($line);
                   11326:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   11327:         if ($#entries>$number) { $number=$#entries; }
                   11328:         my $id=$entries[0];
                   11329:         my @idresponses;
                   11330:         $id=~s/^[\#0]+//;
                   11331:         unless ($id) { next; }
                   11332:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   11333:             $entries[$idx]=~s/\,/\;/g;
                   11334:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   11335:             push(@idresponses,$entries[$idx]);
                   11336:         }
                   11337:         $$responses{$id}=join(',',@idresponses);
                   11338:     }
                   11339:     for (my $i=1; $i<=$number; $i++) {
                   11340:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   11341:     }
                   11342:     return ($errormsg,$number);
                   11343: }
                   11344: 
                   11345: 
1.414     www      11346: sub assign_clicker_grades {
1.766     raeburn  11347:     my ($r,$symb) = @_;
1.414     www      11348:     if (!$symb) {return '';}
1.416     www      11349: # See which part we are saving to
1.582     raeburn  11350:     my $res_error;
                   11351:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   11352:     if ($res_error) {
                   11353:         return &navmap_errormsg();
                   11354:     }
1.416     www      11355: # FIXME: This should probably look for the first handgradeable part
                   11356:     my $part=$$partlist[0];
                   11357: # Start screen output
1.766     raeburn  11358:     my $result = &Apache::loncommon::start_data_table().
                   11359:                  &Apache::loncommon::start_data_table_header_row().
                   11360:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   11361:                  &Apache::loncommon::end_data_table_header_row().
                   11362:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11363: # Get correct result
                   11364: # FIXME: Possibly need delimiter other than ":"
                   11365:     my @correct=();
1.415     www      11366:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11367:     my $number=$env{'form.number'};
                   11368:     if ($gradingmechanism ne 'attendance') {
1.414     www      11369:        foreach my $key (keys(%env)) {
                   11370:           if ($key=~/^form\.correct\:/) {
                   11371:              my @input=split(/\,/,$env{$key});
                   11372:              for (my $i=0;$i<=$#input;$i++) {
                   11373:                  if (($correct[$i]) && ($input[$i]) &&
                   11374:                      ($correct[$i] ne $input[$i])) {
                   11375:                     $result.='<br /><span class="LC_warning">'.
                   11376:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11377:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      11378:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11379:                     $correct[$i]=$input[$i];
                   11380:                  }
                   11381:              }
                   11382:           }
                   11383:        }
1.415     www      11384:        for (my $i=0;$i<$number;$i++) {
1.644     www      11385:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11386:              $result.='<br /><span class="LC_error">'.
                   11387:                       &mt('No correct result given for question "[_1]"!',
                   11388:                           $env{'form.question:'.$i}).'</span>';
                   11389:           }
                   11390:        }
1.644     www      11391:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11392:     }
                   11393: # Start grading
1.415     www      11394:     my $pcorrect=$env{'form.pcorrect'};
                   11395:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11396:     my $storecount=0;
1.632     www      11397:     my %users=();
1.415     www      11398:     foreach my $key (keys(%env)) {
1.420     www      11399:        my $user='';
1.415     www      11400:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11401:           $user=$1;
                   11402:        }
                   11403:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11404:           my $id=$1;
                   11405:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11406:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11407:           } elsif ($env{'form.multi'.$id}) {
                   11408:              $user=$env{'form.multi'.$id};
1.420     www      11409:           }
                   11410:        }
1.632     www      11411:        if ($user) {
                   11412:           if ($users{$user}) {
                   11413:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   11414:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      11415:                       '</span><br />';
                   11416:           }
                   11417:           $users{$user}=1; 
1.415     www      11418:           my @answer=split(/\,/,$env{$key});
                   11419:           my $sum=0;
1.522     www      11420:           my $realnumber=$number;
1.415     www      11421:           for (my $i=0;$i<$number;$i++) {
1.576     www      11422:              if  ($correct[$i] eq '-') {
                   11423:                 $realnumber--;
1.766     raeburn  11424:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11425:                 if ($gradingmechanism eq 'attendance') {
                   11426:                    $sum+=$pcorrect;
1.576     www      11427:                 } elsif ($correct[$i] eq '*') {
1.522     www      11428:                    $sum+=$pcorrect;
1.415     www      11429:                 } else {
1.644     www      11430: # We actually grade if correct or not
                   11431:                    my $increment=$pincorrect;
                   11432: # Special case: numerical answer "0"
                   11433:                    if ($correct[$i] eq '0') {
                   11434:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11435:                          $increment=$pcorrect;
                   11436:                       }
                   11437: # General numerical answer, both evaluate to something non-zero
                   11438:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11439:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11440:                          $increment=$pcorrect;
                   11441:                       }
                   11442: # Must be just alphanumeric
                   11443:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11444:                       $increment=$pcorrect;
1.415     www      11445:                    }
1.644     www      11446:                    $sum+=$increment;
1.415     www      11447:                 }
                   11448:              }
                   11449:           }
1.522     www      11450:           my $ave=$sum/(100*$realnumber);
1.416     www      11451: # Store
                   11452:           my ($username,$domain)=split(/\:/,$user);
                   11453:           my %grades=();
                   11454:           $grades{"resource.$part.solved"}='correct_by_override';
                   11455:           $grades{"resource.$part.awarded"}=$ave;
                   11456:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11457:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11458:                                                  $env{'request.course.id'},
                   11459:                                                  $domain,$username);
                   11460:           if ($returncode ne 'ok') {
                   11461:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11462:           } else {
                   11463:              $storecount++;
                   11464:           }
1.415     www      11465:        }
                   11466:     }
                   11467: # We are done
1.549     hauer    11468:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      11469:              '</td>'.
                   11470:              &Apache::loncommon::end_data_table_row().
                   11471:              &Apache::loncommon::end_data_table();
1.614     www      11472:     return $result;
1.414     www      11473: }
                   11474: 
1.582     raeburn  11475: sub navmap_errormsg {
                   11476:     return '<div class="LC_error">'.
                   11477:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11478:            &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  11479:            '</div>';
                   11480: }
1.607     droeschl 11481: 
1.609     www      11482: sub startpage {
1.777     raeburn  11483:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  11484:     my %args;
                   11485:     if ($onload) {
                   11486:          my %loaditems = (
                   11487:                         'onload' => $onload,
                   11488:                       );
                   11489:          $args{'add_entries'} = \%loaditems;
                   11490:     }
1.671     raeburn  11491:     if ($nomenu) {
1.754     raeburn  11492:         $args{'only_body'} = 1; 
1.777     raeburn  11493:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  11494:     } else {
1.785     raeburn  11495:         if ($env{'request.course.id'}) { 
                   11496:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   11497:         }
1.754     raeburn  11498:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  11499:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  11500:         if ($env{'request.course.id'}) {
                   11501:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   11502:         }
1.671     raeburn  11503:     }
1.613     www      11504:     unless ($nodisplayflag) {
1.773     raeburn  11505:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      11506:     }
1.607     droeschl 11507: }
1.582     raeburn  11508: 
1.622     www      11509: sub select_problem {
                   11510:     my ($r)=@_;
1.632     www      11511:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  11512:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      11513:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11514:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11515: }
                   11516: 
1.1       albertel 11517: sub handler {
1.41      ng       11518:     my $request=$_[0];
1.434     albertel 11519:     &reset_caches();
1.646     raeburn  11520:     if ($request->header_only) {
                   11521:         &Apache::loncommon::content_type($request,'text/html');
                   11522:         $request->send_http_header;
                   11523:         return OK;
                   11524:     }
                   11525:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   11526: 
1.664     raeburn  11527: # see what command we need to execute
                   11528: 
                   11529:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11530:     my $command=$commands[0];
                   11531: 
1.646     raeburn  11532:     &init_perm();
                   11533:     if (!$env{'request.course.id'}) {
1.664     raeburn  11534:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11535:                 ($command =~ /^scantronupload/)) {
                   11536:             # Not in a course.
                   11537:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11538:             return HTTP_NOT_ACCEPTABLE;
                   11539:         }
1.646     raeburn  11540:     } elsif (!%perm) {
                   11541:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  11542:         return OK;
1.41      ng       11543:     }
1.646     raeburn  11544:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       11545:     $request->send_http_header;
1.646     raeburn  11546: 
1.160     albertel 11547:     if ($#commands > 0) {
                   11548: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11549:     }
1.608     www      11550: 
                   11551: # see what the symb is
                   11552: 
                   11553:     my $symb=$env{'form.symb'};
                   11554:     unless ($symb) {
                   11555:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11556:        $symb=&Apache::lonnet::symbread($url);
                   11557:     }
1.646     raeburn  11558:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      11559: 
1.513     foxr     11560:     $ssi_error = 0;
1.637     www      11561:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      11562: #
1.637     www      11563: # Not called from a resource, but inside a course
1.601     www      11564: #    
1.622     www      11565:         &startpage($request,undef,[],1,1);
                   11566:         &select_problem($request);
1.41      ng       11567:     } else {
1.104     albertel 11568: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  11569:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  11570:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11571:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11572:                     &choose_task_version_form($symb,$env{'form.student'},
                   11573:                                               $env{'form.userdom'});
                   11574:             }
1.773     raeburn  11575:             my $divforres;
                   11576:             if ($env{'form.student'} eq '') {
                   11577:                 $js .= &part_selector_js();
                   11578:                 $onload = "toggleParts('gradesub');";
                   11579:             } else {
                   11580:                 $divforres = 1;
                   11581:             }
1.778     raeburn  11582:             my $head_extra = $js;
                   11583:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11584:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11585:                 if ($csslinks) {
                   11586:                     $head_extra .= "\n$csslinks";
                   11587:                 }
                   11588:             }
1.777     raeburn  11589:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   11590:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  11591:             if ($versionform) {
1.775     raeburn  11592:                 if ($divforres) {
                   11593:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   11594:                 }
1.671     raeburn  11595:                 $request->print($versionform);
                   11596:             }
1.773     raeburn  11597: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  11598:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11599:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11600:                 &choose_task_version_form($symb,$env{'form.student'},
                   11601:                                           $env{'form.userdom'},
                   11602:                                           $env{'form.inhibitmenu'});
1.778     raeburn  11603:             my $head_extra = $js;
                   11604:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11605:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11606:                 if ($csslinks) {
                   11607:                     $head_extra .= "\n$csslinks";
                   11608:                 }
                   11609:             }
1.777     raeburn  11610:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   11611:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  11612:             if ($versionform) {
                   11613:                 $request->print($versionform);
                   11614:             }
                   11615:             $request->print('<br clear="all" />');
                   11616:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 11617: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      11618:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11619:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      11620: 	    &pickStudentPage($request,$symb);
1.103     albertel 11621: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  11622:             my $csslinks;
                   11623:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11624:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  11625:             }
1.615     www      11626:             &startpage($request,$symb,
                   11627:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11628:                                        {href=>'',text=>'Select student'},
1.777     raeburn  11629:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      11630: 	    &displayPage($request,$symb);
1.104     albertel 11631: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      11632:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11633:                                        {href=>'',text=>'Select student'},
                   11634:                                        {href=>'',text=>'Grade student'},
                   11635:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      11636: 	    &updateGradeByPage($request,$symb);
1.104     albertel 11637: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  11638:             my $csslinks;
                   11639:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11640:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11641:             }
1.619     www      11642:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  11643:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      11644: 	    &processGroup($request,$symb);
1.104     albertel 11645: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      11646:             &startpage($request,$symb);
                   11647: 	    $request->print(&grading_menu($request,$symb));
1.598     www      11648: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      11649:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      11650: 	    $request->print(&submit_options($request,$symb));
1.598     www      11651:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  11652:             my $js = &part_selector_js();
                   11653:             my $onload = "toggleParts('gradesub');";
                   11654:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11655:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      11656:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      11657:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      11658:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      11659:             $request->print(&submit_options_table($request,$symb));
1.598     www      11660:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      11661:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      11662:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 11663: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      11664:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      11665: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 11666: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      11667:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11668:                                        {href=>'',text=>'Store grades'}]);
1.608     www      11669: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 11670: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      11671:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11672:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11673:                                                                              text=>"Modify grades"},
                   11674:                                        {href=>'', text=>"Store grades"}]);
1.608     www      11675: 	    $request->print(&editgrades($request,$symb));
1.602     www      11676:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      11677:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      11678:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 11679: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      11680:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11681:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      11682: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      11683:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      11684:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      11685:             $request->print(&process_clicker($request,$symb));
1.400     www      11686:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      11687:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11688:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      11689:             $request->print(&process_clicker_file($request,$symb));
1.414     www      11690:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      11691:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11692:                                        {href=>'', text=>'Process clicker file'},
                   11693:                                        {href=>'', text=>'Store grades'}]);
1.608     www      11694:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 11695: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      11696:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11697: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 11698: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      11699:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11700: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 11701: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      11702:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11703: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 11704: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 11705: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      11706:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11707: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       11708: 	    } else {
1.257     albertel 11709: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11710: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       11711: 		} else {
1.257     albertel 11712: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       11713: 		}
1.627     www      11714:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11715: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       11716: 	    }
1.246     albertel 11717: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      11718:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11719: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 11720: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  11721:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11722:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      11723: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 11724:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      11725:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11726:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 11727: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      11728:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11729: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 11730: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      11731:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11732: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 11733:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  11734:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  11735:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11736:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      11737:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 11738:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  11739:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      11740:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11741:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  11742:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      11743:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11744:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  11745:         } elsif ($command eq 'scantronupload_delete' &&
                   11746:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   11747:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11748:             &scantron_upload_delete($request,$symb);
1.523     raeburn  11749:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      11750:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      11751:             $request->print(&checkscantron_results($request,$symb));
                   11752:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  11753:             my $js = &part_selector_js();
                   11754:             my $onload = "toggleParts('gradingMenu');";
                   11755:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11756:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      11757:             $request->print(&submit_options_download($request,$symb));
                   11758:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11759:             &startpage($request,$symb,
                   11760:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  11761:     {href=>'', text=>'Download submitted files'}],
                   11762:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  11763:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      11764:             &submit_download_link($request,$symb);
1.106     albertel 11765: 	} elsif ($command) {
1.620     www      11766:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   11767: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 11768: 	}
1.2       albertel 11769:     }
1.513     foxr     11770:     if ($ssi_error) {
                   11771: 	&ssi_print_error($request);
                   11772:     }
1.671     raeburn  11773:     if ($env{'form.inhibitmenu'}) {
                   11774:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  11775:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  11776:         &Apache::lonquickgrades::endGradeScreen($request);
                   11777:     }
1.434     albertel 11778:     &reset_caches();
1.646     raeburn  11779:     return OK;
1.44      ng       11780: }
                   11781: 
1.1       albertel 11782: 1;
                   11783: 
1.13      albertel 11784: __END__;
1.531     jms      11785: 
                   11786: 
                   11787: =head1 NAME
                   11788: 
                   11789: Apache::grades
                   11790: 
                   11791: =head1 SYNOPSIS
                   11792: 
                   11793: Handles the viewing of grades.
                   11794: 
                   11795: This is part of the LearningOnline Network with CAPA project
                   11796: described at http://www.lon-capa.org.
                   11797: 
                   11798: =head1 OVERVIEW
                   11799: 
                   11800: Do an ssi with retries:
1.715     bisitz   11801: While I'd love to factor out this with the version in lonprintout,
1.531     jms      11802: 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
                   11803: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11804: 
                   11805: At least the logic that drives this has been pulled out into loncommon.
                   11806: 
                   11807: 
                   11808: 
                   11809: ssi_with_retries - Does the server side include of a resource.
                   11810:                      if the ssi call returns an error we'll retry it up to
                   11811:                      the number of times requested by the caller.
1.715     bisitz   11812:                      If we still have a problem, no text is appended to the
1.531     jms      11813:                      output and we set some global variables.
                   11814:                      to indicate to the caller an SSI error occurred.  
                   11815:                      All of this is supposed to deal with the issues described
1.715     bisitz   11816:                      in LON-CAPA BZ 5631 see:
1.531     jms      11817:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11818:                      by informing the user that this happened.
                   11819: 
                   11820: Parameters:
                   11821:   resource   - The resource to include.  This is passed directly, without
                   11822:                interpretation to lonnet::ssi.
                   11823:   form       - The form hash parameters that guide the interpretation of the resource
                   11824:                
                   11825:   retries    - Number of retries allowed before giving up completely.
                   11826: Returns:
                   11827:   On success, returns the rendered resource identified by the resource parameter.
                   11828: Side Effects:
                   11829:   The following global variables can be set:
                   11830:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11831:                               It is up to the caller to initialize this to false
                   11832:                               if desired.
                   11833:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11834:                               of the resource that could not be rendered by the ssi
                   11835:                               call.
                   11836:    ssi_error_message   - The error string fetched from the ssi response
                   11837:                               in the event of an error.
                   11838: 
                   11839: 
                   11840: =head1 HANDLER SUBROUTINE
                   11841: 
                   11842: ssi_with_retries()
                   11843: 
                   11844: =head1 SUBROUTINES
                   11845: 
                   11846: =over
                   11847: 
1.671     raeburn  11848: =head1 Routines to display previous version of a Task for a specific student
                   11849: 
                   11850: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   11851: can receive another opportunity. Access to tasks is slot-based. If a slot
                   11852: requires a proctor to check-in the student, a new version of the Task will
                   11853: be created when the student is checked in to the new opportunity.
                   11854: 
                   11855: If a particular student has tried two or more versions of a particular task,
                   11856: the submission screen provides a user with vgr privileges (e.g., a Course
                   11857: Coordinator) the ability to display a previous version worked on by the
                   11858: student.  By default, the current version is displayed. If a previous version
                   11859: has been selected for display, submission data are only shown that pertain
                   11860: to that particular version, and the interface to submit grades is not shown.
                   11861: 
                   11862: =over 4
                   11863: 
                   11864: =item show_previous_task_version()
                   11865: 
                   11866: Displays a specified version of a student's Task, as the student sees it.
                   11867: 
                   11868: Inputs: 2
                   11869:         request - request object
                   11870:         symb    - unique symb for current instance of resource
                   11871: 
                   11872: Output: None.
                   11873: 
                   11874: Side Effects: calls &show_problem() to print version of Task, with
                   11875:               version contained in form item: $env{'form.previousversion'}
                   11876: 
                   11877: =item choose_task_version_form()
                   11878: 
                   11879: Displays a web form used to select which version of a student's view of a
                   11880: Task should be displayed.  Either launches a pop-up window, or replaces
                   11881: content in existing pop-up, or replaces page in main window.
                   11882: 
                   11883: Inputs: 4
                   11884:         symb    - unique symb for current instance of resource
                   11885:         uname   - username of student
                   11886:         udom    - domain of student
                   11887:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11888:                   breadcrumbs etc., are displayed
                   11889: 
                   11890: Output: 4
                   11891:         current   - student's current version
                   11892:         displayed - student's version being displayed
                   11893:         result    - scalar containing HTML for web form used to switch to
                   11894:                     a different version (or a link to close window, if pop-up).
                   11895:         js        - javascript for processing selection in versions web form
                   11896: 
                   11897: Side Effects: None.
                   11898: 
                   11899: =item previous_display_javascript()
                   11900: 
                   11901: Inputs: 2
                   11902:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11903:                   breadcrumbs etc., are displayed.
                   11904:         current - student's current version number.
                   11905: 
                   11906: Output: 1
                   11907:         js      - javascript for processing selection in versions web form.
                   11908: 
                   11909: Side Effects: None.
                   11910: 
                   11911: =back
                   11912: 
                   11913: =head1 Routines to process bubblesheet data.
                   11914: 
                   11915: =over 4
                   11916: 
1.531     jms      11917: =item scantron_get_correction() : 
                   11918: 
                   11919:    Builds the interface screen to interact with the operator to fix a
                   11920:    specific error condition in a specific scanline
                   11921: 
                   11922:  Arguments:
                   11923:     $r           - Apache request object
                   11924:     $i           - number of the current scanline
                   11925:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  11926:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11927:     $line        - full contents of the current scanline
                   11928:     $error       - error condition, valid values are
                   11929:                    'incorrectCODE', 'duplicateCODE',
                   11930:                    'doublebubble', 'missingbubble',
                   11931:                    'duplicateID', 'incorrectID'
                   11932:     $arg         - extra information needed
                   11933:        For errors:
                   11934:          - duplicateID   - paper number that this studentID was seen before on
                   11935:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11936:                            seen on before
                   11937:          - incorrectCODE - current incorrect CODE 
                   11938:          - doublebubble  - array ref of the bubble lines that have double
                   11939:                            bubble errors
                   11940:          - missingbubble - array ref of the bubble lines that have missing
                   11941:                            bubble errors
                   11942: 
1.788     raeburn  11943:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   11944:    $randompick  - True if exam folder (or a sub-folder) has randompick set
1.691     raeburn  11945:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11946:                      for current line to question number used for same question
                   11947:                      in "Master Seqence" (as seen by Course Coordinator).
                   11948:    $startline   - Reference to hash where key is question number (0 is first)
                   11949:                   and value is number of first bubble line for current student
                   11950:                   or code-based randompick and/or randomorder.
                   11951: 
                   11952: 
                   11953: 
1.531     jms      11954: =item  scantron_get_maxbubble() : 
                   11955: 
1.582     raeburn  11956:    Arguments:
                   11957:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11958:                       failure to retrieve a navmap object.
                   11959:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11960:        calling routine should trap the error condition and display the warning
                   11961:        found in &navmap_errormsg().
                   11962: 
1.649     raeburn  11963:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11964: 
1.531     jms      11965:    Returns the maximum number of bubble lines that are expected to
                   11966:    occur. Does this by walking the selected sequence rendering the
                   11967:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11968:    for what the current value of the problem counter is.
                   11969: 
                   11970:    Caches the results to $env{'form.scantron_maxbubble'},
                   11971:    $env{'form.scantron.bubble_lines.n'}, 
                   11972:    $env{'form.scantron.first_bubble_line.n'} and
                   11973:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11974:    which are the total number of bubble lines, the number of bubble
1.531     jms      11975:    lines for response n and number of the first bubble line for response n,
                   11976:    and a comma separated list of numbers of bubble lines for sub-questions
                   11977:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11978: 
                   11979: 
                   11980: =item  scantron_validate_missingbubbles() : 
                   11981: 
                   11982:    Validates all scanlines in the selected file to not have any
                   11983:     answers that don't have bubbles that have not been verified
                   11984:     to be bubble free.
                   11985: 
                   11986: =item  scantron_process_students() : 
                   11987: 
1.659     raeburn  11988:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11989: 
                   11990:    The parsed scanline hash is added to %env 
                   11991: 
                   11992:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11993:    foreach resource , with the form data of
                   11994: 
                   11995: 	'submitted'     =>'scantron' 
                   11996: 	'grade_target'  =>'grade',
                   11997: 	'grade_username'=> username of student
                   11998: 	'grade_domain'  => domain of student
                   11999: 	'grade_courseid'=> of course
                   12000: 	'grade_symb'    => symb of resource to grade
                   12001: 
                   12002:     This triggers a grading pass. The problem grading code takes care
                   12003:     of converting the bubbled letter information (now in %env) into a
                   12004:     valid submission.
                   12005: 
                   12006: =item  scantron_upload_scantron_data() :
                   12007: 
1.659     raeburn  12008:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      12009: 
                   12010: =item  scantron_upload_scantron_data_save() : 
                   12011: 
                   12012:    Adds a provided bubble information data file to the course if user
1.770     raeburn  12013:    has the correct privileges to do so.
                   12014: 
                   12015: = item scantron_upload_delete() :
                   12016: 
                   12017:    Deletes a previously uploaded bubble information data file, if user
                   12018:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      12019: 
                   12020: =item  valid_file() :
                   12021: 
                   12022:    Validates that the requested bubble data file exists in the course.
                   12023: 
                   12024: =item  scantron_download_scantron_data() : 
                   12025: 
                   12026:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  12027:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      12028:    course.
                   12029: 
                   12030: =item  scantron_validate_ID() : 
                   12031: 
                   12032:    Validates all scanlines in the selected file to not have any
1.556     weissno  12033:    invalid or underspecified student/employee IDs
1.531     jms      12034: 
1.582     raeburn  12035: =item navmap_errormsg() :
                   12036: 
                   12037:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  12038:    Should be called whenever the request to instantiate a navmap object fails.
                   12039: 
                   12040: =back
1.582     raeburn  12041: 
1.531     jms      12042: =back
                   12043: 
                   12044: =cut

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