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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.779   ! raeburn     4: # $Id: grades.pm,v 1.778 2020/11/09 00:44:30 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.561     bisitz   1169:                   .$submission_options
1.773     raeburn  1170:                   .&Apache::lonhtmlcommon::row_closure()
                   1171:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   1172:                   .'<span class="LC_nobreak">'
                   1173:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   1174:                   .&mt('No').('&nbsp;'x2).'</label>'
                   1175:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   1176:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1177:                   .&Apache::lonhtmlcommon::row_closure();
                   1178: 
                   1179:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1180:                   .'<select name="increment">'
                   1181:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1182:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1183:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1184:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773     raeburn  1185:                   .'</select>';
1.485     albertel 1186:     $gradeTable .= 
1.432     banghart 1187:         &build_section_inputs().
1.45      ng       1188: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1189: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1190: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      1191:     if (exists($env{'form.Status'})) {
1.561     bisitz   1192: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1193:     } else {
1.773     raeburn  1194:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1195:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1196:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773     raeburn  1197:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1198:     }
1.773     raeburn  1199:     if ($numessay) {
                   1200:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1201:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1202:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  1203:     }
1.773     raeburn  1204:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
                   1205:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  1206:     my $regrademsg;
                   1207:     if ($is_tool) {
                   1208:         $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.");
                   1209:     } else {
                   1210:         $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.");
                   1211:     }
1.561     bisitz   1212:     $gradeTable .= '<p>'
1.745     raeburn  1213:                   .$regrademsg."\n"
1.561     bisitz   1214:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1215:                   .'</p>';
1.249     albertel 1216: 
                   1217: # checkall buttons
                   1218:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1219:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1220:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1221:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1222:     $gradeTable.=&check_buttons();
1.450     banghart 1223:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1224:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1225: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1226:     my $loop = 0;
                   1227:     while ($loop < 2) {
1.485     albertel 1228: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1229: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1230: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1231: 	    foreach my $part (sort(@$partlist)) {
                   1232: 		my $display_part=
                   1233: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1234: 		$gradeTable.=
                   1235: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1236: 	    }
1.301     albertel 1237: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1238: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1239: 	}
                   1240: 	$loop++;
1.126     ng       1241: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1242:     }
1.474     albertel 1243:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1244: 
1.45      ng       1245:     my $ctr = 0;
1.294     albertel 1246:     foreach my $student (sort 
                   1247: 			 {
                   1248: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1249: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1250: 			     }
                   1251: 			     return $a cmp $b;
                   1252: 			 }
                   1253: 			 (keys(%$fullname))) {
1.41      ng       1254: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1255: 
1.110     ng       1256: 	my %status = ();
1.301     albertel 1257: 
                   1258: 	if ($submitonly eq 'queued') {
                   1259: 	    my %queue_status = 
                   1260: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1261: 							$udom,$uname);
                   1262: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1263: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1264: 	}
                   1265: 
1.618     www      1266: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1267: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1268: 	    my $submitted = 0;
1.164     albertel 1269: 	    my $graded = 0;
1.248     albertel 1270: 	    my $incorrect = 0;
1.110     ng       1271: 	    foreach (keys(%status)) {
1.145     albertel 1272: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1273: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1274: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1275: 		
1.110     ng       1276: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1277: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1278: 		    $submitted = 0;
1.150     albertel 1279: 		    my ($part)=split(/\./,$partid);
1.110     ng       1280: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1281: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1282: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1283: 		}
1.41      ng       1284: 	    }
1.248     albertel 1285: 	    
1.156     albertel 1286: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1287: 				     $submitonly eq 'incorrect' ||
                   1288: 				     $submitonly eq 'graded'));
1.248     albertel 1289: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1290: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1291: 	}
1.34      ng       1292: 
1.45      ng       1293: 	$ctr++;
1.249     albertel 1294: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1295:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1296: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1297: 	    if ($ctr%2 ==1) {
                   1298: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1299: 	    }
1.126     ng       1300: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1301:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1302:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1303: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1304: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1305: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1306: 
1.618     www      1307: 	    if ($submitonly ne 'all') {
1.524     raeburn  1308: 		foreach (sort(keys(%status))) {
1.485     albertel 1309: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1310: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1311: 		}
1.41      ng       1312: 	    }
1.126     ng       1313: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1314: 	    if ($ctr%2 ==0) {
                   1315: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1316: 	    }
1.41      ng       1317: 	}
                   1318:     }
1.110     ng       1319:     if ($ctr%2 ==1) {
1.126     ng       1320: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1321: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1322: 		foreach (@$partlist) {
                   1323: 		    $gradeTable.='<td>&nbsp;</td>';
                   1324: 		}
1.301     albertel 1325: 	    } elsif ($submitonly eq 'queued') {
                   1326: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1327: 	    }
1.474     albertel 1328: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1329:     }
                   1330: 
1.474     albertel 1331:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1332:         '<input type="button" '.
                   1333:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1334:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1335:     if ($ctr == 0) {
1.96      albertel 1336: 	my $num_students=(scalar(keys(%$fullname)));
                   1337: 	if ($num_students eq 0) {
1.485     albertel 1338: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1339: 	} else {
1.171     albertel 1340: 	    my $submissions='submissions';
                   1341: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1342: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1343: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1344: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1345: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1346: 		    $num_students).
                   1347: 		'</span><br />';
1.96      albertel 1348: 	}
1.46      ng       1349:     } elsif ($ctr == 1) {
1.474     albertel 1350: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1351:     }
                   1352:     $request->print($gradeTable);
1.44      ng       1353:     return '';
1.10      ng       1354: }
                   1355: 
1.44      ng       1356: #---- Called from the listStudents routine
1.249     albertel 1357: 
                   1358: sub check_script {
1.766     raeburn  1359:     my ($form,$type) = @_;
                   1360:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1361:     function checkall() {
                   1362:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1363:             ele = document.forms.'.$form.'.elements[i];
                   1364:             if (ele.name == "'.$type.'") {
                   1365:             document.forms.'.$form.'.elements[i].checked=true;
                   1366:                                        }
                   1367:         }
                   1368:     }
                   1369: 
                   1370:     function checksec() {
                   1371:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1372:             ele = document.forms.'.$form.'.elements[i];
                   1373:            string = document.forms.'.$form.'.chksec.value;
                   1374:            if
                   1375:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1376:               document.forms.'.$form.'.elements[i].checked=true;
                   1377:             }
                   1378:         }
                   1379:     }
                   1380: 
                   1381: 
                   1382:     function uncheckall() {
                   1383:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1384:             ele = document.forms.'.$form.'.elements[i];
                   1385:             if (ele.name == "'.$type.'") {
                   1386:             document.forms.'.$form.'.elements[i].checked=false;
                   1387:                                        }
                   1388:         }
                   1389:     }
                   1390: 
1.597     wenzelju 1391: '."\n");
1.249     albertel 1392:     return $chkallscript;
                   1393: }
                   1394: 
                   1395: sub check_buttons {
1.485     albertel 1396:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1397:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1398:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1399:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1400:     return $buttons;
                   1401: }
                   1402: 
1.44      ng       1403: #     Displays the submissions for one student or a group of students
1.34      ng       1404: sub processGroup {
1.766     raeburn  1405:     my ($request,$symb) = @_;
1.41      ng       1406:     my $ctr        = 0;
1.155     albertel 1407:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1408:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1409: 
1.396     banghart 1410:     foreach my $student (@stuchecked) {
                   1411: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1412: 	$env{'form.student'}        = $uname;
                   1413: 	$env{'form.userdom'}        = $udom;
                   1414: 	$env{'form.fullname'}       = $fullname;
1.619     www      1415: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1416: 	$ctr++;
                   1417:     }
                   1418:     return '';
1.35      ng       1419: }
1.34      ng       1420: 
1.44      ng       1421: #------------------------------------------------------------------------------------
                   1422: #
                   1423: #-------------------------- Next few routines handles grading by student, essentially
                   1424: #                           handles essay response type problem/part
                   1425: #
                   1426: #--- Javascript to handle the submission page functionality ---
                   1427: sub sub_page_js {
                   1428:     my $request = shift;
1.736     damieng  1429:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1430:     &js_escape(\$alertmsg);
1.597     wenzelju 1431:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1432:     function updateRadio(formname,id,weight) {
1.125     ng       1433: 	var gradeBox = formname["GD_BOX"+id];
                   1434: 	var radioButton = formname["RADVAL"+id];
                   1435: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1436: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1437: 	gradeBox.value = pts;
                   1438: 	var resetbox = false;
                   1439: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1440: 	    alert("$alertmsg"+pts);
1.71      ng       1441: 	    for (var i=0; i<radioButton.length; i++) {
                   1442: 		if (radioButton[i].checked) {
                   1443: 		    gradeBox.value = i;
                   1444: 		    resetbox = true;
                   1445: 		}
                   1446: 	    }
                   1447: 	    if (!resetbox) {
                   1448: 		formtextbox.value = "";
                   1449: 	    }
                   1450: 	    return;
1.44      ng       1451: 	}
1.71      ng       1452: 
                   1453: 	if (pts > weight) {
                   1454: 	    var resp = confirm("You entered a value ("+pts+
                   1455: 			       ") greater than the weight for the part. Accept?");
                   1456: 	    if (resp == false) {
1.125     ng       1457: 		gradeBox.value = oldpts;
1.71      ng       1458: 		return;
                   1459: 	    }
1.44      ng       1460: 	}
1.13      albertel 1461: 
1.71      ng       1462: 	for (var i=0; i<radioButton.length; i++) {
                   1463: 	    radioButton[i].checked=false;
                   1464: 	    if (pts == i && pts != "") {
                   1465: 		radioButton[i].checked=true;
                   1466: 	    }
                   1467: 	}
                   1468: 	updateSelect(formname,id);
1.125     ng       1469: 	formname["stores"+id].value = "0";
1.41      ng       1470:     }
1.5       albertel 1471: 
1.72      ng       1472:     function writeBox(formname,id,pts) {
1.125     ng       1473: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1474: 	if (checkSolved(formname,id) == 'update') {
                   1475: 	    gradeBox.value = pts;
                   1476: 	} else {
1.125     ng       1477: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1478: 	    gradeBox.value = oldpts;
1.125     ng       1479: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1480: 	    for (var i=0; i<radioButton.length; i++) {
                   1481: 		radioButton[i].checked=false;
1.72      ng       1482: 		if (i == oldpts) {
1.71      ng       1483: 		    radioButton[i].checked=true;
                   1484: 		}
                   1485: 	    }
1.41      ng       1486: 	}
1.125     ng       1487: 	formname["stores"+id].value = "0";
1.71      ng       1488: 	updateSelect(formname,id);
                   1489: 	return;
1.41      ng       1490:     }
1.44      ng       1491: 
1.71      ng       1492:     function clearRadBox(formname,id) {
                   1493: 	if (checkSolved(formname,id) == 'noupdate') {
                   1494: 	    updateSelect(formname,id);
                   1495: 	    return;
                   1496: 	}
1.125     ng       1497: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1498: 	for (var i=0; i<gradeSelect.length; i++) {
                   1499: 	    if (gradeSelect[i].selected) {
                   1500: 		var selectx=i;
                   1501: 	    }
                   1502: 	}
1.125     ng       1503: 	var stores = formname["stores"+id];
1.71      ng       1504: 	if (selectx == stores.value) { return };
1.125     ng       1505: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1506: 	gradeBox.value = "";
1.125     ng       1507: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1508: 	for (var i=0; i<radioButton.length; i++) {
                   1509: 	    radioButton[i].checked=false;
                   1510: 	}
                   1511: 	stores.value = selectx;
                   1512:     }
1.5       albertel 1513: 
1.71      ng       1514:     function checkSolved(formname,id) {
1.125     ng       1515: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1516: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1517: 	    if (!reply) {return "noupdate";}
1.120     ng       1518: 	    formname.overRideScore.value = 'yes';
1.41      ng       1519: 	}
1.71      ng       1520: 	return "update";
1.13      albertel 1521:     }
1.71      ng       1522: 
                   1523:     function updateSelect(formname,id) {
1.125     ng       1524: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1525: 	return;
1.41      ng       1526:     }
1.33      ng       1527: 
1.121     ng       1528: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1529:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1530: 	formname.gradeOpt.value = val;
1.71      ng       1531: 	if (val == "Save & Next") {
                   1532: 	    for (i=0;i<=total;i++) {
                   1533: 		for (j=0;j<parttot;j++) {
1.125     ng       1534: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1535: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1536: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1537: 			if (points == "") {
1.125     ng       1538: 			    var name = formname["name"+i].value;
1.129     ng       1539: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1540: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1541: 					       ", part "+partid+". Continue?");
1.71      ng       1542: 			    if (resp == false) {
1.125     ng       1543: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1544: 				return false;
                   1545: 			    }
                   1546: 			}
                   1547: 		    }
                   1548: 		}
                   1549: 	    }
                   1550: 	}
1.120     ng       1551: 	formname.submit();
                   1552:     }
                   1553: 
1.71      ng       1554: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1555:     function checkSubmitPage(formname,total) {
                   1556: 	noscore = new Array(100);
                   1557: 	var ptr = 0;
                   1558: 	for (i=1;i<total;i++) {
1.125     ng       1559: 	    var partid = formname["q_"+i].value;
1.127     ng       1560: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1561: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1562: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1563: 		if (points == "" && status != "correct_by_student") {
                   1564: 		    noscore[ptr] = i;
                   1565: 		    ptr++;
                   1566: 		}
                   1567: 	    }
                   1568: 	}
                   1569: 	if (ptr != 0) {
                   1570: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1571: 	    var prolist = "";
                   1572: 	    if (ptr == 1) {
                   1573: 		prolist = noscore[0];
                   1574: 	    } else {
                   1575: 		var i = 0;
                   1576: 		while (i < ptr-1) {
                   1577: 		    prolist += noscore[i]+", ";
                   1578: 		    i++;
                   1579: 		}
                   1580: 		prolist += "and "+noscore[i];
                   1581: 	    }
                   1582: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1583: 	    if (resp == false) {
                   1584: 		return false;
                   1585: 	    }
                   1586: 	}
1.45      ng       1587: 
1.71      ng       1588: 	formname.submit();
                   1589:     }
                   1590: SUBJAVASCRIPT
                   1591: }
1.45      ng       1592: 
1.773     raeburn  1593: #--- javascript for grading message center
                   1594: sub sub_grademessage_js {
1.71      ng       1595:     my $request = shift;
1.80      ng       1596:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1597:     &commonJSfunctions($request);
1.350     albertel 1598: 
1.629     www      1599:     my $inner_js_msg_central= (<<INNERJS);
                   1600: <script type="text/javascript">
1.350     albertel 1601:     function checkInput() {
                   1602:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1603:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1604:       var usrctr = document.msgcenter.usrctr.value;
                   1605:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1606:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1607: 
                   1608:       var msgchk = "";
                   1609:       if (document.msgcenter.subchk.checked) {
                   1610:          msgchk = "msgsub,";
                   1611:       }
                   1612:       var includemsg = 0;
                   1613:       for (var i=1; i<=nmsg; i++) {
                   1614:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1615:           var frmmsg = document.msgcenter["msg"+i];
                   1616:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1617:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1618:           showflg.value = "1";
                   1619:           var chkbox = document.msgcenter["msgn"+i];
                   1620:           if (chkbox.checked) {
                   1621:              msgchk += "savemsg"+i+",";
                   1622:              includemsg = 1;
                   1623:           }
                   1624:       }
                   1625:       if (document.msgcenter.newmsgchk.checked) {
                   1626:          msgchk += "newmsg"+usrctr;
                   1627:          includemsg = 1;
                   1628:       }
                   1629:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1630:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1631:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1632:       includemsg.value = msgchk;
                   1633: 
                   1634:       self.close()
                   1635: 
                   1636:     }
1.629     www      1637: </script>
1.350     albertel 1638: INNERJS
                   1639: 
1.773     raeburn  1640:     my $start_page_msg_central =
1.351     albertel 1641:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1642: 				       {'js_ready'  => 1,
                   1643: 					'only_body' => 1,
                   1644: 					'bgcolor'   =>'#FFFFFF',});
1.773     raeburn  1645:     my $end_page_msg_central =
1.350     albertel 1646: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1647: 
1.219     www      1648:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1649:     $docopen=~s/^document\.//;
1.773     raeburn  1650: 
1.736     damieng  1651:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1652:                 comp => 'Compose Message for: ',
                   1653:                 incl => 'Include',
1.656     raeburn  1654:                 type => 'Type',
1.652     raeburn  1655:                 subj => 'Subject',
                   1656:                 mesa => 'Message',
                   1657:                 new  => 'New',
                   1658:                 save => 'Save',
                   1659:                 canc => 'Cancel',
                   1660:              );
1.736     damieng  1661:     &html_escape(\%html_js_lt);
                   1662:     &js_escape(\%html_js_lt);
1.597     wenzelju 1663:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1664: 
1.44      ng       1665: //===================== Script to view submitted by ==================
                   1666:   function viewSubmitter(submitter) {
                   1667:     document.SCORE.refresh.value = "on";
                   1668:     document.SCORE.NCT.value = "1";
                   1669:     document.SCORE.unamedom0.value = submitter;
                   1670:     document.SCORE.submit();
                   1671:     return;
                   1672:   }
                   1673: 
                   1674: //====================== Script for composing message ==============
1.80      ng       1675:    // preload images
                   1676:    img1 = new Image();
                   1677:    img1.src = "$iconpath/mailbkgrd.gif";
                   1678:    img2 = new Image();
                   1679:    img2.src = "$iconpath/mailto.gif";
                   1680: 
1.44      ng       1681:   function msgCenter(msgform,usrctr,fullname) {
                   1682:     var Nmsg  = msgform.savemsgN.value;
                   1683:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1684:     var subject = msgform.msgsub.value;
1.127     ng       1685:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1686:     re = /msgsub/;
                   1687:     var shwsel = "";
                   1688:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1689:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1690:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1691:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1692: 	var testmsg = "savemsg"+i+",";
                   1693: 	re = new RegExp(testmsg,"g");
1.44      ng       1694: 	shwsel = "";
                   1695: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1696: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1697: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1698: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1699: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1700:     }
1.125     ng       1701:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1702:     shwsel = "";
                   1703:     re = /newmsg/;
                   1704:     if (re.test(msgchk)) { shwsel = "checked" }
                   1705:     newMsg(newmsg,shwsel);
                   1706:     msgTail(); 
                   1707:     return;
                   1708:   }
                   1709: 
1.123     ng       1710:   function checkEntities(strx) {
                   1711:     if (strx.length == 0) return strx;
                   1712:     var orgStr = ["&", "<", ">", '"']; 
                   1713:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1714:     var counter = 0;
                   1715:     while (counter < 4) {
                   1716: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1717: 	counter++;
                   1718:     }
                   1719:     return strx;
                   1720:   }
                   1721: 
                   1722:   function strReplace(strx, orgStr, newStr) {
                   1723:     return strx.split(orgStr).join(newStr);
                   1724:   }
                   1725: 
1.44      ng       1726:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1727:     var height = 70*Nmsg+250;
1.44      ng       1728:     if (height > 600) {
                   1729: 	height = 600;
                   1730:     }
1.118     ng       1731:     var xpos = (screen.width-600)/2;
                   1732:     xpos = (xpos < 0) ? '0' : xpos;
                   1733:     var ypos = (screen.height-height)/2-30;
                   1734:     ypos = (ypos < 0) ? '0' : ypos;
                   1735: 
1.668     www      1736:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1737:     pWin.focus();
                   1738:     pDoc = pWin.document;
1.219     www      1739:     pDoc.$docopen;
1.351     albertel 1740:     pDoc.write('$start_page_msg_central');
1.76      ng       1741: 
                   1742:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1743:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1744:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1745: 
1.676     golterma 1746:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1747:     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       1748: }
                   1749:     function displaySubject(msg,shwsel) {
1.76      ng       1750:     pDoc = pWin.document;
1.676     golterma 1751:     pDoc.write("<tr>");
                   1752:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1753:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1754:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1755: }
                   1756: 
1.72      ng       1757:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1758:     pDoc = pWin.document;
1.676     golterma 1759:     pDoc.write("<tr>");
                   1760:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1761:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1762:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1763: }
                   1764: 
                   1765:   function newMsg(newmsg,shwsel) {
1.76      ng       1766:     pDoc = pWin.document;
1.676     golterma 1767:     pDoc.write("<tr>");
                   1768:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1769:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1770:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1771: }
                   1772: 
                   1773:   function msgTail() {
1.76      ng       1774:     pDoc = pWin.document;
1.676     golterma 1775:     //pDoc.write("<\\/table>");
1.465     albertel 1776:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1777:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1778:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1779:     pDoc.write("<\\/form>");
1.351     albertel 1780:     pDoc.write('$end_page_msg_central');
1.128     ng       1781:     pDoc.close();
1.44      ng       1782: }
                   1783: 
1.773     raeburn  1784: SUBJAVASCRIPT
                   1785: }
                   1786: 
                   1787: #--- javascript for essay type problem --
                   1788: sub sub_page_kw_js {
                   1789:     my $request = shift;
                   1790: 
                   1791:     unless ($env{'form.compmsg'}) {
                   1792:         &commonJSfunctions($request);
                   1793:     }
                   1794: 
                   1795:     my $inner_js_highlight_central= (<<INNERJS);
                   1796: <script type="text/javascript">
                   1797:     function updateChoice(flag) {
                   1798:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1799:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1800:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1801:       opener.document.SCORE.refresh.value = "on";
                   1802:       if (opener.document.SCORE.keywords.value!=""){
                   1803:          opener.document.SCORE.submit();
                   1804:       }
                   1805:       self.close()
                   1806:     }
                   1807: </script>
                   1808: INNERJS
                   1809: 
                   1810:     my $start_page_highlight_central =
                   1811:         &Apache::loncommon::start_page('Highlight Central',
                   1812:                                        $inner_js_highlight_central,
                   1813:                                        {'js_ready'  => 1,
                   1814:                                         'only_body' => 1,
                   1815:                                         'bgcolor'   =>'#FFFFFF',});
                   1816:     my $end_page_highlight_central =
                   1817:         &Apache::loncommon::end_page({'js_ready' => 1});
                   1818: 
                   1819:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   1820:     $docopen=~s/^document\.//;
                   1821: 
                   1822:     my %js_lt = &Apache::lonlocal::texthash(
                   1823:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1824:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1825:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1826:                 col1 => 'red',
                   1827:                 col2 => 'green',
                   1828:                 col3 => 'blue',
                   1829:                 siz1 => 'normal',
                   1830:                 siz2 => '+1',
                   1831:                 siz3 => '+2',
                   1832:                 sty1 => 'normal',
                   1833:                 sty2 => 'italic',
                   1834:                 sty3 => 'bold',
                   1835:              );
                   1836:     my %html_js_lt = &Apache::lonlocal::texthash(
                   1837:                 save => 'Save',
                   1838:                 canc => 'Cancel',
                   1839:                 kehi => 'Keyword Highlight Options',
                   1840:                 txtc => 'Text Color',
                   1841:                 font => 'Font Size',
                   1842:                 fnst => 'Font Style',
                   1843:              );
                   1844:     &js_escape(\%js_lt);
                   1845:     &html_escape(\%html_js_lt);
                   1846:     &js_escape(\%html_js_lt);
                   1847:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   1848: 
                   1849: //===================== Show list of keywords ====================
                   1850:   function keywords(formname) {
                   1851:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   1852:     if (nret==null) return;
                   1853:     formname.keywords.value = nret;
                   1854: 
                   1855:     if (formname.keywords.value != "") {
                   1856:         formname.refresh.value = "on";
                   1857:         formname.submit();
                   1858:     }
                   1859:     return;
                   1860:   }
                   1861: 
                   1862: //===================== Script to add keyword(s) ==================
                   1863:   function getSel() {
                   1864:     if (document.getSelection) txt = document.getSelection();
                   1865:     else if (document.selection) txt = document.selection.createRange().text;
                   1866:     else return;
                   1867:     if (typeof(txt) != 'string') {
                   1868:         txt = String(txt);
                   1869:     }
                   1870:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1871:     if (cleantxt=="") {
                   1872:         alert("$js_lt{'plse'}");
                   1873:         return;
                   1874:     }
                   1875:     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   1876:     if (nret==null) return;
                   1877:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   1878:     if (document.SCORE.keywords.value != "") {
                   1879:         document.SCORE.refresh.value = "on";
                   1880:         document.SCORE.submit();
                   1881:     }
                   1882:     return;
                   1883:   }
                   1884: 
1.44      ng       1885: //====================== Script for keyword highlight options ==============
                   1886:   function kwhighlight() {
                   1887:     var kwclr    = document.SCORE.kwclr.value;
                   1888:     var kwsize   = document.SCORE.kwsize.value;
                   1889:     var kwstyle  = document.SCORE.kwstyle.value;
                   1890:     var redsel = "";
                   1891:     var grnsel = "";
                   1892:     var blusel = "";
1.736     damieng  1893:     var txtcol1 = "$js_lt{'col1'}";
                   1894:     var txtcol2 = "$js_lt{'col2'}";
                   1895:     var txtcol3 = "$js_lt{'col3'}";
                   1896:     var txtsiz1 = "$js_lt{'siz1'}";
                   1897:     var txtsiz2 = "$js_lt{'siz2'}";
                   1898:     var txtsiz3 = "$js_lt{'siz3'}";
                   1899:     var txtsty1 = "$js_lt{'sty1'}";
                   1900:     var txtsty2 = "$js_lt{'sty2'}";
                   1901:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1902:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1903:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1904:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1905:     var sznsel = "";
                   1906:     var sz1sel = "";
                   1907:     var sz2sel = "";
1.718     bisitz   1908:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1909:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1910:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1911:     var synsel = "";
                   1912:     var syisel = "";
                   1913:     var sybsel = "";
1.718     bisitz   1914:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1915:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1916:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1917:     highlightCentral();
1.718     bisitz   1918:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1919:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1920:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1921:     highlightend();
                   1922:     return;
                   1923:   }
                   1924: 
                   1925:   function highlightCentral() {
1.76      ng       1926: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1927:     var xpos = (screen.width-400)/2;
                   1928:     xpos = (xpos < 0) ? '0' : xpos;
                   1929:     var ypos = (screen.height-330)/2-30;
                   1930:     ypos = (ypos < 0) ? '0' : ypos;
                   1931: 
1.206     albertel 1932:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1933:     hwdWin.focus();
                   1934:     var hDoc = hwdWin.document;
1.219     www      1935:     hDoc.$docopen;
1.351     albertel 1936:     hDoc.write('$start_page_highlight_central');
1.76      ng       1937:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1938:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1939: 
1.718     bisitz   1940:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1941:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1942:   }
                   1943: 
                   1944:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1945:     var hDoc = hwdWin.document;
1.718     bisitz   1946:     hDoc.write("<tr>");
1.76      ng       1947:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1948:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1949:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1950:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1951:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1952:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1953:     hDoc.write("<\\/tr>");
1.44      ng       1954:   }
                   1955: 
                   1956:   function highlightend() { 
1.76      ng       1957:     var hDoc = hwdWin.document;
1.718     bisitz   1958:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1959:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1960:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1961:     hDoc.write("<\\/form>");
1.351     albertel 1962:     hDoc.write('$end_page_highlight_central');
1.128     ng       1963:     hDoc.close();
1.44      ng       1964:   }
                   1965: 
                   1966: SUBJAVASCRIPT
                   1967: }
                   1968: 
1.349     albertel 1969: sub get_increment {
1.348     bowersj2 1970:     my $increment = $env{'form.increment'};
                   1971:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1972:         $increment != .1) {
                   1973:         $increment = 1;
                   1974:     }
                   1975:     return $increment;
                   1976: }
                   1977: 
1.585     bisitz   1978: sub gradeBox_start {
                   1979:     return (
                   1980:         &Apache::loncommon::start_data_table()
                   1981:        .&Apache::loncommon::start_data_table_header_row()
                   1982:        .'<th>'.&mt('Part').'</th>'
                   1983:        .'<th>'.&mt('Points').'</th>'
                   1984:        .'<th>&nbsp;</th>'
                   1985:        .'<th>'.&mt('Assign Grade').'</th>'
                   1986:        .'<th>'.&mt('Weight').'</th>'
                   1987:        .'<th>'.&mt('Grade Status').'</th>'
                   1988:        .&Apache::loncommon::end_data_table_header_row()
                   1989:     );
                   1990: }
                   1991: 
                   1992: sub gradeBox_end {
                   1993:     return (
                   1994:         &Apache::loncommon::end_data_table()
                   1995:     );
                   1996: }
1.71      ng       1997: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1998: sub gradeBox {
1.322     albertel 1999:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 2000:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2001: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2002:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2003:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2004:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2005:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2006:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2007: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   2008:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2009:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2010:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2011: 				       [$partid]);
                   2012:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2013:     if ($last_resets{$partid}) {
                   2014:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2015:     }
1.695     bisitz   2016:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2017:     my $ctr = 0;
1.348     bowersj2 2018:     my $thisweight = 0;
1.349     albertel 2019:     my $increment = &get_increment();
1.485     albertel 2020: 
                   2021:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2022:     while ($thisweight<=$wgt) {
1.532     bisitz   2023: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2024:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2025: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2026: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2027: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2028:         $thisweight += $increment;
1.71      ng       2029: 	$ctr++;
                   2030:     }
1.485     albertel 2031:     $radio.='</tr></table>';
                   2032: 
                   2033:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2034: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2035: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2036: 	$wgt.')" /></td>'."\n";
1.485     albertel 2037:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2038: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2039: 	' </td>'."\n";
                   2040:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2041: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2042:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2043: 	$line.='<option></option>'.
                   2044: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2045:     } else {
1.485     albertel 2046: 	$line.='<option selected="selected"></option>'.
                   2047: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2048:     }
1.485     albertel 2049:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2050: 
                   2051: 
                   2052:     $result .= 
1.695     bisitz   2053: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   2054:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   2055:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2056:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2057: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2058: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2059: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2060:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2061:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2062:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2063:         $aggtries.'" />'."\n";
1.582     raeburn  2064:     my $res_error;
                   2065:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   2066:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2067:     if ($res_error) {
                   2068:         return &navmap_errormsg();
                   2069:     }
1.318     banghart 2070:     return $result;
                   2071: }
1.322     albertel 2072: 
                   2073: sub handback_box {
1.623     www      2074:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773     raeburn  2075:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   2076:     return unless ($numessay);
1.323     banghart 2077:     my (@respids);
1.652     raeburn  2078:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2079:     foreach my $part_response_id (@part_response_id) {
                   2080:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2081:         if ($part eq $partid) {
1.375     albertel 2082:             push(@respids,$resp);
1.323     banghart 2083:         }
                   2084:     }
1.318     banghart 2085:     my $result;
1.323     banghart 2086:     foreach my $respid (@respids) {
1.322     albertel 2087: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2088: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2089: 	next if (!@$files);
1.654     raeburn  2090: 	my $file_counter = 0;
1.313     banghart 2091: 	foreach my $file (@$files) {
1.368     banghart 2092: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  2093:                 $file_counter++;
1.368     banghart 2094:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  2095:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 2096:     	        $file_disp = "$name.$ext";
                   2097:     	        $file = $file_path.$file_disp;
                   2098:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2099:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2100:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  2101:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2102: 	    }
1.322     albertel 2103: 	}
1.654     raeburn  2104:         if ($file_counter) {
                   2105:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2106:                        '<span class="LC_info">'.
                   2107:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2108:         }
1.313     banghart 2109:     }
1.318     banghart 2110:     return $result;    
1.71      ng       2111: }
1.44      ng       2112: 
1.58      albertel 2113: sub show_problem {
1.382     albertel 2114:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2115:     my $rendered;
1.382     albertel 2116:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2117:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2118:     if ($mode eq 'both' or $mode eq 'text') {
                   2119: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2120: 						       $env{'request.course.id'},
                   2121: 						       undef,\%form);
1.144     albertel 2122:     }
1.58      albertel 2123:     if ($removeform) {
                   2124: 	$rendered=~s|<form(.*?)>||g;
                   2125: 	$rendered=~s|</form>||g;
1.374     albertel 2126: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2127:     }
1.144     albertel 2128:     my $companswer;
                   2129:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2130: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2131: 	$companswer=
                   2132: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2133: 						    $env{'request.course.id'},
                   2134: 						    %form);
1.144     albertel 2135:     }
1.58      albertel 2136:     if ($removeform) {
                   2137: 	$companswer=~s|<form(.*?)>||g;
                   2138: 	$companswer=~s|</form>||g;
1.144     albertel 2139: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2140:     }
1.671     raeburn  2141:     my $renderheading = &mt('View of the problem');
                   2142:     my $answerheading = &mt('Correct answer');
                   2143:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2144:         my $stu_fullname = $env{'form.fullname'};
                   2145:         if ($stu_fullname eq '') {
                   2146:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2147:         }
                   2148:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2149:         if ($forwhom ne '') {
                   2150:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2151:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2152:         }
                   2153:     }
1.468     albertel 2154:     $rendered=
1.588     bisitz   2155:         '<div class="LC_Box">'
1.671     raeburn  2156:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2157:        .$rendered
                   2158:        .'</div>';
1.468     albertel 2159:     $companswer=
1.588     bisitz   2160:         '<div class="LC_Box">'
1.671     raeburn  2161:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2162:        .$companswer
                   2163:        .'</div>';
1.468     albertel 2164:     my $result;
1.144     albertel 2165:     if ($mode eq 'both') {
1.588     bisitz   2166:         $result=$rendered.$companswer;
1.144     albertel 2167:     } elsif ($mode eq 'text') {
1.588     bisitz   2168:         $result=$rendered;
1.144     albertel 2169:     } elsif ($mode eq 'answer') {
1.588     bisitz   2170:         $result=$companswer;
1.144     albertel 2171:     }
1.71      ng       2172:     return $result;
1.58      albertel 2173: }
1.397     albertel 2174: 
1.396     banghart 2175: sub files_exist {
                   2176:     my ($r, $symb) = @_;
                   2177:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2178:     foreach my $student (@students) {
                   2179:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2180:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2181: 					      $udom,$uname);
1.396     banghart 2182:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2183:         foreach my $submission (@$string) {
                   2184:             my ($partid,$respid) =
                   2185: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2186:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2187: 					   \%record);
                   2188:             return 1 if (@$files);
1.396     banghart 2189:         }
                   2190:     }
1.397     albertel 2191:     return 0;
1.396     banghart 2192: }
1.397     albertel 2193: 
1.394     banghart 2194: sub download_all_link {
                   2195:     my ($r,$symb) = @_;
1.621     www      2196:     unless (&files_exist($r, $symb)) {
1.766     raeburn  2197:         $r->print(&mt('There are currently no submitted documents.'));
                   2198:         return;
1.621     www      2199:     }
1.395     albertel 2200:     my $all_students = 
                   2201: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2202: 
                   2203:     my $parts =
                   2204: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2205: 
1.394     banghart 2206:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2207:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2208:                              'cgi.'.$identifier.'.symb' => $symb,
                   2209:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2210:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2211: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2212:     return;
                   2213: }
                   2214: 
                   2215: sub submit_download_link {
                   2216:     my ($request,$symb) = @_;
                   2217:     if (!$symb) { return ''; }
1.750     raeburn  2218:     my $res_error;
1.773     raeburn  2219:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   2220:         &response_type($symb,\$res_error);
                   2221:     if ($res_error) {
                   2222:         $request->print(&mt('An error occurred retrieving response types'));
                   2223:         return;
                   2224:     }
                   2225:     unless ($numessay) {
                   2226:         $request->print(&mt('No essayresponse items found'));
                   2227:         return;
1.750     raeburn  2228:     }
1.773     raeburn  2229:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2230:     if (@chosenparts) {
                   2231:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   2232:                                           undef,undef,1));
1.750     raeburn  2233:     }
1.773     raeburn  2234:     if ($numessay) {
1.750     raeburn  2235:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2236:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2237:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2238:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2239:         if (ref($fullname) eq 'HASH') {
                   2240:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2241:             if (@students) {
                   2242:                 @{$env{'form.stuinfo'}} = @students;
1.773     raeburn  2243:                 if ($numdropbox) {
1.750     raeburn  2244:                     &download_all_link($request,$symb);
1.773     raeburn  2245:                 } else {
                   2246:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  2247:                 }
1.773     raeburn  2248: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  2249: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2250:             } else {
                   2251:                 $request->print(&mt('No students match the criteria you selected'));
                   2252:             }
                   2253:         } else {
                   2254:             $request->print(&mt('Could not retrieve student information'));
                   2255:         }
                   2256:     } else {
                   2257:         $request->print(&mt('No essayresponse items found'));
                   2258:     }
                   2259:     return;
1.394     banghart 2260: }
1.395     albertel 2261: 
1.432     banghart 2262: sub build_section_inputs {
                   2263:     my $section_inputs;
                   2264:     if ($env{'form.section'} eq '') {
                   2265:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2266:     } else {
                   2267:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2268:         foreach my $section (@sections) {
1.432     banghart 2269:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2270:         }
                   2271:     }
                   2272:     return $section_inputs;
                   2273: }
                   2274: 
1.44      ng       2275: # --------------------------- show submissions of a student, option to grade 
                   2276: sub submission {
1.773     raeburn  2277:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2278:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2279:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2280:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2281:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2282: 
1.324     albertel 2283:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773     raeburn  2284:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  2285:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  2286:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2287: 
                   2288:     if (!&canview($usec)) {
1.712     bisitz   2289:         $request->print(
                   2290:             '<span class="LC_warning">'.
1.713     bisitz   2291:             &mt('Unable to view requested student.').
1.712     bisitz   2292:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2293:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2294:             '</span>');
1.104     albertel 2295: 	return;
                   2296:     }
                   2297: 
1.773     raeburn  2298:     my $res_error;
                   2299:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   2300:         &response_type($symb,\$res_error);
                   2301:     if ($res_error) {
                   2302:         $request->print(&navmap_errormsg());
                   2303:         return;
                   2304:     }
                   2305: 
1.257     albertel 2306:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2307:     unless ($is_tool) { 
                   2308:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2309:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2310:     }
1.773     raeburn  2311:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   2312:         $env{'form.compmsg'} = 1;
                   2313:     }
1.257     albertel 2314:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2315:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2316: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2317: 	'/check.gif" height="16" border="0" />';
1.41      ng       2318: 
                   2319:     # header info
                   2320:     if ($counter == 0) {
1.773     raeburn  2321:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2322:         if (@chosenparts) {
                   2323:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   2324:         } elsif ($divforres) {
                   2325:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   2326:         } else {
                   2327:             $request->print('<br clear="all" />');
                   2328:         }
1.41      ng       2329: 	&sub_page_js($request);
1.773     raeburn  2330:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   2331: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       2332: 
1.44      ng       2333: 	# option to display problem, only once else it cause problems 
                   2334:         # with the form later since the problem has a form.
1.257     albertel 2335: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2336: 	    my $mode;
1.257     albertel 2337: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2338: 		$mode='both';
1.257     albertel 2339: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2340: 		$mode='text';
1.257     albertel 2341: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2342: 		$mode='answer';
                   2343: 	    }
1.329     albertel 2344: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2345: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2346: 	}
1.441     www      2347: 
1.41      ng       2348: 	my %keyhash = ();
1.773     raeburn  2349: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       2350: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2351: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2352: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773     raeburn  2353: 	}
                   2354: 	# kwclr is the only variable that is guaranteed not to be blank
                   2355: 	# if this subroutine has been called once.
                   2356: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 2357: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2358: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2359: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2360: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2361: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773     raeburn  2362: 	}
                   2363: 	if ($env{'form.compmsg'}) {
                   2364: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      2365: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2366: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2367: 	}
1.773     raeburn  2368: 
1.257     albertel 2369: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2370: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2371: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2372: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2373: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2374: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2375: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2376: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2377: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2378: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2379: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2380: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2381: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773     raeburn  2382: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 2383: 			&build_section_inputs().
1.326     albertel 2384: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2385: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2386: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773     raeburn  2387: 	if ($env{'form.compmsg'}) {
                   2388: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   2389: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   2390: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   2391: 	}
                   2392: 	if ($numessay) {
1.257     albertel 2393: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2394: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2395: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773     raeburn  2396: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       2397: 	}
1.773     raeburn  2398: 
1.41      ng       2399: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2400: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2401: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2402: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2403: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2404: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2405: 		'" />'."\n".
                   2406: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2407: 	    $cts++;
                   2408: 	}
                   2409: 	$request->print($prnmsg);
1.32      ng       2410: 
1.773     raeburn  2411: 	if ($numessay) {
1.652     raeburn  2412: 
                   2413:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2414:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2415:                           keyw => 'Keyword Options',
1.655     raeburn  2416:                           list => 'List',
1.652     raeburn  2417:                           past => 'Paste Selection to List',
1.661     www      2418:                           high => 'Highlight Attribute',
1.773     raeburn  2419:                      );
1.88      www      2420: #
                   2421: # Print out the keyword options line
                   2422: #
1.718     bisitz   2423: 	    $request->print(
                   2424:                 '<div class="LC_columnSection">'
                   2425:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2426:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2427:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2428:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2429:  class="page">'.$lt{'past'}.'</a>',
                   2430:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2431:                     {legend => $lt{'keyw'}})
                   2432:                .'</fieldset></div>'
                   2433:             );
                   2434: 
1.88      www      2435: #
                   2436: # Load the other essays for similarity check
                   2437: #
1.753     raeburn  2438:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2439:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2440:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2441:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2442:                 if ($cdom ne '' && $cnum ne '') {
                   2443:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2444:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2445:                         my $apath = $1.'_'.$id;
                   2446:                         $apath=~s/\W/\_/gs;
                   2447:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2448:                     }
                   2449:                 }
                   2450:             } else {
                   2451: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2452: 	        $apath=&escape($apath);
                   2453: 	        $apath=~s/\W/\_/gs;
                   2454:                 &init_old_essays($symb,$apath,$adom,$aname);
                   2455:             }
1.41      ng       2456:         }
                   2457:     }
1.44      ng       2458: 
1.441     www      2459: # This is where output for one specific student would start
1.592     bisitz   2460:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2461:     $request->print(
                   2462:         "\n\n"
                   2463:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2464:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2465:        ."\n"
                   2466:     );
1.441     www      2467: 
1.592     bisitz   2468:     # Show additional functions if allowed
                   2469:     if ($perm{'vgr'}) {
                   2470:         $request->print(
                   2471:             &Apache::loncommon::track_student_link(
1.708     bisitz   2472:                 'View recent activity',
1.592     bisitz   2473:                 $uname,$udom,'check')
                   2474:            .' '
                   2475:         );
                   2476:     }
                   2477:     if ($perm{'opa'}) {
                   2478:         $request->print(
                   2479:             &Apache::loncommon::pprmlink(
                   2480:                 &mt('Set/Change parameters'),
                   2481:                 $uname,$udom,$symb,'check'));
                   2482:     }
                   2483: 
                   2484:     # Show Problem
1.257     albertel 2485:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2486: 	my $mode;
1.257     albertel 2487: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2488: 	    $mode='both';
1.257     albertel 2489: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2490: 	    $mode='text';
1.257     albertel 2491: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2492: 	    $mode='answer';
                   2493: 	}
1.329     albertel 2494: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2495: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2496:     }
1.144     albertel 2497: 
1.257     albertel 2498:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       2499: 
1.44      ng       2500:     # Display student info
1.41      ng       2501:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2502: 
1.745     raeburn  2503:     my $boxtitle = &mt('Submissions');
                   2504:     if ($is_tool) {
                   2505:         $boxtitle = &mt('Transactions')
                   2506:     }
1.590     bisitz   2507:     my $result='<div class="LC_Box">'
1.745     raeburn  2508:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2509:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2510:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773     raeburn  2511:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   2512:         $result.='<p class="LC_info">'
                   2513:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2514:                 ."</p>\n";
1.469     albertel 2515:     }
                   2516: 
1.773     raeburn  2517:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 2518:     my $fullname;
                   2519:     my $col_fullnames = [];
1.773     raeburn  2520:     if ($numessay) {
1.464     albertel 2521: 	(my $sub_result,$fullname,$col_fullnames)=
                   2522: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2523: 				 $counter);
                   2524: 	$result.=$sub_result;
1.41      ng       2525:     }
1.44      ng       2526:     $request->print($result."\n");
1.773     raeburn  2527: 
1.44      ng       2528:     # print student answer/submission
1.773     raeburn  2529:     # Options are (1) Last submission only
                   2530:     #             (2) Last submission (with detailed information for that submission)
                   2531:     #             (3) All transactions (by date)
                   2532:     #             (4) The whole record (with detailed information for all transactions)
                   2533: 
1.745     raeburn  2534:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.773     raeburn  2535: 
1.702     kruse    2536:     my $lastsubonly;
1.468     albertel 2537: 
1.702     kruse    2538:     if ($$timestamp eq '') {
                   2539:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2540:     } elsif ($is_tool) {
                   2541:         $lastsubonly =
                   2542:             '<div class="LC_grade_submissions_body">'
                   2543:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2544:     } else {
                   2545:         $lastsubonly =
                   2546:             '<div class="LC_grade_submissions_body">'
                   2547:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2548: 
                   2549: 	my %seenparts;
                   2550: 	my @part_response_id = &flatten_responseType($responseType);
                   2551: 	foreach my $part (@part_response_id) {
                   2552: 	    my ($partid,$respid) = @{ $part };
                   2553: 	    my $display_part=&get_display_part($partid,$symb);
                   2554: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2555: 		if (exists($seenparts{$partid})) { next; }
                   2556: 		$seenparts{$partid}=1;
                   2557:                 $request->print(
                   2558:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2559:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2560:                                '<a href="javascript:viewSubmitter(\''.
                   2561:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2562:                                '\');" target="_self">'.
                   2563:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2564:                     '<br />');
                   2565: 		next;
1.773     raeburn  2566: 	    }
1.702     kruse    2567: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2568: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2569:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2570:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2571:                     ' <span class="LC_internal_info">'.
                   2572:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2573:                     '</span>&nbsp; &nbsp;'.
                   2574: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2575: 		next;
                   2576: 	    }
                   2577: 	    foreach my $submission (@$string) {
                   2578: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2579: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2580: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2581: 		# Similarity check
                   2582:                 my $similar='';
                   2583:                 my ($type,$trial,$rndseed);
                   2584:                 if ($hide eq 'rand') {
                   2585:                     $type = 'randomizetry';
                   2586:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2587:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2588:                 }
                   2589: 	        if ($env{'form.checkPlag'}) {
1.774     raeburn  2590: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2591: 		    &most_similar($uname,$udom,$symb,$subval);
1.702     kruse    2592: 		    if ($osim) {
                   2593: 			$osim=int($osim*100.0);
                   2594:                         if ($hide eq 'anon') {
                   2595:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2596:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2597:                         } else {
1.753     raeburn  2598: 			    $similar='<hr />';
                   2599:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2600:                                 $similar .= '<h3><span class="LC_warning">'.
                   2601:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2602:                                                 $osim,
                   2603:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2604:                                             '</span></h3>';
                   2605:                             } else {
                   2606:                                 my %old_course_desc;
                   2607:                                 if ($ocrsid ne '') {
                   2608:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2609:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
                   2610:                                     } else {
                   2611:                                         my $args;
                   2612:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   2613:                                             $args = {'one_time' => 1};
                   2614:                                         }
                   2615:                                         %old_course_desc =
                   2616:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
                   2617:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
                   2618:                                     }
                   2619:                                     $similar .=
                   2620:                                         '<h3><span class="LC_warning">'.
                   2621:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2622:                                             $osim,
                   2623:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2624:                                             $old_course_desc{'description'},
                   2625:                                             $old_course_desc{'num'},
                   2626:                                             $old_course_desc{'domain'}).
                   2627:                                         '</span></h3>';
                   2628:                                 } else {
                   2629:                                     $similar .=
                   2630:                                         '<h3><span class="LC_warning">'.
                   2631:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2632:                                             $osim,
                   2633:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2634:                                         '</span></h3>';
                   2635:                                 }
                   2636:                             }
                   2637:                             $similar .= '<blockquote><i>'.
                   2638:                                         &keywords_highlight($oessay).
                   2639:                                         '</i></blockquote><hr />';
1.702     kruse    2640:                         }
                   2641: 	            }
                   2642: 		}
                   2643: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2644:                                      undef,$type,$trial,$rndseed);
1.773     raeburn  2645:                 if (($env{'form.lastSub'} eq 'lastonly') ||
                   2646:                     ($env{'form.lastSub'} eq 'datesub')  ||
                   2647:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
1.702     kruse    2648: 		    my $display_part=&get_display_part($partid,$symb);
                   2649:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2650:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2651:                         ' <span class="LC_internal_info">'.
                   2652:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2653:                         '</span>&nbsp; &nbsp;';
                   2654: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2655: 		    if (@$files) {
                   2656:                         if ($hide eq 'anon') {
                   2657:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2658:                         } else {
                   2659:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2660:                                         .'<br /><span class="LC_warning">';
                   2661:                             if(@$files == 1) {
                   2662:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2663:                             } else {
1.702     kruse    2664:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2665:                             }
1.774     raeburn  2666:                             $lastsubonly .= '</span>';
1.702     kruse    2667:                             foreach my $file (@$files) {
                   2668:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2669:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2670:                             }
                   2671:                         }
1.702     kruse    2672: 			$lastsubonly.='<br />';
                   2673:                     }
                   2674:                     if ($hide eq 'anon') {
                   2675:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2676:                     } else {
1.774     raeburn  2677:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  2678:                         if ($draft) {
                   2679:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2680:                         }
                   2681:                         $subval =
1.702     kruse    2682: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2683: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2684:                         if ($responsetype eq 'essay') {
                   2685:                             $subval =~ s{\n}{<br />}g;
                   2686:                         }
                   2687:                         $lastsubonly.=$subval."\n";
1.702     kruse    2688:                     }
1.774     raeburn  2689:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.702     kruse    2690: 		    $lastsubonly.='</div>';
1.41      ng       2691: 		}
1.702     kruse    2692:             }
1.151     albertel 2693: 	}
1.702     kruse    2694: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2695:     }
                   2696:     $request->print($lastsubonly);
                   2697:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2698:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2699: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.773     raeburn  2700:     }
1.702     kruse    2701:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2702:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2703:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2704: 								 $env{'request.course.id'},
1.44      ng       2705: 								 $last,'.submission',
1.726     raeburn  2706: 								 'Apache::grades::keywords_highlight',
                   2707:                                                                  $usec,$identifier));
1.41      ng       2708:     }
1.121     ng       2709:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2710: 	.$udom.'" />'."\n");
1.44      ng       2711:     # return if view submission with no grading option
1.618     www      2712:     if (!&canmodify($usec)) {
1.633     www      2713: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2714: 	return;
1.180     albertel 2715:     } else {
1.468     albertel 2716: 	$request->print('</div>'."\n");
1.41      ng       2717:     }
1.33      ng       2718: 
1.773     raeburn  2719:     # grading message center
                   2720: 
                   2721:     if ($env{'form.compmsg'}) {
                   2722:         my $result='<div class="LC_Box">'.
                   2723:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2724:                    '<div class="LC_grade_message_center_body">';
                   2725:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2726:         my $msgfor = $givenn.' '.$lastname;
                   2727:         if (scalar(@$col_fullnames) > 0) {
                   2728:             my $lastone = pop(@$col_fullnames);
                   2729:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2730:         }
                   2731:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2732:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2733:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2734:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2735:                  ',\''.$msgfor.'\');" target="_self">'.
                   2736:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2737:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2738:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2739:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2740:                  '<br />&nbsp;('.
                   2741:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2742:                  '</div></div>';
                   2743:         $request->print($result);
1.118     ng       2744:     }
1.41      ng       2745: 
                   2746:     my %seen = ();
                   2747:     my @partlist;
1.129     ng       2748:     my @gradePartRespid;
1.745     raeburn  2749:     my @part_response_id;
                   2750:     if ($is_tool) {
                   2751:         @part_response_id = ([0,'']);
                   2752:     } else {
                   2753:         @part_response_id = &flatten_responseType($responseType);
                   2754:     }
1.585     bisitz   2755:     $request->print(
1.588     bisitz   2756:         '<div class="LC_Box">'
                   2757:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2758:     );
1.592     bisitz   2759:     $request->print(&gradeBox_start());
1.375     albertel 2760:     foreach my $part_response_id (@part_response_id) {
                   2761:     	my ($partid,$respid) = @{ $part_response_id };
                   2762: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2763: 	next if ($seen{$partid} > 0);
1.41      ng       2764: 	$seen{$partid}++;
1.524     raeburn  2765: 	push(@partlist,$partid);
                   2766: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2767: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2768:     }
1.585     bisitz   2769:     $request->print(&gradeBox_end()); # </div>
                   2770:     $request->print('</div>');
1.468     albertel 2771: 
                   2772:     $request->print('<div class="LC_grade_info_links">');
                   2773:     $request->print('</div>');
                   2774: 
1.45      ng       2775:     $result='<input type="hidden" name="partlist'.$counter.
                   2776: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2777:     $result.='<input type="hidden" name="gradePartRespid'.
                   2778: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2779:     my $ctr = 0;
                   2780:     while ($ctr < scalar(@partlist)) {
                   2781: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2782: 	    $partlist[$ctr].'" />'."\n";
                   2783: 	$ctr++;
                   2784:     }
1.468     albertel 2785:     $request->print($result.''."\n");
1.41      ng       2786: 
1.441     www      2787: # Done with printing info for one student
                   2788: 
1.468     albertel 2789:     $request->print('</div>');#LC_grade_show_user
1.441     www      2790: 
                   2791: 
1.41      ng       2792:     # print end of form
                   2793:     if ($counter == $total) {
1.592     bisitz   2794:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2795: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2796: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2797: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2798: 	my $ntstu ='<select name="NTSTU">'.
                   2799: 	    '<option>1</option><option>2</option>'.
                   2800: 	    '<option>3</option><option>5</option>'.
                   2801: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2802: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2803: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2804:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2805: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2806: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2807: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2808: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2809:         $endform.='<span class="LC_warning">'.
                   2810:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2811:                   '</span>'."\n" ;
1.349     albertel 2812:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2813:             "' name='increment' />";
1.485     albertel 2814: 	$endform.='</td></tr></table></form>';
1.41      ng       2815: 	$request->print($endform);
                   2816:     }
                   2817:     return '';
1.38      ng       2818: }
                   2819: 
1.464     albertel 2820: sub check_collaborators {
                   2821:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2822:     my ($result,@col_fullnames);
                   2823:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2824:     foreach my $part (keys(%$handgrade)) {
                   2825: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2826: 					'.maxcollaborators',
                   2827: 					$symb,$udom,$uname);
                   2828: 	next if ($ncol <= 0);
                   2829: 	$part =~ s/\_/\./g;
                   2830: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2831: 	my (@good_collaborators, @bad_collaborators);
                   2832: 	foreach my $possible_collaborator
1.630     www      2833: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2834: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2835: 	    next if ($possible_collaborator eq '');
1.631     www      2836: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2837: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2838: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2839: 	    # Doing this grep allows 'fuzzy' specification
                   2840: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2841: 			       keys(%$classlist));
                   2842: 	    if (! scalar(@matches)) {
                   2843: 		push(@bad_collaborators, $possible_collaborator);
                   2844: 	    } else {
                   2845: 		push(@good_collaborators, @matches);
                   2846: 	    }
                   2847: 	}
                   2848: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2849: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2850: 	    foreach my $name (@good_collaborators) {
                   2851: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2852: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2853: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2854: 	    }
1.630     www      2855: 	    $result.='</ol><br />'."\n";
1.466     albertel 2856: 	    my ($part)=split(/\./,$part);
1.464     albertel 2857: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2858: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2859: 		"\n";
                   2860: 	}
                   2861: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2862: 	    $result.='<div class="LC_warning">';
1.464     albertel 2863: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2864: 	    $result .= '</div>';
                   2865: 	}         
                   2866: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2867: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2868: 	    $result .= &mt('This student has submitted too many '.
                   2869: 		'collaborators.  Maximum is [_1].',$ncol);
                   2870: 	    $result .= '</div>';
                   2871: 	}
                   2872:     }
                   2873:     return ($result,$fullname,\@col_fullnames);
                   2874: }
                   2875: 
1.44      ng       2876: #--- Retrieve the last submission for all the parts
1.38      ng       2877: sub get_last_submission {
1.745     raeburn  2878:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2879:     my (@string,$timestamp,%lasthidden);
1.119     ng       2880:     if ($$returnhash{'version'}) {
1.46      ng       2881: 	my %lasthash=();
                   2882: 	my ($version);
1.119     ng       2883: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2884: 	    foreach my $key (sort(split(/\:/,
                   2885: 					$$returnhash{$version.':keys'}))) {
                   2886: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2887: 		$timestamp = 
1.545     raeburn  2888: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2889: 	    }
                   2890: 	}
1.640     raeburn  2891:         my (%typeparts,%randombytry);
1.596     raeburn  2892:         my $showsurv = 
                   2893:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2894:         foreach my $key (sort(keys(%lasthash))) {
                   2895:             if ($key =~ /\.type$/) {
                   2896:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2897:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2898:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2899:                     my ($ign,@parts) = split(/\./,$key);
                   2900:                     pop(@parts);
1.641     raeburn  2901:                     my $id = join('.',@parts);
1.640     raeburn  2902:                     if ($lasthash{$key} eq 'randomizetry') {
                   2903:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2904:                     } else {
                   2905:                         unless ($showsurv) {
                   2906:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2907:                         }
1.596     raeburn  2908:                     }
                   2909:                     delete($lasthash{$key});
                   2910:                 }
                   2911:             }
                   2912:         }
                   2913:         my @hidden = keys(%typeparts);
1.640     raeburn  2914:         my @randomize = keys(%randombytry);
1.397     albertel 2915: 	foreach my $key (keys(%lasthash)) {
                   2916: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2917:             my $hide;
                   2918:             if (@hidden) {
                   2919:                 foreach my $id (@hidden) {
                   2920:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2921:                         $hide = 'anon';
1.596     raeburn  2922:                         last;
                   2923:                     }
                   2924:                 }
                   2925:             }
1.640     raeburn  2926:             unless ($hide) {
                   2927:                 if (@randomize) {
1.732     raeburn  2928:                     foreach my $id (@randomize) {
1.640     raeburn  2929:                         if ($key =~ /^\Q$id\E/) {
                   2930:                             $hide = 'rand';
                   2931:                             last;
                   2932:                         }
                   2933:                     }
                   2934:                 }
                   2935:             }
1.397     albertel 2936: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2937: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2938:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2939:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2940:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2941: 	}
                   2942:     }
1.397     albertel 2943:     if (!@string) {
1.745     raeburn  2944:         my $msg;
                   2945:         if ($is_tool) {
1.747     raeburn  2946:             $msg = &mt('No grade passed back.');
1.745     raeburn  2947:         } else {
                   2948:             $msg = &mt('Nothing submitted - no attempts.');
                   2949:         }
1.397     albertel 2950: 	$string[0] =
1.745     raeburn  2951: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2952:     }
                   2953:     return (\@string,\$timestamp);
1.38      ng       2954: }
1.35      ng       2955: 
1.44      ng       2956: #--- High light keywords, with style choosen by user.
1.38      ng       2957: sub keywords_highlight {
1.44      ng       2958:     my $string    = shift;
1.257     albertel 2959:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2960:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2961:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2962:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2963:     foreach my $keyword (@keylist) {
                   2964: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2965:     }
                   2966:     return $string;
1.38      ng       2967: }
1.36      ng       2968: 
1.671     raeburn  2969: # For Tasks provide a mechanism to display previous version for one specific student
                   2970: 
                   2971: sub show_previous_task_version {
                   2972:     my ($request,$symb) = @_;
                   2973:     if ($symb eq '') {
1.717     bisitz   2974:         $request->print(
                   2975:             '<span class="LC_error">'.
                   2976:             &mt('Unable to handle ambiguous references.').
                   2977:             '</span>');
1.671     raeburn  2978:         return '';
                   2979:     }
                   2980:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2981:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2982:     if (!&canview($usec)) {
1.712     bisitz   2983:         $request->print(
                   2984:             '<span class="LC_warning">'.
1.713     bisitz   2985:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2986:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2987:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2988:             '</span>');
1.671     raeburn  2989:         return;
                   2990:     }
                   2991:     my $mode = 'both';
                   2992:     my $isTask = ($symb =~/\.task$/);
                   2993:     if ($isTask) {
                   2994:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2995:             if ($env{'form.fullname'} eq '') {
                   2996:                 $env{'form.fullname'} =
                   2997:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2998:             }
                   2999:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   3000:             $request->print("\n\n".
                   3001:                             '<div class="LC_grade_show_user">'.
                   3002:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   3003:                             '</h2>'."\n");
                   3004:             &Apache::lonxml::clear_problem_counter();
                   3005:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   3006:                             {'previousversion' => $env{'form.previousversion'} }));
                   3007:             $request->print("\n</div>");
                   3008:         }
                   3009:     }
                   3010:     return;
                   3011: }
                   3012: 
                   3013: sub choose_task_version_form {
                   3014:     my ($symb,$uname,$udom,$nomenu) = @_;
                   3015:     my $isTask = ($symb =~/\.task$/);
                   3016:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   3017:     if ($isTask) {
                   3018:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3019:                                               $udom,$uname);
                   3020:         if (($record{'resource.0.version'} eq '') ||
                   3021:             ($record{'resource.0.version'} < 2)) {
                   3022:             return ($record{'resource.0.version'},
                   3023:                     $record{'resource.0.version'},$result,$js);
                   3024:         } else {
                   3025:             $current = $record{'resource.0.version'};
                   3026:         }
                   3027:         if ($env{'form.previousversion'}) {
                   3028:             $displayed = $env{'form.previousversion'};
                   3029:             $rowtitle = &mt('Choose another version:')
                   3030:         } else {
                   3031:             $displayed = $current;
                   3032:             $rowtitle = &mt('Show earlier version:');
                   3033:         }
                   3034:         $result = '<div class="LC_left_float">';
                   3035:         my $list;
                   3036:         my $numversions = 0;
                   3037:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3038:             if ($i == $current) {
                   3039:                 if (!$env{'form.previousversion'} || $nomenu) {
                   3040:                     next;
                   3041:                 } else {
                   3042:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3043:                     $numversions ++;
                   3044:                 }
                   3045:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3046:                 unless ($i == $env{'form.previousversion'}) {
                   3047:                     $numversions ++;
                   3048:                 }
                   3049:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3050:             }
                   3051:         }
                   3052:         if ($numversions) {
                   3053:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3054:             $result .=
                   3055:                 '<form name="getprev" method="post" action=""'.
                   3056:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3057:                 &Apache::loncommon::start_data_table().
                   3058:                 &Apache::loncommon::start_data_table_row().
                   3059:                 '<th align="left">'.$rowtitle.'</th>'.
                   3060:                 '<td><select name="version">'.
                   3061:                 '<option>'.&mt('Select').'</option>'.
                   3062:                 $list.
                   3063:                 '</select></td>'.
                   3064:                 &Apache::loncommon::end_data_table_row();
                   3065:             unless ($nomenu) {
                   3066:                 $result .= &Apache::loncommon::start_data_table_row().
                   3067:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3068:                 '<td><span class="LC_nobreak">'.
                   3069:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3070:                 &mt('Yes').'</label>'.
                   3071:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3072:                 '</span></td>'.
                   3073:                 &Apache::loncommon::end_data_table_row();
                   3074:             }
                   3075:             $result .=
                   3076:                 &Apache::loncommon::start_data_table_row().
                   3077:                 '<th align="left">&nbsp;</th>'.
                   3078:                 '<td>'.
                   3079:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3080:                 '</td>'.
                   3081:                 &Apache::loncommon::end_data_table_row().
                   3082:                 &Apache::loncommon::end_data_table().
                   3083:                 '</form>';
                   3084:             $js = &previous_display_javascript($nomenu,$current);
                   3085:         } elsif ($displayed && $nomenu) {
                   3086:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3087:         } else {
                   3088:             $result .= &mt('No previous versions to show for this student');
                   3089:         }
                   3090:         $result .= '</div>';
                   3091:     }
                   3092:     return ($current,$displayed,$result,$js);
                   3093: }
                   3094: 
                   3095: sub previous_display_javascript {
                   3096:     my ($nomenu,$current) = @_;
                   3097:     my $js = <<"JSONE";
                   3098: <script type="text/javascript">
                   3099: // <![CDATA[
                   3100: function previousVersion(uname,udom,symb) {
                   3101:     var current = '$current';
                   3102:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3103:     var prevstr = new RegExp("^\\\\d+\$");
                   3104:     if (!prevstr.test(version)) {
                   3105:         return false;
                   3106:     }
                   3107:     var url = '';
                   3108:     if (version == current) {
                   3109:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3110:     } else {
                   3111:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3112:     }
                   3113: JSONE
                   3114:     if ($nomenu) {
                   3115:         $js .= <<"JSTWO";
                   3116:     document.location.href = url;
                   3117: JSTWO
                   3118:     } else {
                   3119:         $js .= <<"JSTHREE";
                   3120:     var newwin = 0;
                   3121:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3122:         if (document.getprev.prevwin[i].checked == true) {
                   3123:             newwin = document.getprev.prevwin[i].value;
                   3124:         }
                   3125:     }
                   3126:     if (newwin == 1) {
                   3127:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3128:         url = url+'&inhibitmenu=yes';
                   3129:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3130:             previousWin = window.open(url,'',options,1);
                   3131:         } else {
                   3132:             previousWin.location.href = url;
                   3133:         }
                   3134:         previousWin.focus();
                   3135:         return false;
                   3136:     } else {
                   3137:         document.location.href = url;
                   3138:         return false;
                   3139:     }
                   3140: JSTHREE
                   3141:     }
                   3142:     $js .= <<"ENDJS";
                   3143:     return false;
                   3144: }
                   3145: // ]]>
                   3146: </script>
                   3147: ENDJS
                   3148: 
                   3149: }
                   3150: 
1.44      ng       3151: #--- Called from submission routine
1.38      ng       3152: sub processHandGrade {
1.608     www      3153:     my ($request,$symb) = @_;
1.324     albertel 3154:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3155:     my $button = $env{'form.gradeOpt'};
                   3156:     my $ngrade = $env{'form.NCT'};
                   3157:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3158:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3159:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3160: 
1.44      ng       3161:     if ($button eq 'Save & Next') {
                   3162: 	my $ctr = 0;
                   3163: 	while ($ctr < $ngrade) {
1.257     albertel 3164: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  3165: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   3166:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3167: 	    if ($errorflag eq 'no_score') {
                   3168: 		$ctr++;
                   3169: 		next;
                   3170: 	    }
1.104     albertel 3171: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3172: 		$request->print(
                   3173:                     '<span class="LC_error">'
                   3174:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3175:                    .'</span>');
1.104     albertel 3176: 		$ctr++;
                   3177: 		next;
                   3178: 	    }
1.726     raeburn  3179:             if ($numhidden) {
                   3180:                 $request->print(
                   3181:                     '<span class="LC_info">'
                   3182:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3183:                    .'</span><br />');
                   3184:             }
1.257     albertel 3185: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3186: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3187: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3188:             my ($feedurl,$showsymb) =
                   3189: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3190: 	    my $messagetail;
1.62      albertel 3191: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3192: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3193: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3194: 		$subject.=' ['.$restitle.']';
1.44      ng       3195: 		my (@msgnum) = split(/,/,$includemsg);
                   3196: 		foreach (@msgnum) {
1.257     albertel 3197: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3198: 		}
1.80      ng       3199: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3200: 		if ($env{'form.withgrades'.$ctr}) {
                   3201: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3202: 		    $messagetail = " for <a href=\"".
1.605     www      3203: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3204: 		}
                   3205: 		$msgstatus = 
                   3206:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3207: 						     $message.$messagetail,
1.418     albertel 3208:                                                      undef,$feedurl,undef,
1.386     raeburn  3209:                                                      undef,undef,$showsymb,
                   3210:                                                      $restitle);
1.574     bisitz   3211: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3212: 				$msgstatus.'<br />');
1.44      ng       3213: 	    }
1.257     albertel 3214: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3215: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3216: 		foreach my $collabstr (@collabstrs) {
                   3217: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3218: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3219: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3220: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3221: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3222: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3223: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3224: 			    next;
1.418     albertel 3225: 			} elsif ($message ne '') {
                   3226: 			    my ($baseurl,$showsymb) = 
                   3227: 				&get_feedurl_and_symb($symb,$collaborator,
                   3228: 						      $udom);
                   3229: 			    if ($env{'form.withgrades'.$ctr}) {
                   3230: 				$messagetail = " for <a href=\"".
1.605     www      3231:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3232: 			    }
1.418     albertel 3233: 			    $msgstatus = 
                   3234: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3235: 			}
1.44      ng       3236: 		    }
                   3237: 		}
                   3238: 	    }
                   3239: 	    $ctr++;
                   3240: 	}
                   3241:     }
                   3242: 
1.773     raeburn  3243:     my $res_error;
                   3244:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3245:     if ($res_error) {
                   3246:         $request->print(&navmap_errormsg());
                   3247:         return;
                   3248:     }
                   3249: 
                   3250:     my %keyhash = ();
                   3251:     if ($numessay) {
1.119     ng       3252: 	# Keywords sorted in alphabatical order
1.257     albertel 3253: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3254: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  3255: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3256: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3257: 	$env{'form.keywords'} = join(' ',@keywords);
                   3258: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3259: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3260: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3261: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3262: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  3263:     }
1.119     ng       3264: 
1.773     raeburn  3265:     if ($env{'form.compmsg'}) {
1.119     ng       3266: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3267: 	# New messages are saved in env for the next student.
1.119     ng       3268: 	# All messages are saved in nohist_handgrade.db
                   3269: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3270: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3271: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3272: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3273: 		$idx++;
                   3274: 	    }
                   3275: 	    $ctr++;
1.41      ng       3276: 	}
1.119     ng       3277: 	$ctr = 0;
                   3278: 	while ($ctr < $ngrade) {
1.257     albertel 3279: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  3280: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3281: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3282: 	        $idx++;
1.119     ng       3283: 	    }
                   3284: 	    $ctr++;
1.41      ng       3285: 	}
1.257     albertel 3286: 	$env{'form.savemsgN'} = --$idx;
                   3287: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       3288:     }
1.773     raeburn  3289:     if (($numessay) || ($env{'form.compmsg'})) {
                   3290:         my $putresult = &Apache::lonnet::put
                   3291:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   3292:     }
                   3293: 
1.44      ng       3294:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3295:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3296:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3297: 	my ($ctr,$total) = (0,0);
                   3298: 	while ($ctr < $ngrade) {
1.257     albertel 3299: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3300: 	    $ctr++;
                   3301: 	}
1.257     albertel 3302: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3303: 	$ctr = 0;
                   3304: 	while ($ctr < $total) {
1.257     albertel 3305: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3306: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3307: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3308: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3309: 	    $ctr++;
                   3310: 	}
                   3311: 	return '';
                   3312:     }
1.36      ng       3313: 
1.44      ng       3314:     # Get the next/previous one or group of students
1.257     albertel 3315:     my $firststu = $env{'form.unamedom0'};
                   3316:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3317:     my $ctr = 2;
1.41      ng       3318:     while ($laststu eq '') {
1.257     albertel 3319: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3320: 	$ctr++;
                   3321: 	$laststu = $firststu if ($ctr > $ngrade);
                   3322:     }
1.44      ng       3323: 
1.41      ng       3324:     my (@parsedlist,@nextlist);
                   3325:     my ($nextflg) = 0;
1.524     raeburn  3326:     foreach my $item (sort 
1.294     albertel 3327: 	     {
                   3328: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3329: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3330: 		 }
                   3331: 		 return $a cmp $b;
                   3332: 	     } (keys(%$fullname))) {
1.41      ng       3333: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3334: 	    push(@parsedlist,$item);
1.41      ng       3335: 	}
1.524     raeburn  3336: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3337: 	if ($button eq 'Previous') {
1.524     raeburn  3338: 	    last if ($item eq $firststu);
                   3339: 	    push(@parsedlist,$item);
1.41      ng       3340: 	}
                   3341:     }
                   3342:     $ctr = 0;
                   3343:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3344:     foreach my $student (@parsedlist) {
1.257     albertel 3345: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3346: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3347: 	
                   3348: 	if ($submitonly eq 'queued') {
                   3349: 	    my %queue_status = 
                   3350: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3351: 							$udom,$uname);
                   3352: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3353: 	}
                   3354: 
1.156     albertel 3355: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3356: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3357: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3358: 	    my $submitted = 0;
1.248     albertel 3359: 	    my $ungraded = 0;
                   3360: 	    my $incorrect = 0;
1.524     raeburn  3361: 	    foreach my $item (keys(%status)) {
                   3362: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3363: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3364: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3365: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3366: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3367: 		    $submitted = 0;
                   3368: 		}
1.41      ng       3369: 	    }
1.156     albertel 3370: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3371: 				     $submitonly eq 'incorrect' ||
                   3372: 				     $submitonly eq 'graded'));
1.248     albertel 3373: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3374: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3375: 	}
1.524     raeburn  3376: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3377: 	last if ($ctr == $ntstu);
1.41      ng       3378: 	$ctr++;
                   3379:     }
1.36      ng       3380: 
1.41      ng       3381:     $ctr = 0;
                   3382:     my $total = scalar(@nextlist)-1;
1.39      ng       3383: 
1.524     raeburn  3384:     foreach (sort(@nextlist)) {
1.41      ng       3385: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3386: 	$env{'form.student'}  = $uname;
                   3387: 	$env{'form.userdom'}  = $udom;
                   3388: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3389: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3390: 	$ctr++;
                   3391:     }
                   3392:     if ($total < 0) {
1.653     raeburn  3393: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3394: 	$request->print($the_end);
                   3395:     }
                   3396:     return '';
1.38      ng       3397: }
1.36      ng       3398: 
1.44      ng       3399: #---- Save the score and award for each student, if changed
1.38      ng       3400: sub saveHandGrade {
1.324     albertel 3401:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3402:     my @version_parts;
1.104     albertel 3403:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3404: 					   $env{'request.course.id'});
1.104     albertel 3405:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3406:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3407:     my @parts_graded;
1.77      ng       3408:     my %newrecord  = ();
1.726     raeburn  3409:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3410:     my %aggregate = ();
                   3411:     my $aggregateflag = 0;
1.726     raeburn  3412:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3413:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3414:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3415:         $totchg += $numchgs;
                   3416:     }
1.301     albertel 3417:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3418:     foreach my $new_part (@parts) {
1.337     banghart 3419: 	#collaborator ($submi may vary for different parts
1.259     banghart 3420: 	if ($submitter && $new_part ne $part) { next; }
                   3421: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3422: 	if ($dropMenu eq 'excused') {
1.259     banghart 3423: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3424: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3425: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3426: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3427: 		}
1.364     banghart 3428: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3429: 	    }
1.125     ng       3430: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3431: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3432: 	    foreach my $key (keys(%record)) {
1.259     banghart 3433: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3434: 	    }
1.259     banghart 3435: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3436: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3437:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3438: 
                   3439:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3440: 					       [$new_part]);
                   3441:             my $aggtries =$totaltries;
1.269     raeburn  3442:             if ($last_resets{$new_part}) {
1.270     albertel 3443:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3444: 					   $new_part);
1.269     raeburn  3445:             }
1.270     albertel 3446: 
                   3447:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3448:             if ($aggtries > 0) {
1.327     albertel 3449:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3450:                 $aggregateflag = 1;
                   3451:             }
1.125     ng       3452: 	} elsif ($dropMenu eq '') {
1.259     banghart 3453: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3454: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3455: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3456: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3457: 		next;
                   3458: 	    }
1.259     banghart 3459: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3460: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3461: 	    my $partial= $pts/$wgt;
1.259     banghart 3462: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3463: 		#do not update score for part if not changed.
1.346     banghart 3464:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3465: 		next;
1.251     banghart 3466: 	    } else {
1.524     raeburn  3467: 	        push(@parts_graded,$new_part);
1.153     albertel 3468: 	    }
1.259     banghart 3469: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3470: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3471: 	    }
1.259     banghart 3472: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3473: 	    if ($partial == 0) {
1.153     albertel 3474: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3475: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3476: 		}
1.41      ng       3477: 	    } else {
1.153     albertel 3478: 		if ($record{$reckey} ne 'correct_by_override') {
                   3479: 		    $newrecord{$reckey} = 'correct_by_override';
                   3480: 		}
                   3481: 	    }	    
                   3482: 	    if ($submitter && 
1.259     banghart 3483: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3484: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3485: 	    }
1.259     banghart 3486: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3487: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3488: 	}
1.259     banghart 3489: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3490: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3491: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3492: 	        $dropMenu eq 'reset status')
                   3493: 	   {
1.524     raeburn  3494: 	    push(@version_parts,$new_part);
1.259     banghart 3495: 	}
1.41      ng       3496:     }
1.301     albertel 3497:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3498:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3499: 
1.344     albertel 3500:     if (%newrecord) {
                   3501:         if (@version_parts) {
1.364     banghart 3502:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3503:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3504: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3505: 	    foreach my $new_part (@version_parts) {
                   3506: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3507: 				$new_part,\%newrecord);
                   3508: 	    }
1.259     banghart 3509:         }
1.44      ng       3510: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3511: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3512: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3513: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3514:     }
1.269     raeburn  3515:     if ($aggregateflag) {
                   3516:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3517: 			      $cdom,$cnum);
1.269     raeburn  3518:     }
1.726     raeburn  3519:     return ('',$pts,$wgt,$totchg);
                   3520: }
                   3521: 
                   3522: sub makehidden {
1.728     raeburn  3523:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3524:     return unless (ref($record) eq 'HASH');
                   3525:     my %modified;
                   3526:     my $numchanged = 0;
                   3527:     if (exists($record->{$version.':keys'})) {
                   3528:         my $partsregexp = $parts;
                   3529:         $partsregexp =~ s/,/|/g;
                   3530:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3531:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3532:                  my $item = $1;
                   3533:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3534:                      $modified{$key} = $record->{$version.':'.$key};
                   3535:                  }
                   3536:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3537:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3538:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3539:                 $modified{$key} = $record->{$version.':'.$key};
                   3540:             }
                   3541:         }
                   3542:         if (keys(%modified)) {
                   3543:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3544:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3545:                 $numchanged ++;
                   3546:             }
                   3547:         }
                   3548:     }
                   3549:     return $numchanged;
1.36      ng       3550: }
1.322     albertel 3551: 
1.380     albertel 3552: sub check_and_remove_from_queue {
                   3553:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3554:     my @ungraded_parts;
                   3555:     foreach my $part (@{$parts}) {
                   3556: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3557: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3558: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3559: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3560: 		) {
                   3561: 	    push(@ungraded_parts, $part);
                   3562: 	}
                   3563:     }
                   3564:     if ( !@ungraded_parts ) {
                   3565: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3566: 					       $cnum,$domain,$stuname);
                   3567:     }
                   3568: }
                   3569: 
1.337     banghart 3570: sub handback_files {
                   3571:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3572:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3573:     my $res_error;
                   3574:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3575:     if ($res_error) {
                   3576:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3577:         return;
                   3578:     }
1.654     raeburn  3579:     my @handedback;
                   3580:     my $file_msg;
1.375     albertel 3581:     my @part_response_id = &flatten_responseType($responseType);
                   3582:     foreach my $part_response_id (@part_response_id) {
                   3583:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3584: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3585:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3586:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3587:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3588:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3589:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3590:                     my ($directory,$answer_file) = 
1.654     raeburn  3591:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3592:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3593: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3594: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3595:                     my $getpropath = 1;
1.773     raeburn  3596:                     my ($dir_list,$listerror) =
1.662     raeburn  3597:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3598:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3599: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3600:                     # fix filename
1.355     banghart 3601:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3602:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3603:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3604:             	                                $save_file_name);
1.337     banghart 3605:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3606:                         $request->print('<br /><span class="LC_error">'.
                   3607:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3608:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3609:                                         '</span>');
1.356     banghart 3610:                     } else {
1.360     banghart 3611:                         # mark the file as read only
1.654     raeburn  3612:                         push(@handedback,$save_file_name);
1.367     albertel 3613: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3614: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3615: 			}
                   3616:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3617: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3618:                     }
1.686     bisitz   3619:                     $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 3620:                 }
                   3621:             }
                   3622:         }
1.654     raeburn  3623:     }
                   3624:     if (@handedback > 0) {
                   3625:         $request->print('<br />');
                   3626:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3627:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3628:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3629:         my ($subject,$message);
                   3630:         if (scalar(@handedback) == 1) {
                   3631:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3632:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3633:         } else {
                   3634:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3635:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3636:         }
                   3637:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3638:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3639:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3640:         my ($feedurl,$showsymb) =
                   3641:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3642:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3643:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3644:         my $msgstatus =
                   3645:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3646:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3647:                  $restitle);
                   3648:         if ($msgstatus) {
                   3649:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3650:         }
                   3651:     }
1.338     banghart 3652:     return;
1.337     banghart 3653: }
                   3654: 
1.418     albertel 3655: sub get_feedurl_and_symb {
                   3656:     my ($symb,$uname,$udom) = @_;
                   3657:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3658:     $url = &Apache::lonnet::clutter($url);
                   3659:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3660: 					$symb,$udom,$uname);
                   3661:     if ($encrypturl =~ /^yes$/i) {
                   3662: 	&Apache::lonenc::encrypted(\$url,1);
                   3663: 	&Apache::lonenc::encrypted(\$symb,1);
                   3664:     }
                   3665:     return ($url,$symb);
                   3666: }
                   3667: 
1.313     banghart 3668: sub get_submitted_files {
                   3669:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3670:     my @files;
                   3671:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3672:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3673:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3674:     	    push(@files,$file_url.$file);
                   3675:         }
                   3676:     }
                   3677:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3678:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3679:     }
                   3680:     return (\@files);
                   3681: }
1.322     albertel 3682: 
1.269     raeburn  3683: # ----------- Provides number of tries since last reset.
                   3684: sub get_num_tries {
                   3685:     my ($record,$last_reset,$part) = @_;
                   3686:     my $timestamp = '';
                   3687:     my $num_tries = 0;
                   3688:     if ($$record{'version'}) {
                   3689:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3690:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3691:                 $timestamp = $$record{$version.':timestamp'};
                   3692:                 if ($timestamp > $last_reset) {
                   3693:                     $num_tries ++;
                   3694:                 } else {
                   3695:                     last;
                   3696:                 }
                   3697:             }
                   3698:         }
                   3699:     }
                   3700:     return $num_tries;
                   3701: }
                   3702: 
                   3703: # ----------- Determine decrements required in aggregate totals 
                   3704: sub decrement_aggs {
                   3705:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3706:     my %decrement = (
                   3707:                         attempts => 0,
                   3708:                         users => 0,
                   3709:                         correct => 0
                   3710:                     );
                   3711:     $decrement{'attempts'} = $aggtries;
                   3712:     if ($solvedstatus =~ /^correct/) {
                   3713:         $decrement{'correct'} = 1;
                   3714:     }
                   3715:     if ($aggtries == $totaltries) {
                   3716:         $decrement{'users'} = 1;
                   3717:     }
1.524     raeburn  3718:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3719:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3720:     }
                   3721:     return;
                   3722: }
                   3723: 
                   3724: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3725: sub get_last_resets {
1.270     albertel 3726:     my ($symb,$courseid,$partids) =@_;
                   3727:     my %last_resets;
1.269     raeburn  3728:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3729:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3730:     my @keys;
                   3731:     foreach my $part (@{$partids}) {
                   3732: 	push(@keys,"$symb\0$part\0resettime");
                   3733:     }
                   3734:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3735: 				     $cdom,$cname);
                   3736:     foreach my $part (@{$partids}) {
                   3737: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3738:     }
1.270     albertel 3739:     return %last_resets;
1.269     raeburn  3740: }
                   3741: 
1.251     banghart 3742: # ----------- Handles creating versions for portfolio files as answers
                   3743: sub version_portfiles {
1.343     banghart 3744:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3745:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3746:     my @returned_keys;
1.255     banghart 3747:     my $parts = join('|', @$parts_graded);
1.277     albertel 3748:     foreach my $key (keys(%$record)) {
1.259     banghart 3749:         my $new_portfiles;
1.263     banghart 3750:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3751:             my @versioned_portfiles;
1.367     albertel 3752:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3753:             if (@portfiles) {
                   3754:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3755:                                                       \@versioned_portfiles);
1.252     banghart 3756:             }
1.343     banghart 3757:             $$record{$key} = join(',',@versioned_portfiles);
                   3758:             push(@returned_keys,$key);
1.251     banghart 3759:         }
                   3760:     } 
1.343     banghart 3761:     return (@returned_keys);   
1.305     banghart 3762: }
                   3763: 
1.44      ng       3764: #--------------------------------------------------------------------------------------
                   3765: #
                   3766: #-------------------------- Next few routines handles grading by section or whole class
                   3767: #
                   3768: #--- Javascript to handle grading by section or whole class
1.42      ng       3769: sub viewgrades_js {
                   3770:     my ($request) = shift;
                   3771: 
1.539     riegler  3772:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3773:     &js_escape(\$alertmsg);
1.597     wenzelju 3774:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3775:    function writePoint(partid,weight,point) {
1.125     ng       3776: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3777: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3778: 	if (point == "textval") {
1.125     ng       3779: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3780: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3781: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3782: 		var resetbox = false;
                   3783: 		for (var i=0; i<radioButton.length; i++) {
                   3784: 		    if (radioButton[i].checked) {
                   3785: 			textbox.value = i;
                   3786: 			resetbox = true;
                   3787: 		    }
                   3788: 		}
                   3789: 		if (!resetbox) {
                   3790: 		    textbox.value = "";
                   3791: 		}
                   3792: 		return;
                   3793: 	    }
1.109     matthew  3794: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3795: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3796: 				   ") greater than the weight for the part. Accept?");
                   3797: 		if (resp == false) {
                   3798: 		    textbox.value = "";
                   3799: 		    return;
                   3800: 		}
                   3801: 	    }
1.42      ng       3802: 	    for (var i=0; i<radioButton.length; i++) {
                   3803: 		radioButton[i].checked=false;
1.109     matthew  3804: 		if (parseFloat(point) == i) {
1.42      ng       3805: 		    radioButton[i].checked=true;
                   3806: 		}
                   3807: 	    }
1.41      ng       3808: 
1.42      ng       3809: 	} else {
1.125     ng       3810: 	    textbox.value = parseFloat(point);
1.42      ng       3811: 	}
1.41      ng       3812: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3813: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3814: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3815: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3816: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3817: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3818: 	    if (saveval != "correct") {
                   3819: 		scorename.value = point;
1.43      ng       3820: 		if (selname[0].selected != true) {
                   3821: 		    selname[0].selected = true;
                   3822: 		}
1.42      ng       3823: 	    }
                   3824: 	}
1.125     ng       3825: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3826:     }
                   3827: 
                   3828:     function writeRadText(partid,weight) {
1.125     ng       3829: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3830: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3831:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3832: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3833: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3834: 	    for (var i=0; i<radioButton.length; i++) {
                   3835: 		radioButton[i].checked=false;
                   3836: 
                   3837: 	    }
                   3838: 	    textbox.value = "";
                   3839: 
                   3840: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3841: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3842: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3843: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3844: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3845: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3846: 		if ((saveval != "correct") || override) {
1.42      ng       3847: 		    scorename.value = "";
1.125     ng       3848: 		    if (selval[1].selected) {
                   3849: 			selname[1].selected = true;
                   3850: 		    } else {
                   3851: 			selname[2].selected = true;
                   3852: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3853: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3854: 		    }
1.42      ng       3855: 		}
                   3856: 	    }
1.43      ng       3857: 	} else {
                   3858: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3859: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3860: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3861: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3862: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3863: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3864: 		if ((saveval != "correct") || override) {
1.125     ng       3865: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3866: 		    selname[0].selected = true;
                   3867: 		}
                   3868: 	    }
                   3869: 	}	    
1.42      ng       3870:     }
                   3871: 
                   3872:     function changeSelect(partid,user) {
1.125     ng       3873: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3874: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3875: 	var point  = textbox.value;
1.125     ng       3876: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3877: 
1.109     matthew  3878: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3879: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3880: 	    textbox.value = "";
                   3881: 	    return;
                   3882: 	}
1.109     matthew  3883: 	if (parseFloat(point) > parseFloat(weight)) {
                   3884: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3885: 			       ") greater than the weight of the part. Accept?");
                   3886: 	    if (resp == false) {
                   3887: 		textbox.value = "";
                   3888: 		return;
                   3889: 	    }
                   3890: 	}
1.42      ng       3891: 	selval[0].selected = true;
                   3892:     }
                   3893: 
                   3894:     function changeOneScore(partid,user) {
1.125     ng       3895: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3896: 	if (selval[1].selected || selval[2].selected) {
                   3897: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3898: 	    if (selval[2].selected) {
                   3899: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3900: 	    }
1.269     raeburn  3901:         }
1.42      ng       3902:     }
                   3903: 
                   3904:     function resetEntry(numpart) {
                   3905: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3906: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3907: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3908: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3909: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3910: 	    for (var i=0; i<radioButton.length; i++) {
                   3911: 		radioButton[i].checked=false;
                   3912: 
                   3913: 	    }
                   3914: 	    textbox.value = "";
                   3915: 	    selval[0].selected = true;
                   3916: 
                   3917: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3918: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3919: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3920: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3921: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3922: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3923: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3924: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3925: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3926: 		if (saveselval == "excused") {
1.43      ng       3927: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3928: 		} else {
1.43      ng       3929: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3930: 		}
                   3931: 	    }
1.41      ng       3932: 	}
1.42      ng       3933:     }
                   3934: 
1.41      ng       3935: VIEWJAVASCRIPT
1.42      ng       3936: }
                   3937: 
1.44      ng       3938: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3939: sub viewgrades {
1.608     www      3940:     my ($request,$symb) = @_;
1.745     raeburn  3941:     my ($is_tool,$toolsymb);
                   3942:     if ($symb =~ /ext\.tool$/) {
                   3943:         $is_tool = 1;
                   3944:         $toolsymb = $symb;
                   3945:     }
1.42      ng       3946:     &viewgrades_js($request);
1.41      ng       3947: 
1.168     albertel 3948:     #need to make sure we have the correct data for later EXT calls, 
                   3949:     #thus invalidate the cache
                   3950:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3951:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3952:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3953:     &Apache::lonnet::clear_EXT_cache_status();
                   3954: 
1.398     albertel 3955:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3956: 
                   3957:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3958:     $result.=&jscriptNform($symb);
1.41      ng       3959: 
1.44      ng       3960:     #beginning of class grading form
1.442     banghart 3961:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3962:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3963: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3964: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3965: 	&build_section_inputs().
1.442     banghart 3966: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3967: 
1.738     raeburn  3968:     #retrieve selected groups
                   3969:     my (@groups,$group_display);
                   3970:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3971:     if (grep(/^all$/,@groups)) {
                   3972:         @groups = ('all');
                   3973:     } elsif (grep(/^none$/,@groups)) {
                   3974:         @groups = ('none');
                   3975:     } elsif (@groups > 0) {
                   3976:         $group_display = join(', ',@groups);
                   3977:     }
                   3978: 
                   3979:     my ($common_header,$specific_header,@sections,$section_display);
                   3980:     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3981:     if (grep(/^all$/,@sections)) {
                   3982:         @sections = ('all');
                   3983:         if ($group_display) {
                   3984:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3985:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3986:         } elsif (grep(/^none$/,@groups)) {
                   3987:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3988:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3989:         } else {
                   3990: 	    $common_header = &mt('Assign Common Grade to Class');
                   3991:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3992:         }
                   3993:     } elsif (grep(/^none$/,@sections)) {
                   3994:         @sections = ('none');
                   3995:         if ($group_display) {
                   3996:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3997:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3998:         } elsif (grep(/^none$/,@groups)) {
                   3999:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4000:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4001:         } else {
                   4002:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4003: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4004:         }
                   4005:     } else {
                   4006:         $section_display = join (", ",@sections);
                   4007:         if ($group_display) {
                   4008:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4009:                                  $section_display,$group_display);
                   4010:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4011:                                    $section_display,$group_display);
                   4012:         } elsif (grep(/^none$/,@groups)) {
                   4013:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4014:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4015:         } else {
                   4016:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4017: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4018:         }
                   4019:     }
                   4020:     my %submit_types = &substatus_options();
                   4021:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4022: 
                   4023:     if ($env{'form.submitonly'} eq 'all') {
                   4024:         $result.= '<h3>'.$common_header.'</h3>';
                   4025:     } else {
1.745     raeburn  4026:         my $text;
                   4027:         if ($is_tool) {
                   4028:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4029:         } else {
                   4030:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4031:         }
                   4032:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 4033:     }
1.738     raeburn  4034:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4035:     #radio buttons/text box for assigning points for a section or class.
                   4036:     #handles different parts of a problem
1.582     raeburn  4037:     my $res_error;
                   4038:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4039:     if ($res_error) {
                   4040:         return &navmap_errormsg();
                   4041:     }
1.42      ng       4042:     my %weight = ();
                   4043:     my $ctsparts = 0;
1.45      ng       4044:     my %seen = ();
1.745     raeburn  4045:     my @part_response_id;
                   4046:     if ($is_tool) {
                   4047:         @part_response_id = ([0,'']);
                   4048:     } else {
                   4049:         @part_response_id = &flatten_responseType($responseType);
                   4050:     }
1.375     albertel 4051:     foreach my $part_response_id (@part_response_id) {
                   4052:     	my ($partid,$respid) = @{ $part_response_id };
                   4053: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4054: 	next if $seen{$partid};
                   4055: 	$seen{$partid}++;
1.42      ng       4056: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4057: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4058: 
1.324     albertel 4059: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4060: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4061: 	my $ctr = 0;
1.42      ng       4062: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4063: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4064: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4065: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4066: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4067: 	    $ctr++;
                   4068: 	}
1.485     albertel 4069: 	$radio.='</tr></table>';
                   4070: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4071: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4072: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4073: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   4074:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4075:             '<select name="SELVAL_'.$partid.'" '.
                   4076:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   4077:                 $weight{$partid}.')"> '.
1.401     albertel 4078: 	    '<option selected="selected"> </option>'.
1.485     albertel 4079: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4080: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4081: 	    '</select></td>'.
                   4082:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4083: 	$line.='<input type="hidden" name="partid_'.
                   4084: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4085: 	$line.='<input type="hidden" name="weight_'.
                   4086: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4087: 
                   4088: 	$result.=
                   4089: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4090: 	    '<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 4091: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4092: 	$ctsparts++;
1.41      ng       4093:     }
1.474     albertel 4094:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4095: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4096:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4097: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4098: 
1.44      ng       4099:     #table listing all the students in a section/class
                   4100:     #header of table
1.738     raeburn  4101:     if ($env{'form.submitonly'} eq 'all') {
                   4102:         $result.= '<h3>'.$specific_header.'</h3>';
                   4103:     } else {
1.745     raeburn  4104:         my $text;
                   4105:         if ($is_tool) {
                   4106:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4107:         } else {
                   4108:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4109:         }
                   4110:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  4111:     }
                   4112:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4113: 	      &Apache::loncommon::start_data_table_header_row().
                   4114: 	      '<th>'.&mt('No.').'</th>'.
                   4115: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4116:     my $partserror;
                   4117:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4118:     if ($partserror) {
                   4119:         return &navmap_errormsg();
                   4120:     }
1.324     albertel 4121:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4122:     my @partids = ();
1.41      ng       4123:     foreach my $part (@parts) {
1.745     raeburn  4124: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  4125:         my $narrowtext = &mt('Tries');
                   4126: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  4127: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 4128: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4129:         push(@partids,$partid);
1.628     www      4130: #
                   4131: # FIXME: Looks like $display looks at English text
                   4132: #
1.324     albertel 4133: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4134: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4135: 	    $result.='<th>'.
1.697     bisitz   4136: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   4137: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4138: 	    next;
1.485     albertel 4139: 	    
1.207     albertel 4140: 	} else {
1.485     albertel 4141: 	    if ($display =~ /Problem Status/) {
                   4142: 		my $grade_status_mt = &mt('Grade Status');
                   4143: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4144: 	    }
                   4145: 	    my $part_mt = &mt('Part:');
                   4146: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4147: 	}
1.485     albertel 4148: 
1.474     albertel 4149: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4150:     }
1.474     albertel 4151:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4152: 
1.270     albertel 4153:     my %last_resets = 
                   4154: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4155: 
1.41      ng       4156:     #get info for each student
1.44      ng       4157:     #list all the students - with points and grade status
1.738     raeburn  4158:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4159:     my $ctr = 0;
1.294     albertel 4160:     foreach (sort 
                   4161: 	     {
                   4162: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4163: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4164: 		 }
                   4165: 		 return $a cmp $b;
                   4166: 	     } (keys(%$fullname))) {
1.324     albertel 4167: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  4168: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4169:     }
1.474     albertel 4170:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4171:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 4172:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   4173: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4174:     if ($ctr == 0) {
1.442     banghart 4175:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4176:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4177:                 '<span class="LC_warning">';
                   4178:         if ($env{'form.submitonly'} eq 'all') {
                   4179:             if (grep(/^all$/,@sections)) {
                   4180:                 if (grep(/^all$/,@groups)) {
                   4181:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4182:                                    $stu_status);
                   4183:                 } elsif (grep(/^none$/,@groups)) {
                   4184:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4185:                                    $stu_status); 
                   4186:                 } else {
                   4187:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4188:                                    $group_display,$stu_status);
                   4189:                 }
                   4190:             } elsif (grep(/^none$/,@sections)) {
                   4191:                 if (grep(/^all$/,@groups)) {
                   4192:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4193:                                    $stu_status);
                   4194:                 } elsif (grep(/^none$/,@groups)) {
                   4195:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4196:                                    $stu_status);
                   4197:                 } else {
                   4198:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4199:                                    $group_display,$stu_status);
                   4200:                 }
                   4201:             } else {
                   4202:                 if (grep(/^all$/,@groups)) {
                   4203:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4204:                                    $section_display,$stu_status);
                   4205:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4206:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4207:                                    $section_display,$stu_status);
                   4208:                 } else {
                   4209:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4210:                                    $section_display,$group_display,$stu_status);
                   4211:                 }
                   4212:             }
                   4213:         } else {
                   4214:             if (grep(/^all$/,@sections)) {
                   4215:                 if (grep(/^all$/,@groups)) {
                   4216:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4217:                                    $stu_status,$submission_status);
                   4218:                 } elsif (grep(/^none$/,@groups)) {
                   4219:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4220:                                    $stu_status,$submission_status);
                   4221:                 } else {
                   4222:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4223:                                    $group_display,$stu_status,$submission_status);
                   4224:                 }
                   4225:             } elsif (grep(/^none$/,@sections)) {
                   4226:                 if (grep(/^all$/,@groups)) {
                   4227:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4228:                                    $stu_status,$submission_status);
                   4229:                 } elsif (grep(/^none$/,@groups)) {
                   4230:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4231:                                    $stu_status,$submission_status);
                   4232:                 } else {
                   4233:                     $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.',
                   4234:                                    $group_display,$stu_status,$submission_status);
                   4235:                 }
                   4236:             } else {
                   4237:                 if (grep(/^all$/,@groups)) {
                   4238: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4239: 	                           $section_display,$stu_status,$submission_status);
                   4240:                 } elsif (grep(/^none$/,@groups)) {
                   4241:                     $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.',
                   4242:                                    $section_display,$stu_status,$submission_status);
                   4243:                 } else {
                   4244:                     $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.',
                   4245:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4246:                 }
                   4247:             }
                   4248:         }
                   4249: 	$result .= '</span><br />';
1.96      albertel 4250:     }
1.41      ng       4251:     return $result;
                   4252: }
                   4253: 
1.738     raeburn  4254: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4255: sub viewstudentgrade {
1.745     raeburn  4256:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4257:     my ($uname,$udom) = split(/:/,$student);
                   4258:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4259:     my $submitonly = $env{'form.submitonly'};
                   4260:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4261:         my %partstatus = ();
                   4262:         if (ref($parts) eq 'ARRAY') {
                   4263:             foreach my $apart (@{$parts}) {
                   4264:                 my ($part,$type) = &split_part_type($apart);
                   4265:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4266:                 $status = 'nothing' if ($status eq '');
                   4267:                 $partstatus{$part}      = $status;
                   4268:                 my $subkey = "resource.$part.submitted_by";
                   4269:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4270:             }
                   4271:             my $submitted = 0;
                   4272:             my $graded = 0;
                   4273:             my $incorrect = 0;
                   4274:             foreach my $key (keys(%partstatus)) {
                   4275:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4276:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4277:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4278: 
                   4279:                 my $partid = (split(/\./,$key))[1];
                   4280:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4281:                     $submitted = 0;
                   4282:                 }
                   4283:             }
                   4284:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4285:                                        $submitonly eq 'incorrect' ||
                   4286:                                        $submitonly eq 'graded'));
                   4287:             return if (!$graded && ($submitonly eq 'graded'));
                   4288:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4289:         }
                   4290:     }
                   4291:     if ($submitonly eq 'queued') {
                   4292:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4293:         my %queue_status =
                   4294:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4295:                                                     $udom,$uname);
                   4296:         return if (!defined($queue_status{'gradingqueue'}));
                   4297:     }
                   4298:     $$ctr++;
                   4299:     my %aggregates = ();
1.474     albertel 4300:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4301: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4302: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4303: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4304: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4305: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4306:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4307:     foreach my $apart (@$parts) {
                   4308: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4309: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4310:         $result.='<td align="center">';
1.269     raeburn  4311:         my ($aggtries,$totaltries);
                   4312:         unless (exists($aggregates{$part})) {
1.270     albertel 4313: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4314: 	    $aggtries = $totaltries;
1.269     raeburn  4315:             if ($$last_resets{$part}) {  
1.270     albertel 4316:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4317: 					   $part);
                   4318:             }
1.269     raeburn  4319:             $result.='<input type="hidden" name="'.
                   4320:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4321:             $result.='<input type="hidden" name="'.
                   4322:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4323:             $aggregates{$part} = 1;
                   4324:         }
1.41      ng       4325: 	if ($type eq 'awarded') {
1.320     albertel 4326: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4327: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4328: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4329: 	    $result.='<input type="text" name="'.
1.89      albertel 4330: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4331:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4332: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4333: 	} elsif ($type eq 'solved') {
                   4334: 	    my ($status,$foo)=split(/_/,$score,2);
                   4335: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4336: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4337: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4338: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4339: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4340:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4341: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4342: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4343: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4344: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4345: 	} else {
                   4346: 	    $result.='<input type="hidden" name="'.
                   4347: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4348: 		    "\n";
1.233     albertel 4349: 	    $result.='<input type="text" name="'.
1.122     ng       4350: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4351: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4352: 	}
                   4353:     }
1.474     albertel 4354:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4355:     return $result;
1.38      ng       4356: }
                   4357: 
1.44      ng       4358: #--- change scores for all the students in a section/class
                   4359: #    record does not get update if unchanged
1.38      ng       4360: sub editgrades {
1.608     www      4361:     my ($request,$symb) = @_;
1.745     raeburn  4362:     my $toolsymb;
                   4363:     if ($symb =~ /ext\.tool$/) {
                   4364:         $toolsymb = $symb;
                   4365:     }
1.41      ng       4366: 
1.433     banghart 4367:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4368:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  4369:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4370: 
1.477     albertel 4371:     my $result= &Apache::loncommon::start_data_table().
                   4372: 	&Apache::loncommon::start_data_table_header_row().
                   4373: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4374: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4375:     my %scoreptr = (
                   4376: 		    'correct'  =>'correct_by_override',
                   4377: 		    'incorrect'=>'incorrect_by_override',
                   4378: 		    'excused'  =>'excused',
                   4379: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4380:                     'credited' =>'credit_attempted',
1.43      ng       4381: 		    'nothing'  => '',
                   4382: 		    );
1.257     albertel 4383:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4384: 
1.44      ng       4385:     my (@partid);
                   4386:     my %weight = ();
1.54      albertel 4387:     my %columns = ();
1.44      ng       4388:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4389: 
1.582     raeburn  4390:     my $partserror;
                   4391:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4392:     if ($partserror) {
                   4393:         return &navmap_errormsg();
                   4394:     }
1.54      albertel 4395:     my $header;
1.257     albertel 4396:     while ($ctr < $env{'form.totalparts'}) {
                   4397: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4398: 	push(@partid,$partid);
1.257     albertel 4399: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4400: 	$ctr++;
1.54      albertel 4401:     }
1.324     albertel 4402:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4403:     my $totcolspan = 0;
1.54      albertel 4404:     foreach my $partid (@partid) {
1.478     albertel 4405: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4406: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4407: 	$columns{$partid}=2;
                   4408: 	foreach my $stores (@parts) {
                   4409: 	    my ($part,$type) = &split_part_type($stores);
                   4410: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4411: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4412: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4413: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4414:             my $narrowtext = &mt('Tries');
                   4415: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4416: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4417: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4418: 	    $columns{$partid}+=2;
                   4419: 	}
1.748     raeburn  4420:         $totcolspan += $columns{$partid};
1.54      albertel 4421:     }
                   4422:     foreach my $partid (@partid) {
1.324     albertel 4423: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4424: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4425: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4426: 	    '</th>';
1.54      albertel 4427: 
1.44      ng       4428:     }
1.477     albertel 4429:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4430: 	&Apache::loncommon::start_data_table_header_row().
                   4431: 	$header.
                   4432: 	&Apache::loncommon::end_data_table_header_row();
                   4433:     my @noupdate;
1.126     ng       4434:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4435:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4436: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4437: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4438: 	my %newrecord;
                   4439: 	my $updateflag = 0;
1.108     albertel 4440: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4441: 	my $canmodify = &canmodify($usec);
                   4442: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4443: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4444: 	if (!$canmodify) {
1.477     albertel 4445: 	    push(@noupdate,
1.748     raeburn  4446: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4447: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4448: 	    next;
                   4449: 	}
1.269     raeburn  4450:         my %aggregate = ();
                   4451:         my $aggregateflag = 0;
1.281     albertel 4452: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4453: 	foreach (@partid) {
1.257     albertel 4454: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4455: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4456: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4457: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4458: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4459: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4460: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4461: 	    my $score;
                   4462: 	    if ($partial eq '') {
1.257     albertel 4463: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4464: 	    } elsif ($partial > 0) {
                   4465: 		$score = 'correct_by_override';
                   4466: 	    } elsif ($partial == 0) {
                   4467: 		$score = 'incorrect_by_override';
                   4468: 	    }
1.257     albertel 4469: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4470: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4471: 
1.292     albertel 4472: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4473: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4474: 	    if ($dropMenu eq 'reset status' &&
                   4475: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4476: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4477: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4478: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4479: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4480: 		$updateflag = 1;
1.269     raeburn  4481:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4482:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4483:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4484:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4485:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4486:                     $aggregateflag = 1;
                   4487:                 }
1.139     albertel 4488: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4489: 		$updateflag = 1;
                   4490: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4491: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4492: 		$rec_update++;
1.125     ng       4493: 	    }
                   4494: 
1.93      albertel 4495: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4496: 		'<td align="center">'.$awarded.
                   4497: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4498: 
1.54      albertel 4499: 
                   4500: 	    my $partid=$_;
                   4501: 	    foreach my $stores (@parts) {
                   4502: 		my ($part,$type) = &split_part_type($stores);
                   4503: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4504: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4505: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4506: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4507: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4508: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4509: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4510: 		    $updateflag=1;
                   4511: 		}
1.93      albertel 4512: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4513: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4514: 	    }
1.44      ng       4515: 	}
1.477     albertel 4516: 	$line.="\n";
1.301     albertel 4517: 
                   4518: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4519: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4520: 
1.44      ng       4521: 	if ($updateflag) {
                   4522: 	    $count++;
1.257     albertel 4523: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4524: 				    $udom,$uname);
1.301     albertel 4525: 
                   4526: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4527: 					      $cnum,$udom,$uname)) {
                   4528: 		# need to figure out if should be in queue.
                   4529: 		my %record =  
                   4530: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4531: 					     $udom,$uname);
                   4532: 		my $all_graded = 1;
                   4533: 		my $none_graded = 1;
                   4534: 		foreach my $part (@parts) {
                   4535: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4536: 			$all_graded = 0;
                   4537: 		    } else {
                   4538: 			$none_graded = 0;
                   4539: 		    }
                   4540: 		}
                   4541: 
                   4542: 		if ($all_graded || $none_graded) {
                   4543: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4544: 							   $symb,$cdom,$cnum,
                   4545: 							   $udom,$uname);
                   4546: 		}
                   4547: 	    }
                   4548: 
1.477     albertel 4549: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4550: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4551: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4552: 	    $updateCtr++;
1.93      albertel 4553: 	} else {
1.477     albertel 4554: 	    push(@noupdate,
                   4555: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4556: 	    $noupdateCtr++;
1.44      ng       4557: 	}
1.269     raeburn  4558:         if ($aggregateflag) {
                   4559:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4560: 				  $cdom,$cnum);
1.269     raeburn  4561:         }
1.93      albertel 4562:     }
1.477     albertel 4563:     if (@noupdate) {
1.748     raeburn  4564:         my $numcols=$totcolspan+2;
1.477     albertel 4565: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4566: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4567: 	    &mt('No Changes Occurred For the Students Below').
                   4568: 	    '</td>'.
1.477     albertel 4569: 	    &Apache::loncommon::end_data_table_row();
                   4570: 	foreach my $line (@noupdate) {
                   4571: 	    $result.=
                   4572: 		&Apache::loncommon::start_data_table_row().
                   4573: 		$line.
                   4574: 		&Apache::loncommon::end_data_table_row();
                   4575: 	}
1.44      ng       4576:     }
1.614     www      4577:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4578:     my $msg = '<p><b>'.
                   4579: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4580: 	    $rec_update,$count).'</b><br />'.
                   4581: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4582: 	'</b></p>';
1.44      ng       4583:     return $title.$msg.$result;
1.5       albertel 4584: }
1.54      albertel 4585: 
                   4586: sub split_part_type {
                   4587:     my ($partstr) = @_;
                   4588:     my ($temp,@allparts)=split(/_/,$partstr);
                   4589:     my $type=pop(@allparts);
1.439     albertel 4590:     my $part=join('_',@allparts);
1.54      albertel 4591:     return ($part,$type);
                   4592: }
                   4593: 
1.44      ng       4594: #------------- end of section for handling grading by section/class ---------
                   4595: #
                   4596: #----------------------------------------------------------------------------
                   4597: 
1.5       albertel 4598: 
1.44      ng       4599: #----------------------------------------------------------------------------
                   4600: #
                   4601: #-------------------------- Next few routines handles grading by csv upload
                   4602: #
                   4603: #--- Javascript to handle csv upload
1.27      albertel 4604: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4605:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4606:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4607:   &js_escape(\$error1);
                   4608:   &js_escape(\$error2);
1.27      albertel 4609:   return(<<ENDPICK);
                   4610:   function verify(vf) {
                   4611:     var foundsomething=0;
                   4612:     var founduname=0;
1.243     albertel 4613:     var foundID=0;
1.743     raeburn  4614:     var foundclicker=0;
1.27      albertel 4615:     for (i=0;i<=vf.nfields.value;i++) {
                   4616:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4617:       if (i==0 && tw!=0) { foundID=1; }
                   4618:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4619:       if (i==2 && tw!=0) { foundclicker=1; }
                   4620:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4621:     }
1.743     raeburn  4622:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4623: 	alert('$error1');
                   4624: 	return;
1.27      albertel 4625:     }
                   4626:     if (foundsomething==0) {
1.246     albertel 4627: 	alert('$error2');
                   4628: 	return;
1.27      albertel 4629:     }
                   4630:     vf.submit();
                   4631:   }
                   4632:   function flip(vf,tf) {
                   4633:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4634:     var i;
                   4635:     for (i=0;i<=vf.nfields.value;i++) {
                   4636:       //can not pick the same destination field for both name and domain
                   4637:       if (((i ==0)||(i ==1)) && 
                   4638:           ((tf==0)||(tf==1)) && 
                   4639:           (i!=tf) &&
                   4640:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4641:         eval('vf.f'+i+'.selectedIndex=0;')
                   4642:       }
                   4643:     }
                   4644:   }
                   4645: ENDPICK
                   4646: }
                   4647: 
                   4648: sub csvupload_javascript_forward_associate {
1.743     raeburn  4649:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4650:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4651:   &js_escape(\$error1);
                   4652:   &js_escape(\$error2);
1.27      albertel 4653:   return(<<ENDPICK);
                   4654:   function verify(vf) {
                   4655:     var foundsomething=0;
                   4656:     var founduname=0;
1.243     albertel 4657:     var foundID=0;
1.743     raeburn  4658:     var foundclicker=0;
1.27      albertel 4659:     for (i=0;i<=vf.nfields.value;i++) {
                   4660:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4661:       if (tw==1) { foundID=1; }
                   4662:       if (tw==2) { founduname=1; }
1.745     raeburn  4663:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4664:       if (tw>4) { foundsomething=1; }
1.27      albertel 4665:     }
1.743     raeburn  4666:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4667: 	alert('$error1');
                   4668: 	return;
1.27      albertel 4669:     }
                   4670:     if (foundsomething==0) {
1.246     albertel 4671: 	alert('$error2');
                   4672: 	return;
1.27      albertel 4673:     }
                   4674:     vf.submit();
                   4675:   }
                   4676:   function flip(vf,tf) {
                   4677:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4678:     var i;
                   4679:     //can not pick the same destination field twice
                   4680:     for (i=0;i<=vf.nfields.value;i++) {
                   4681:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4682:         eval('vf.f'+i+'.selectedIndex=0;')
                   4683:       }
                   4684:     }
                   4685:   }
                   4686: ENDPICK
                   4687: }
                   4688: 
1.26      albertel 4689: sub csvuploadmap_header {
1.324     albertel 4690:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4691:     my $javascript;
1.257     albertel 4692:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4693: 	$javascript=&csvupload_javascript_reverse_associate();
                   4694:     } else {
                   4695: 	$javascript=&csvupload_javascript_forward_associate();
                   4696:     }
1.45      ng       4697: 
1.418     albertel 4698:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4699:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4700:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4701:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4702:     my $reverse=&mt("Reverse Association");
1.41      ng       4703:     $request->print(<<ENDPICK);
1.632     www      4704: <br />
                   4705: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4706: <input type="hidden" name="associate"  value="" />
                   4707: <input type="hidden" name="phase"      value="three" />
                   4708: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4709: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4710: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4711: <input type="hidden" name="upfile_associate" 
1.257     albertel 4712:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4713: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4714: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4715: <hr />
                   4716: ENDPICK
1.597     wenzelju 4717:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4718:     return '';
1.26      albertel 4719: 
                   4720: }
                   4721: 
                   4722: sub csvupload_fields {
1.582     raeburn  4723:     my ($symb,$errorref) = @_;
1.745     raeburn  4724:     my $toolsymb;
                   4725:     if ($symb =~ /ext\.tool$/) {
                   4726:         $toolsymb = $symb;
                   4727:     }
1.582     raeburn  4728:     my (@parts) = &getpartlist($symb,$errorref);
                   4729:     if (ref($errorref)) {
                   4730:         if ($$errorref) {
                   4731:             return;
                   4732:         }
                   4733:     }
                   4734: 
1.556     weissno  4735:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4736: 		['username','Student Username'],
1.743     raeburn  4737: 		['clicker','Clicker ID'],
1.243     albertel 4738: 		['domain','Student Domain']);
1.324     albertel 4739:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4740:     foreach my $part (sort(@parts)) {
                   4741: 	my @datum;
1.745     raeburn  4742: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4743: 	my $name=$part;
1.745     raeburn  4744: 	if (!$display) { $display = $name; }
1.41      ng       4745: 	@datum=($name,$display);
1.244     albertel 4746: 	if ($name=~/^stores_(.*)_awarded/) {
                   4747: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4748: 	}
1.41      ng       4749: 	push(@fields,\@datum);
                   4750:     }
                   4751:     return (@fields);
1.26      albertel 4752: }
                   4753: 
                   4754: sub csvuploadmap_footer {
1.41      ng       4755:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4756:     my $buttontext = &mt('Assign Grades');
1.41      ng       4757:     $request->print(<<ENDPICK);
1.26      albertel 4758: </table>
                   4759: <input type="hidden" name="nfields" value="$i" />
                   4760: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4761: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4762: </form>
                   4763: ENDPICK
                   4764: }
                   4765: 
1.283     albertel 4766: sub checkforfile_js {
1.638     www      4767:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4768:     &js_escape(\$alertmsg);
1.597     wenzelju 4769:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4770:     function checkUpload(formname) {
                   4771: 	if (formname.upfile.value == "") {
1.539     riegler  4772: 	    alert("$alertmsg");
1.86      ng       4773: 	    return false;
                   4774: 	}
                   4775: 	formname.submit();
                   4776:     }
                   4777: CSVFORMJS
1.283     albertel 4778:     return $result;
                   4779: }
                   4780: 
                   4781: sub upcsvScores_form {
1.608     www      4782:     my ($request,$symb) = @_;
1.283     albertel 4783:     if (!$symb) {return '';}
                   4784:     my $result=&checkforfile_js();
1.632     www      4785:     $result.=&Apache::loncommon::start_data_table().
                   4786:              &Apache::loncommon::start_data_table_header_row().
                   4787:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4788:              &Apache::loncommon::end_data_table_header_row().
                   4789:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4790:     my $upload=&mt("Upload Scores");
1.86      ng       4791:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4792:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4793:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4794:     $result.=<<ENDUPFORM;
1.106     albertel 4795: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4796: <input type="hidden" name="symb" value="$symb" />
                   4797: <input type="hidden" name="command" value="csvuploadmap" />
                   4798: $upfile_select
1.589     bisitz   4799: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4800: </form>
                   4801: ENDUPFORM
1.370     www      4802:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4803:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4804:              '</td>'.
                   4805:             &Apache::loncommon::end_data_table_row().
                   4806:             &Apache::loncommon::end_data_table();
1.86      ng       4807:     return $result;
                   4808: }
                   4809: 
                   4810: 
1.26      albertel 4811: sub csvuploadmap {
1.768     raeburn  4812:     my ($request,$symb) = @_;
1.41      ng       4813:     if (!$symb) {return '';}
1.72      ng       4814: 
1.41      ng       4815:     my $datatoken;
1.257     albertel 4816:     if (!$env{'form.datatoken'}) {
1.41      ng       4817: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4818:     } else {
1.742     raeburn  4819: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4820:         if ($datatoken ne '') {
                   4821: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4822:         }
1.26      albertel 4823:     }
1.41      ng       4824:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4825:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4826:     my ($i,$keyfields);
                   4827:     if (@records) {
1.582     raeburn  4828:         my $fieldserror;
                   4829: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4830:         if ($fieldserror) {
                   4831:             $request->print(&navmap_errormsg());
                   4832:             return;
                   4833:         }
1.257     albertel 4834: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4835: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4836: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4837: 							  \@fields);
                   4838: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4839: 	    chop($keyfields);
                   4840: 	} else {
                   4841: 	    unshift(@fields,['none','']);
                   4842: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4843: 							    \@fields);
1.311     banghart 4844:             foreach my $rec (@records) {
                   4845:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4846:                 if (%temp) {
                   4847:                     $keyfields=join(',',sort(keys(%temp)));
                   4848:                     last;
                   4849:                 }
                   4850:             }
1.41      ng       4851: 	}
                   4852:     }
                   4853:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4854: 
1.41      ng       4855:     return '';
1.27      albertel 4856: }
                   4857: 
1.246     albertel 4858: sub csvuploadoptions {
1.608     www      4859:     my ($request,$symb)= @_;
1.632     www      4860:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4861:     $request->print(<<ENDPICK);
                   4862: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4863: <input type="hidden" name="command"    value="csvuploadassign" />
                   4864: <p>
                   4865: <label>
                   4866:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4867:    $overwrite
1.246     albertel 4868: </label>
                   4869: </p>
                   4870: ENDPICK
                   4871:     my %fields=&get_fields();
                   4872:     if (!defined($fields{'domain'})) {
1.257     albertel 4873: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4874: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4875:     }
1.257     albertel 4876:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4877: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4878: 	my $cleankey=$1;
                   4879: 	if ($cleankey eq 'command') { next; }
                   4880: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4881: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4882:     }
                   4883:     # FIXME do a check for any duplicated user ids...
                   4884:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4885:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4886: <hr /></form>'."\n");
1.246     albertel 4887:     return '';
                   4888: }
                   4889: 
                   4890: sub get_fields {
                   4891:     my %fields;
1.257     albertel 4892:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4893:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4894: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4895: 	    if ($env{'form.f'.$i} ne 'none') {
                   4896: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4897: 	    }
                   4898: 	} else {
1.257     albertel 4899: 	    if ($env{'form.f'.$i} ne 'none') {
                   4900: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4901: 	    }
                   4902: 	}
1.27      albertel 4903:     }
1.246     albertel 4904:     return %fields;
                   4905: }
                   4906: 
                   4907: sub csvuploadassign {
1.766     raeburn  4908:     my ($request,$symb) = @_;
1.246     albertel 4909:     if (!$symb) {return '';}
1.345     bowersj2 4910:     my $error_msg = '';
1.742     raeburn  4911:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4912:     if ($datatoken ne '') { 
                   4913:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4914:     }
1.246     albertel 4915:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4916:     my %fields=&get_fields();
1.257     albertel 4917:     my $courseid=$env{'request.course.id'};
1.97      albertel 4918:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4919:     my @notallowed;
1.41      ng       4920:     my @skipped;
1.657     raeburn  4921:     my @warnings;
1.41      ng       4922:     my $countdone=0;
                   4923:     foreach my $grade (@gradedata) {
                   4924: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4925: 	my $domain;
                   4926: 	if ($entries{$fields{'domain'}}) {
                   4927: 	    $domain=$entries{$fields{'domain'}};
                   4928: 	} else {
1.257     albertel 4929: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4930: 	}
1.243     albertel 4931: 	$domain=~s/\s//g;
1.41      ng       4932: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4933: 	$username=~s/\s//g;
1.243     albertel 4934: 	if (!$username) {
                   4935: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4936: 	    $id=~s/\s//g;
1.737     raeburn  4937:             if ($id ne '') {
                   4938: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4939: 	        $username=$ids{$id};
                   4940:             } else {
                   4941:                 if ($entries{$fields{'clicker'}}) {
                   4942:                     my $clicker = $entries{$fields{'clicker'}};
                   4943:                     $clicker=~s/\s//g;
                   4944:                     if ($clicker ne '') {
                   4945:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4946:                         if ($clickers{$clicker} ne '') {  
                   4947:                             my $match = 0;
                   4948:                             my @inclass;
                   4949:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4950:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4951:                                     $username = $poss;
                   4952:                                     push(@inclass,$poss);
                   4953:                                     $match ++;
                   4954:                                     
                   4955:                                 }
                   4956:                             }
                   4957:                             if ($match > 1) {
                   4958:                                 undef($username); 
                   4959:                                 $request->print('<p class="LC_warning">'.
                   4960:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   4961:                                                 $clicker,join(', ',@inclass)).'</p>');
                   4962:                             }
                   4963:                         }
                   4964:                     }
                   4965:                 }
                   4966:             }
1.243     albertel 4967: 	}
1.41      ng       4968: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4969: 	    my $id=$entries{$fields{'ID'}};
                   4970: 	    $id=~s/\s//g;
1.737     raeburn  4971:             my $clicker = $entries{$fields{'clicker'}};
                   4972:             $clicker=~s/\s//g;
                   4973:             if ($clicker) {
                   4974:                 push(@skipped,"$clicker:$domain");
                   4975: 	    } elsif ($id) {
1.247     albertel 4976: 		push(@skipped,"$id:$domain");
                   4977: 	    } else {
                   4978: 		push(@skipped,"$username:$domain");
                   4979: 	    }
1.41      ng       4980: 	    next;
                   4981: 	}
1.108     albertel 4982: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4983: 	if (!&canmodify($usec)) {
                   4984: 	    push(@notallowed,"$username:$domain");
                   4985: 	    next;
                   4986: 	}
1.244     albertel 4987: 	my %points;
1.41      ng       4988: 	my %grades;
                   4989: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4990: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4991: 		$dest eq 'domain') { next; }
                   4992: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4993: 	    if ($dest=~/stores_(.*)_points/) {
                   4994: 		my $part=$1;
                   4995: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4996: 					      $symb,$domain,$username);
1.345     bowersj2 4997:                 if ($wgt) {
                   4998:                     $entries{$fields{$dest}}=~s/\s//g;
                   4999:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5000:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5001:                                           : 'correct_by_override';
1.638     www      5002:                     if ($pcr>1) {
1.657     raeburn  5003:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      5004:                     }
1.345     bowersj2 5005:                     $grades{"resource.$part.awarded"}=$pcr;
                   5006:                     $grades{"resource.$part.solved"}=$award;
                   5007:                     $points{$part}=1;
                   5008:                 } else {
                   5009:                     $error_msg = "<br />" .
                   5010:                         &mt("Some point values were assigned"
                   5011:                             ." for problems with a weight "
                   5012:                             ."of zero. These values were "
                   5013:                             ."ignored.");
                   5014:                 }
1.244     albertel 5015: 	    } else {
                   5016: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5017: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5018: 		my $store_key=$dest;
                   5019: 		$store_key=~s/^stores/resource/;
                   5020: 		$store_key=~s/_/\./g;
                   5021: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5022: 	    }
1.41      ng       5023: 	}
1.766     raeburn  5024: 	if (! %grades) {
1.508     www      5025:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5026:         } else {
                   5027: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5028: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5029: 					   $env{'request.course.id'},
                   5030: 					   $domain,$username);
1.508     www      5031: 	   if ($result eq 'ok') {
1.627     www      5032: # Successfully stored
1.508     www      5033: 	      $request->print('.');
1.627     www      5034: # Remove from grading queue
                   5035:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5036:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5037:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5038:                                              $domain,$username);
                   5039:               $countdone++;
                   5040:            } else {
1.508     www      5041: 	      $request->print("<p><span class=\"LC_error\">".
                   5042:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5043:                                   "$username:$domain",$result)."</span></p>");
                   5044: 	   }
                   5045: 	   $request->rflush();
                   5046:         }
1.41      ng       5047:     }
1.570     www      5048:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  5049:     if (@warnings) {
                   5050:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5051:         $request->print(join(', ',@warnings));
                   5052:     }
1.41      ng       5053:     if (@skipped) {
1.571     www      5054: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5055:         $request->print(join(', ',@skipped));
1.106     albertel 5056:     }
                   5057:     if (@notallowed) {
1.571     www      5058: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5059: 	$request->print(join(', ',@notallowed));
1.41      ng       5060:     }
1.106     albertel 5061:     $request->print("<br />\n");
1.345     bowersj2 5062:     return $error_msg;
1.26      albertel 5063: }
1.44      ng       5064: #------------- end of section for handling csv file upload ---------
                   5065: #
                   5066: #-------------------------------------------------------------------
                   5067: #
1.122     ng       5068: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5069: #
                   5070: #--- Select a page/sequence and a student to grade
1.68      ng       5071: sub pickStudentPage {
1.608     www      5072:     my ($request,$symb) = @_;
1.68      ng       5073: 
1.539     riegler  5074:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  5075:     &js_escape(\$alertmsg);
1.597     wenzelju 5076:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5077: 
                   5078: function checkPickOne(formname) {
1.76      ng       5079:     if (radioSelection(formname.student) == null) {
1.539     riegler  5080: 	alert("$alertmsg");
1.68      ng       5081: 	return;
                   5082:     }
1.125     ng       5083:     ptr = pullDownSelection(formname.selectpage);
                   5084:     formname.page.value = formname["page"+ptr].value;
                   5085:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5086:     formname.submit();
                   5087: }
                   5088: 
                   5089: LISTJAVASCRIPT
1.118     ng       5090:     &commonJSfunctions($request);
1.608     www      5091: 
1.257     albertel 5092:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5093:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5094:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  5095:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5096: 
1.398     albertel 5097:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5098: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5099: 
1.80      ng       5100:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5101:     my $map_error;
                   5102:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5103:     if ($map_error) {
                   5104:         $request->print(&navmap_errormsg());
                   5105:         return; 
                   5106:     }
1.137     albertel 5107:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5108: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5109: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   5110: 
                   5111:     # Collection of hidden fields
1.70      ng       5112:     my $ctr=0;
1.68      ng       5113:     foreach (@$titles) {
1.700     bisitz   5114:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5115:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5116:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5117:         $ctr++;
1.68      ng       5118:     }
1.700     bisitz   5119:     $result.='<input type="hidden" name="page" />'."\n".
                   5120:         '<input type="hidden" name="title" />'."\n";
                   5121: 
                   5122:     $result.=&build_section_inputs();
                   5123:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5124:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   5125: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   5126: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 5127: 
1.700     bisitz   5128:     # Show grading options
                   5129:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5130:     my $select = '<select name="selectpage">'."\n";
1.70      ng       5131:     $ctr=0;
                   5132:     foreach (@$titles) {
                   5133: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   5134: 	$select.='<option value="'.$ctr.'"'.
                   5135: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5136: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       5137: 	$ctr++;
                   5138:     }
1.700     bisitz   5139:     $select.= '</select>';
1.68      ng       5140: 
1.700     bisitz   5141:     $result.=
                   5142:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5143:        .$select
                   5144:        .&Apache::lonhtmlcommon::row_closure();
                   5145: 
                   5146:     $result.=
                   5147:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5148:        .'<label><input type="radio" name="vProb" value="no"'
                   5149:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5150:        .'<label><input type="radio" name="vProb" value="yes" />'
                   5151:            .&mt('yes').'</label>'."\n"
                   5152:        .&Apache::lonhtmlcommon::row_closure();
                   5153: 
                   5154:     $result.=
                   5155:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5156:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5157:            .&mt('none').' </label>'."\n"
                   5158:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5159:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5160:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5161:            .&mt('all submissions with details').' </label>'
                   5162:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 5163:     
1.700     bisitz   5164:     $result.=
                   5165:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5166:        .'<input type="text" name="CODE" value="" />'
                   5167:        .&Apache::lonhtmlcommon::row_closure(1)
                   5168:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5169: 
1.700     bisitz   5170:     # Show list of students to select for grading
                   5171:     $result.='<br /><input type="button" '.
1.589     bisitz   5172:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5173: 
1.68      ng       5174:     $request->print($result);
                   5175: 
1.485     albertel 5176:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5177: 	&Apache::loncommon::start_data_table().
                   5178: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5179: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5180: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5181: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5182: 	'<th>'.&nameUserString('header').'</th>'.
                   5183: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5184:  
1.761     raeburn  5185:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5186:     my $ptr = 1;
1.294     albertel 5187:     foreach my $student (sort 
                   5188: 			 {
                   5189: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5190: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5191: 			     }
                   5192: 			     return $a cmp $b;
                   5193: 			 } (keys(%$fullname))) {
1.68      ng       5194: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5195: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5196:                                   : '</td>');
1.126     ng       5197: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5198: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5199: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5200: 	$studentTable.=
                   5201: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5202:                          : '');
1.68      ng       5203: 	$ptr++;
                   5204:     }
1.484     albertel 5205:     if ($ptr%2 == 0) {
                   5206: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5207: 	    &Apache::loncommon::end_data_table_row();
                   5208:     }
                   5209:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5210:     $studentTable.='<input type="button" '.
1.589     bisitz   5211:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5212: 
                   5213:     $request->print($studentTable);
                   5214: 
                   5215:     return '';
                   5216: }
                   5217: 
                   5218: sub getSymbMap {
1.582     raeburn  5219:     my ($map_error) = @_;
1.132     bowersj2 5220:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5221:     unless (ref($navmap)) {
                   5222:         if (ref($map_error)) {
                   5223:             $$map_error = 'navmap';
                   5224:         }
                   5225:         return;
                   5226:     }
1.68      ng       5227:     my %symbx = ();
                   5228:     my @titles = ();
1.117     bowersj2 5229:     my $minder = 0;
                   5230: 
                   5231:     # Gather every sequence that has problems.
1.240     albertel 5232:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5233: 					       1,0,1);
1.117     bowersj2 5234:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5235: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5236: 	    my $title = $minder.'.'.
                   5237: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5238: 	    push(@titles, $title); # minder in case two titles are identical
                   5239: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5240: 	    $minder++;
1.241     albertel 5241: 	}
1.68      ng       5242:     }
                   5243:     return \@titles,\%symbx;
                   5244: }
                   5245: 
1.72      ng       5246: #
                   5247: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5248: sub displayPage {
1.608     www      5249:     my ($request,$symb) = @_;
1.257     albertel 5250:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5251:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5252:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5253:     my $pageTitle = $env{'form.page'};
1.103     albertel 5254:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5255:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5256:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5257: 
                   5258:     #need to make sure we have the correct data for later EXT calls, 
                   5259:     #thus invalidate the cache
                   5260:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5261:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5262:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5263:     &Apache::lonnet::clear_EXT_cache_status();
                   5264: 
1.103     albertel 5265:     if (!&canview($usec)) {
1.712     bisitz   5266:         $request->print(
                   5267:             '<span class="LC_warning">'.
                   5268:             &mt('Unable to view requested student. ([_1])',
                   5269:                     $env{'form.student'}).
                   5270:             '</span>');
                   5271:         return;
1.103     albertel 5272:     }
1.398     albertel 5273:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5274:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5275: 	'</h3>'."\n";
1.500     albertel 5276:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5277:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5278: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5279:     } else {
                   5280: 	delete($env{'form.CODE'});
                   5281:     }
1.71      ng       5282:     &sub_page_js($request);
                   5283:     $request->print($result);
                   5284: 
1.132     bowersj2 5285:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5286:     unless (ref($navmap)) {
                   5287:         $request->print(&navmap_errormsg());
                   5288:         return;
                   5289:     }
1.257     albertel 5290:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5291:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5292:     if (!$map) {
1.485     albertel 5293: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5294: 	return; 
                   5295:     }
1.68      ng       5296:     my $iterator = $navmap->getIterator($map->map_start(),
                   5297: 					$map->map_finish());
                   5298: 
1.71      ng       5299:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5300: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5301: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5302: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5303: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5304: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5305: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5306: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5307: 
1.382     albertel 5308:     if (defined($env{'form.CODE'})) {
                   5309: 	$studentTable.=
                   5310: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5311:     }
1.381     albertel 5312:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5313: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5314: 
1.594     bisitz   5315:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5316:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5317:         '</span>'."\n".
1.484     albertel 5318: 	&Apache::loncommon::start_data_table().
                   5319: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5320: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5321: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5322: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5323: 
1.329     albertel 5324:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5325:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5326:     $iterator->next(); # skip the first BEGIN_MAP
                   5327:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5328:     while ($depth > 0) {
1.68      ng       5329:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5330:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5331: 
1.745     raeburn  5332:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5333: 	    my $parts = $curRes->parts();
1.68      ng       5334:             my $title = $curRes->compTitle();
1.71      ng       5335: 	    my $symbx = $curRes->symb();
1.746     raeburn  5336:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5337: 	    $studentTable.=
                   5338: 		&Apache::loncommon::start_data_table_row().
                   5339: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5340: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5341: 		                        : '<br />('.&mt('[_1]parts',
                   5342: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5343: 		 ).
                   5344: 		 '</td>';
1.71      ng       5345: 	    $studentTable.='<td valign="top">';
1.382     albertel 5346: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5347:             if ($is_tool) {
                   5348:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5349:             } else {
1.745     raeburn  5350: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5351: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5352: 					         undef,'both',\%form);
                   5353: 	        } else {
                   5354: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5355: 		    $companswer =~ s|<form(.*?)>||g;
                   5356: 		    $companswer =~ s|</form>||g;
                   5357: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5358: #		        $companswer =~ s/$1/ /ms;
                   5359: #		        $request->print('match='.$1."<br />\n");
                   5360: #		    }
                   5361: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5362: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5363: 		}
1.71      ng       5364: 	    }
                   5365: 
1.257     albertel 5366: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5367: 
1.257     albertel 5368: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5369: 		if ($record{'version'} eq '') {
1.745     raeburn  5370:                     my $msg = &mt('No recorded submission for this problem.');
                   5371:                     if ($is_tool) {
                   5372:                         $msg = &mt('No recorded transactions for this external tool');
                   5373:                     }
                   5374: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5375: 		} else {
1.116     ng       5376: 		    my %responseType = ();
                   5377: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5378: 			my @responseIds =$curRes->responseIds($partid);
                   5379: 			my @responseType =$curRes->responseType($partid);
                   5380: 			my %responseIds;
                   5381: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5382: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5383: 			}
                   5384: 			$responseType{$partid} = \%responseIds;
1.116     ng       5385: 		    }
1.148     albertel 5386: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5387: 		}
1.257     albertel 5388: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5389: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5390:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5391: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5392: 									$env{'request.course.id'},
1.726     raeburn  5393: 									'','.submission',undef,
                   5394:                                                                         $usec,$identifier);
1.71      ng       5395:  
                   5396: 	    }
1.103     albertel 5397: 	    if (&canmodify($usec)) {
1.585     bisitz   5398:             $studentTable.=&gradeBox_start();
1.103     albertel 5399: 		foreach my $partid (@{$parts}) {
                   5400: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5401: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5402: 		    $question++;
                   5403: 		}
1.585     bisitz   5404:             $studentTable.=&gradeBox_end();
1.196     albertel 5405: 		$prob++;
1.71      ng       5406: 	    }
                   5407: 	    $studentTable.='</td></tr>';
1.68      ng       5408: 
1.103     albertel 5409: 	}
1.68      ng       5410:         $curRes = $iterator->next();
                   5411:     }
                   5412: 
1.589     bisitz   5413:     $studentTable.=
                   5414:         '</table>'."\n".
                   5415:         '<input type="button" value="'.&mt('Save').'" '.
                   5416:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5417:         '</form>'."\n";
1.71      ng       5418:     $request->print($studentTable);
                   5419: 
                   5420:     return '';
1.119     ng       5421: }
                   5422: 
                   5423: sub displaySubByDates {
1.148     albertel 5424:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5425:     my $isCODE=0;
1.335     albertel 5426:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5427:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5428:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5429:     my $studentTable=&Apache::loncommon::start_data_table().
                   5430: 	&Apache::loncommon::start_data_table_header_row().
                   5431: 	'<th>'.&mt('Date/Time').'</th>'.
                   5432: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5433:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5434: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5435: 	'<th>'.&mt('Status').'</th>'.
                   5436: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5437:     my ($version);
                   5438:     my %mark;
1.148     albertel 5439:     my %orders;
1.119     ng       5440:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5441:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5442:         if ($is_tool) {
                   5443:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5444:         } else {
                   5445:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5446:         }
1.147     albertel 5447:     }
1.335     albertel 5448: 
                   5449:     my $interaction;
1.525     raeburn  5450:     my $no_increment = 1;
1.735     raeburn  5451:     my (%lastrndseed,%lasttype);
1.119     ng       5452:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5453: 	my $timestamp = 
                   5454: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5455: 	if (exists($$record{$version.':resource.0.version'})) {
                   5456: 	    $interaction = $$record{$version.':resource.0.version'};
                   5457: 	}
1.671     raeburn  5458:         if ($isTask && $env{'form.previousversion'}) {
                   5459:             next unless ($interaction == $env{'form.previousversion'});
                   5460:         }
1.335     albertel 5461: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5462: 		             : "$version:resource");
1.467     albertel 5463: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5464: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5465: 	if ($isCODE) {
                   5466: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5467: 	}
1.671     raeburn  5468:         if ($isTask) {
                   5469:             $studentTable.='<td>'.$interaction.'</td>';
                   5470:         }
1.119     ng       5471: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5472: 	my @displaySub = ();
                   5473: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5474:             my ($hidden,$type);
                   5475:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5476:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5477:                 $hidden = 1;
                   5478:             }
1.749     raeburn  5479:             my @matchKey;
                   5480:             if ($isTask) {
1.769     raeburn  5481:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  5482:             } elsif ($is_tool) {
1.769     raeburn  5483:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  5484:             } else {
1.769     raeburn  5485:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  5486:             }
1.122     ng       5487: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5488: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5489: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5490: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5491: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5492:                     if ($is_tool) {
                   5493:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5494:                     } else {
1.749     raeburn  5495: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5496: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5497:                         $displaySub[0].='<span class="LC_nobreak">';
                   5498:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5499:                                        .' <span class="LC_internal_info">'
                   5500:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5501:                                        .'</span>'
                   5502:                                        .' <b>';
                   5503:                         if ($hidden) {
                   5504:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5505:                         } else {
                   5506:                             my ($trial,$rndseed,$newvariation);
                   5507:                             if ($type eq 'randomizetry') {
                   5508:                                 $trial = $$record{"$where.$partid.tries"};
                   5509:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5510:                             }
                   5511: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5512: 			        $displaySub[0].=&mt('Trial not counted');
                   5513: 		            } else {
                   5514: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5515: 					        $$record{"$where.$partid.tries"});
                   5516:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5517:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5518:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5519:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5520:                                     }
1.640     raeburn  5521:                                 }
1.749     raeburn  5522:                                 $lastrndseed{$partid} = $rndseed;
                   5523:                                 $lasttype{$partid} = $type;
                   5524: 		            }
                   5525: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5526:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5527: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5528: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5529: 			        $orders{$partid}->{$responseId}=
                   5530: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5531:                                                $no_increment,$type,$trial,$rndseed);
                   5532: 		            }
                   5533: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5534: 		            $displaySub[0].='&nbsp; '.
                   5535: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5536:                         }
1.596     raeburn  5537:                     }
1.147     albertel 5538: 		}
                   5539: 	    }
1.335     albertel 5540: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5541: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5542: 				    $$record{"$where.$partid.checkedin"},
                   5543: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5544: 					'<br />';
1.335     albertel 5545: 	    }
                   5546: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5547: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5548: 		    lc($$record{"$where.$partid.award"}).' '.
                   5549: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5550: 		    '<br />';
1.749     raeburn  5551: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5552: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5553: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5554: 		}
1.147     albertel 5555: 	    }
1.335     albertel 5556: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5557: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5558: 		unless ($is_tool) {
                   5559: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5560: 		}
1.335     albertel 5561: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5562: 		$displaySub[2].=
1.749     raeburn  5563: 		    $$record{"$version:resource.$partid.regrader"};
                   5564:                 unless ($is_tool) {
                   5565: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5566:                 }
1.147     albertel 5567: 	    }
                   5568: 	}
                   5569: 	# needed because old essay regrader has not parts info
                   5570: 	if (exists $$record{"$version:resource.regrader"}) {
                   5571: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5572: 	}
                   5573: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5574: 	if ($displaySub[2]) {
1.467     albertel 5575: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5576: 	}
1.467     albertel 5577: 	$studentTable.='&nbsp;</td>'.
                   5578: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5579:     }
1.467     albertel 5580:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5581:     return $studentTable;
1.71      ng       5582: }
                   5583: 
                   5584: sub updateGradeByPage {
1.608     www      5585:     my ($request,$symb) = @_;
1.71      ng       5586: 
1.257     albertel 5587:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5588:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5589:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5590:     my $pageTitle = $env{'form.page'};
1.103     albertel 5591:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5592:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5593:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5594:     if (!&canmodify($usec)) {
1.526     raeburn  5595: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5596: 	return;
                   5597:     }
1.398     albertel 5598:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5599:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5600: 	'</h3>'."\n";
1.70      ng       5601: 
1.68      ng       5602:     $request->print($result);
                   5603: 
1.582     raeburn  5604: 
1.132     bowersj2 5605:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5606:     unless (ref($navmap)) {
                   5607:         $request->print(&navmap_errormsg());
                   5608:         return;
                   5609:     }
1.257     albertel 5610:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5611:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5612:     if (!$map) {
1.527     raeburn  5613: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5614: 	return; 
                   5615:     }
1.71      ng       5616:     my $iterator = $navmap->getIterator($map->map_start(),
                   5617: 					$map->map_finish());
1.70      ng       5618: 
1.484     albertel 5619:     my $studentTable=
                   5620: 	&Apache::loncommon::start_data_table().
                   5621: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5622: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5623: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5624: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5625: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5626: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5627: 
                   5628:     $iterator->next(); # skip the first BEGIN_MAP
                   5629:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5630:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5631:     while ($depth > 0) {
1.71      ng       5632:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5633:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5634: 
1.385     albertel 5635:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5636: 	    my $parts = $curRes->parts();
1.71      ng       5637:             my $title = $curRes->compTitle();
                   5638: 	    my $symbx = $curRes->symb();
1.484     albertel 5639: 	    $studentTable.=
                   5640: 		&Apache::loncommon::start_data_table_row().
                   5641: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5642: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5643:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5644: 		.')').'</td>';
1.71      ng       5645: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5646: 
                   5647: 	    my %newrecord=();
                   5648: 	    my @displayPts=();
1.269     raeburn  5649:             my %aggregate = ();
                   5650:             my $aggregateflag = 0;
1.726     raeburn  5651:             if ($env{'form.HIDE'.$prob}) {
                   5652:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5653:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5654:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5655:                 $hideflag += $numchgs;
                   5656:             }
1.71      ng       5657: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5658: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5659: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5660: 
1.257     albertel 5661: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5662: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5663: 		my $partial = $newpts/$wgt;
                   5664: 		my $score;
                   5665: 		if ($partial > 0) {
                   5666: 		    $score = 'correct_by_override';
1.125     ng       5667: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5668: 		    $score = 'incorrect_by_override';
                   5669: 		}
1.257     albertel 5670: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5671: 		if ($dropMenu eq 'excused') {
1.71      ng       5672: 		    $partial = '';
                   5673: 		    $score = 'excused';
1.125     ng       5674: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5675: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5676: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5677: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5678: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5679: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5680: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5681: 		    $changeflag++;
                   5682: 		    $newpts = '';
1.269     raeburn  5683:                     
                   5684:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5685:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5686:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5687:                     if ($aggtries > 0) {
                   5688:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5689:                         $aggregateflag = 1;
                   5690:                     }
1.71      ng       5691: 		}
1.324     albertel 5692: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5693: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5694: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5695: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5696: 		    '&nbsp;<br />';
1.526     raeburn  5697: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5698: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5699: 		    '&nbsp;<br />';
1.71      ng       5700: 		$question++;
1.380     albertel 5701: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5702: 
1.71      ng       5703: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5704: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5705: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5706: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5707: 
                   5708: 		$changeflag++;
                   5709: 	    }
                   5710: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5711: 		my %record = 
                   5712: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5713: 					     $udom,$uname);
                   5714: 
                   5715: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5716: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5717: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5718: 		    $newrecord{'resource.CODE'} = '';
                   5719: 		}
1.257     albertel 5720: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5721: 					$udom,$uname);
1.382     albertel 5722: 		%record = &Apache::lonnet::restore($symbx,
                   5723: 						   $env{'request.course.id'},
                   5724: 						   $udom,$uname);
1.380     albertel 5725: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5726: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5727: 	    }
1.380     albertel 5728: 	    
1.269     raeburn  5729:             if ($aggregateflag) {
                   5730:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5731:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5732:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5733:             }
1.125     ng       5734: 
1.71      ng       5735: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5736: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5737: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5738: 
1.196     albertel 5739: 	    $prob++;
1.68      ng       5740: 	}
1.71      ng       5741:         $curRes = $iterator->next();
1.68      ng       5742:     }
1.98      albertel 5743: 
1.484     albertel 5744:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5745:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5746: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5747: 		  $changeflag).'<br />');
                   5748:     my $hidemsg=($hideflag == 0 ? '' :
                   5749:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5750:                      $hideflag).'<br />');
                   5751:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5752: 
1.70      ng       5753:     return '';
                   5754: }
                   5755: 
1.72      ng       5756: #-------- end of section for handling grading by page/sequence ---------
                   5757: #
                   5758: #-------------------------------------------------------------------
                   5759: 
1.581     www      5760: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5761: #
                   5762: #------ start of section for handling grading by page/sequence ---------
                   5763: 
1.423     albertel 5764: =pod
                   5765: 
                   5766: =head1 Bubble sheet grading routines
                   5767: 
1.424     albertel 5768:   For this documentation:
                   5769: 
                   5770:    'scanline' refers to the full line of characters
                   5771:    from the file that we are parsing that represents one entire sheet
                   5772: 
                   5773:    'bubble line' refers to the data
1.659     raeburn  5774:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5775: 
                   5776: 
1.659     raeburn  5777: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5778: into a course. When a user wants to grade, they select a
1.659     raeburn  5779: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5780: one of the predefined configurations for what each scanline looks
                   5781: like.
                   5782: 
                   5783: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5784: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5785: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5786: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5787: invalid student/employee ID
1.424     albertel 5788: 
                   5789: If the CODE option is used that determines the randomization of the
1.556     weissno  5790: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5791: username:domain.
                   5792: 
                   5793: During the validation phase the instructor can choose to skip scanlines. 
                   5794: 
1.659     raeburn  5795: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5796: 
                   5797:   scantron_original_filename (unmodified original file)
                   5798:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5799:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5800: 
                   5801: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5802: correction information that isn't representable in the bubblesheet
1.424     albertel 5803: file (see &scantron_getfile() for more information)
                   5804: 
                   5805: After all scanlines are either valid, marked as valid or skipped, then
                   5806: foreach line foreach problem in the picked sequence, an ssi request is
                   5807: made that simulates a user submitting their selected letter(s) against
                   5808: the homework problem.
1.423     albertel 5809: 
                   5810: =over 4
                   5811: 
                   5812: 
                   5813: 
                   5814: =item defaultFormData
                   5815: 
                   5816:   Returns html hidden inputs used to hold context/default values.
                   5817: 
                   5818:  Arguments:
                   5819:   $symb - $symb of the current resource 
                   5820: 
                   5821: =cut
1.422     foxr     5822: 
1.81      albertel 5823: sub defaultFormData {
1.324     albertel 5824:     my ($symb)=@_;
1.766     raeburn  5825:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5826: }
                   5827: 
1.447     foxr     5828: 
1.423     albertel 5829: =pod 
                   5830: 
                   5831: =item getSequenceDropDown
                   5832: 
                   5833:    Return html dropdown of possible sequences to grade
                   5834:  
                   5835:  Arguments:
1.582     raeburn  5836:    $symb - $symb of the current resource
                   5837:    $map_error - ref to scalar which will container error if
                   5838:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5839: 
                   5840: =cut
1.422     foxr     5841: 
1.75      albertel 5842: sub getSequenceDropDown {
1.582     raeburn  5843:     my ($symb,$map_error)=@_;
1.75      albertel 5844:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5845:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5846:     if (ref($map_error)) {
                   5847:         return if ($$map_error);
                   5848:     }
1.137     albertel 5849:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5850:     my $ctr=0;
                   5851:     foreach (@$titles) {
                   5852: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5853: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5854: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5855: 	    '>'.$showtitle.'</option>'."\n";
                   5856: 	$ctr++;
                   5857:     }
                   5858:     $result.= '</select>';
                   5859:     return $result;
                   5860: }
                   5861: 
1.495     albertel 5862: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5863:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5864: 
                   5865: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5866: 
1.509     raeburn  5867: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5868:                                    # matchresponse or rankresponse, where 
                   5869:                                    # an individual response can have multiple 
                   5870:                                    # lines
1.503     raeburn  5871: 
                   5872: my %responsetype_per_response;     # responsetype for each response
                   5873: 
1.691     raeburn  5874: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5875:                                    # numbered response. Needed when randomorder
                   5876:                                    # or randompick are in use. Key is ID, value 
                   5877:                                    # is response number.
                   5878: 
1.495     albertel 5879: # Save and restore the bubble lines array to the form env.
                   5880: 
                   5881: 
                   5882: sub save_bubble_lines {
                   5883:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5884: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5885: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5886: 	    $first_bubble_line{$line};
1.503     raeburn  5887:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5888:             $subdivided_bubble_lines{$line};
                   5889:         $env{"form.scantron.responsetype.$line"} =
                   5890:             $responsetype_per_response{$line};
1.495     albertel 5891:     }
1.691     raeburn  5892:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5893:         my $line = $masterseq_id_responsenum{$resid};
                   5894:         $env{"form.scantron.residpart.$line"} = $resid;
                   5895:     }
1.495     albertel 5896: }
                   5897: 
                   5898: 
                   5899: sub restore_bubble_lines {
                   5900:     my $line = 0;
                   5901:     %bubble_lines_per_response = ();
1.691     raeburn  5902:     %masterseq_id_responsenum = ();
1.495     albertel 5903:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5904: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5905: 	$bubble_lines_per_response{$line} = $value;
                   5906: 	$first_bubble_line{$line}  =
                   5907: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5908:         $subdivided_bubble_lines{$line} =
                   5909:             $env{"form.scantron.sub_bubblelines.$line"};
                   5910:         $responsetype_per_response{$line} =
                   5911:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5912:         my $id = $env{"form.scantron.residpart.$line"};
                   5913:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5914: 	$line++;
                   5915:     }
                   5916: }
                   5917: 
1.423     albertel 5918: =pod 
                   5919: 
                   5920: =item scantron_filenames
                   5921: 
                   5922:    Returns a list of the scantron files in the current course 
                   5923: 
                   5924: =cut
1.422     foxr     5925: 
1.202     albertel 5926: sub scantron_filenames {
1.257     albertel 5927:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5928:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5929:     my $getpropath = 1;
1.662     raeburn  5930:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5931:                                                         $cname,$getpropath);
1.202     albertel 5932:     my @possiblenames;
1.662     raeburn  5933:     if (ref($dirlist) eq 'ARRAY') {
                   5934:         foreach my $filename (sort(@{$dirlist})) {
                   5935: 	    ($filename)=split(/&/,$filename);
                   5936: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5937: 	    $filename=~s/^scantron_orig_//;
                   5938: 	    push(@possiblenames,$filename);
                   5939:         }
1.202     albertel 5940:     }
                   5941:     return @possiblenames;
                   5942: }
                   5943: 
1.423     albertel 5944: =pod 
                   5945: 
                   5946: =item scantron_uploads
                   5947: 
                   5948:    Returns  html drop-down list of scantron files in current course.
                   5949: 
                   5950:  Arguments:
                   5951:    $file2grade - filename to set as selected in the dropdown
                   5952: 
                   5953: =cut
1.422     foxr     5954: 
1.202     albertel 5955: sub scantron_uploads {
1.209     ng       5956:     my ($file2grade) = @_;
1.202     albertel 5957:     my $result=	'<select name="scantron_selectfile">';
                   5958:     $result.="<option></option>";
                   5959:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5960: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5961:     }
                   5962:     $result.="</select>";
                   5963:     return $result;
                   5964: }
                   5965: 
1.423     albertel 5966: =pod 
                   5967: 
                   5968: =item scantron_scantab
                   5969: 
                   5970:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5971:   file.
                   5972: 
                   5973: =cut
1.422     foxr     5974: 
1.82      albertel 5975: sub scantron_scantab {
                   5976:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5977:     $result.='<option></option>'."\n";
1.754     raeburn  5978:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5979:     if (@lines > 0) {
                   5980:         foreach my $line (@lines) {
                   5981:             next if (($line =~ /^\#/) || ($line eq ''));
                   5982: 	    my ($name,$descrip)=split(/:/,$line);
                   5983: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5984:         }
1.82      albertel 5985:     }
                   5986:     $result.='</select>'."\n";
1.518     raeburn  5987:     return $result;
                   5988: }
                   5989: 
1.423     albertel 5990: =pod 
                   5991: 
                   5992: =item scantron_CODElist
                   5993: 
                   5994:   Returns html drop down of the saved CODE lists from current course,
                   5995:   generated from earlier printings.
                   5996: 
                   5997: =cut
1.422     foxr     5998: 
1.186     albertel 5999: sub scantron_CODElist {
1.257     albertel 6000:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6001:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 6002:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   6003:     my $namechoice='<option></option>';
1.225     albertel 6004:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 6005: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 6006: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 6007: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   6008:     }
                   6009:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6010:     return $namechoice;
                   6011: }
                   6012: 
1.423     albertel 6013: =pod 
                   6014: 
                   6015: =item scantron_CODEunique
                   6016: 
                   6017:   Returns the html for "Each CODE to be used once" radio.
                   6018: 
                   6019: =cut
1.422     foxr     6020: 
1.186     albertel 6021: sub scantron_CODEunique {
1.532     bisitz   6022:     my $result='<span class="LC_nobreak">
1.272     albertel 6023:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6024:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6025:                 </span>
1.532     bisitz   6026:                 <span class="LC_nobreak">
1.272     albertel 6027:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6028:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6029:                 </span>';
1.186     albertel 6030:     return $result;
                   6031: }
1.423     albertel 6032: 
                   6033: =pod 
                   6034: 
                   6035: =item scantron_selectphase
                   6036: 
1.659     raeburn  6037:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6038:   Allows for - starting a grading run.
1.424     albertel 6039:              - downloading existing scan data (original, corrected
1.423     albertel 6040:                                                 or skipped info)
                   6041: 
                   6042:              - uploading new scan data
                   6043: 
                   6044:  Arguments:
                   6045:   $r          - The Apache request object
                   6046:   $file2grade - name of the file that contain the scanned data to score
                   6047: 
                   6048: =cut
1.186     albertel 6049: 
1.75      albertel 6050: sub scantron_selectphase {
1.608     www      6051:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6052:     if (!$symb) {return '';}
1.582     raeburn  6053:     my $map_error;
                   6054:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6055:     if ($map_error) {
                   6056:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6057:         return;
                   6058:     }
1.324     albertel 6059:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6060:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6061:     my $format_selector=&scantron_scantab();
1.186     albertel 6062:     my $CODE_selector=&scantron_CODElist();
                   6063:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6064:     my $result;
1.422     foxr     6065: 
1.513     foxr     6066:     $ssi_error = 0;
                   6067: 
1.770     raeburn  6068:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 6069: 
                   6070: 	# Chunk of form to prompt for a scantron file upload.
                   6071: 
                   6072:         $r->print('
1.754     raeburn  6073:     <br />');
1.606     wenzelju 6074:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6075:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  6076:     my $csec= $env{'request.course.sec'};
1.736     damieng  6077:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6078:     &js_escape(\$alertmsg);
1.754     raeburn  6079:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 6080:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   6081:     function checkUpload(formname) {
                   6082: 	if (formname.upfile.value == "") {
1.736     damieng  6083: 	    alert("'.$alertmsg.'");
1.606     wenzelju 6084: 	    return false;
                   6085: 	}
                   6086: 	formname.submit();
1.756     raeburn  6087:     }'."\n".$formatjs));
1.606     wenzelju 6088:     $r->print('
                   6089:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6090:                 '.$default_form_data.'
                   6091:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  6092:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 6093:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6094:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  6095:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6096:               '.&Apache::loncommon::start_data_table_header_row().'
                   6097:                 <th>
                   6098:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6099:                 </th>
                   6100:               '.&Apache::loncommon::end_data_table_header_row().'
                   6101:               '.&Apache::loncommon::start_data_table_row().'
                   6102:             <td>
                   6103:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6104:     if ($formatoptions) {
                   6105:         $r->print('</td>
                   6106:                  '.&Apache::loncommon::end_data_table_row().'
                   6107:                  '.&Apache::loncommon::start_data_table_row().'
                   6108:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6109:                  </td>
                   6110:                  '.&Apache::loncommon::end_data_table_row().'
                   6111:                  '.&Apache::loncommon::start_data_table_row().'
                   6112:                  <td>'
                   6113:         );
                   6114:     } else {
                   6115:         $r->print(' <br />');
                   6116:     }
                   6117:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6118:               </td>
                   6119:              '.&Apache::loncommon::end_data_table_row().'
                   6120:              '.&Apache::loncommon::end_data_table().'
                   6121:              </form>'
                   6122:     );
1.606     wenzelju 6123: 
                   6124:     }
                   6125: 
1.422     foxr     6126:     # Chunk of form to prompt for a file to grade and how:
                   6127: 
1.489     albertel 6128:     $result.= '
                   6129:     <br />
                   6130:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6131:     <input type="hidden" name="command" value="scantron_warning" />
                   6132:     '.$default_form_data.'
                   6133:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6134:        '.&Apache::loncommon::start_data_table_header_row().'
                   6135:             <th colspan="2">
1.492     albertel 6136:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6137:             </th>
                   6138:        '.&Apache::loncommon::end_data_table_header_row().'
                   6139:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6140:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6141:        '.&Apache::loncommon::end_data_table_row().'
                   6142:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6143:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6144:        '.&Apache::loncommon::end_data_table_row().'
                   6145:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6146:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6147:        '.&Apache::loncommon::end_data_table_row().'
                   6148:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6149:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6150:        '.&Apache::loncommon::end_data_table_row().'
                   6151:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6152:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6153:        '.&Apache::loncommon::end_data_table_row().'
                   6154:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6155: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6156:             <td>
1.492     albertel 6157: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6158:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6159:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6160: 	    </td>
1.489     albertel 6161:        '.&Apache::loncommon::end_data_table_row().'
                   6162:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6163:             <td colspan="2">
1.572     www      6164:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6165:             </td>
1.489     albertel 6166:        '.&Apache::loncommon::end_data_table_row().'
                   6167:     '.&Apache::loncommon::end_data_table().'
                   6168:     </form>
                   6169: ';
1.162     albertel 6170:    
                   6171:     $r->print($result);
                   6172: 
1.422     foxr     6173:     # Chunk of the form that prompts to view a scoring office file,
                   6174:     # corrected file, skipped records in a file.
                   6175: 
1.489     albertel 6176:     $r->print('
                   6177:    <br />
                   6178:    <form action="/adm/grades" name="scantron_download">
                   6179:      '.$default_form_data.'
                   6180:      <input type="hidden" name="command" value="scantron_download" />
                   6181:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6182:        '.&Apache::loncommon::start_data_table_header_row().'
                   6183:               <th>
1.492     albertel 6184:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6185:               </th>
                   6186:        '.&Apache::loncommon::end_data_table_header_row().'
                   6187:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6188:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6189:                 <br />
1.492     albertel 6190:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6191:        '.&Apache::loncommon::end_data_table_row().'
                   6192:      '.&Apache::loncommon::end_data_table().'
                   6193:    </form>
                   6194:    <br />
                   6195: ');
1.162     albertel 6196: 
1.457     banghart 6197:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6198: 
1.694     bisitz   6199:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6200:              $default_form_data."\n".
                   6201:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6202:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6203:              '<th colspan="2">
1.572     www      6204:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6205:              '</th>'."\n".
                   6206:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6207:               &Apache::loncommon::start_data_table_row()."\n".
                   6208:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6209:               '<td> '.$sequence_selector.' </td>'.
                   6210:               &Apache::loncommon::end_data_table_row()."\n".
                   6211:               &Apache::loncommon::start_data_table_row()."\n".
                   6212:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6213:               '<td> '.$file_selector.' </td>'."\n".
                   6214:               &Apache::loncommon::end_data_table_row()."\n".
                   6215:               &Apache::loncommon::start_data_table_row()."\n".
                   6216:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6217:               '<td> '.$format_selector.' </td>'."\n".
                   6218:               &Apache::loncommon::end_data_table_row()."\n".
                   6219:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6220:               '<td> '.&mt('Options').' </td>'."\n".
                   6221:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6222:               &Apache::loncommon::end_data_table_row()."\n".
                   6223:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6224:               '<td colspan="2">'."\n".
                   6225:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6226:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6227:               '</td>'."\n".
                   6228:               &Apache::loncommon::end_data_table_row()."\n".
                   6229:               &Apache::loncommon::end_data_table()."\n".
                   6230:               '</form><br />');
                   6231:     return;
1.75      albertel 6232: }
                   6233: 
1.423     albertel 6234: =pod 
                   6235: 
                   6236: =item username_to_idmap
                   6237: 
1.556     weissno  6238:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6239:     student username:domain. If a single ID occurs for more than one student,
                   6240:     the status of the student is checked, and if Active, the value in the hash
                   6241:     will be set to the Active student.
1.423     albertel 6242: 
                   6243:   Arguments:
                   6244: 
                   6245:     $classlist - reference to the class list hash. This is a hash
                   6246:                  keyed by student name:domain  whose elements are references
1.424     albertel 6247:                  to arrays containing various chunks of information
1.423     albertel 6248:                  about the student. (See loncoursedata for more info).
                   6249: 
                   6250:   Returns
                   6251:     %idmap - the constructed hash
                   6252: 
                   6253: =cut
                   6254: 
1.82      albertel 6255: sub username_to_idmap {
                   6256:     my ($classlist)= @_;
                   6257:     my %idmap;
                   6258:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6259:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6260:         unless ($id eq '') {
                   6261:             if (!exists($idmap{$id})) {
                   6262:                 $idmap{$id} = $student;
                   6263:             } else {
                   6264:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6265:                 if ($status eq 'Active') {
                   6266:                     $idmap{$id} = $student;
                   6267:                 }
                   6268:             }
                   6269:         }
1.82      albertel 6270:     }
                   6271:     return %idmap;
                   6272: }
1.423     albertel 6273: 
                   6274: =pod
                   6275: 
1.424     albertel 6276: =item scantron_fixup_scanline
1.423     albertel 6277: 
                   6278:    Process a requested correction to a scanline.
                   6279: 
                   6280:   Arguments:
1.754     raeburn  6281:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6282:     $scan_data         - hash of correction information 
                   6283:                           (see &scantron_getfile())
                   6284:     $line              - existing scanline
                   6285:     $whichline         - line number of the passed in scanline
                   6286:     $field             - type of change to process 
                   6287:                          (either 
1.573     bisitz   6288:                           'ID'     -> correct the student/employee ID
1.423     albertel 6289:                           'CODE'   -> correct the CODE
                   6290:                           'answer' -> fixup the submitted answers)
                   6291:     
                   6292:    $args               - hash of additional info,
                   6293:                           - 'ID' 
                   6294:                                'newid' -> studentID to use in replacement
1.424     albertel 6295:                                           of existing one
1.423     albertel 6296:                           - 'CODE' 
                   6297:                                'CODE_ignore_dup' - set to true if duplicates
                   6298:                                                    should be ignored.
                   6299: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6300:                                         if the existing unfound code should
1.423     albertel 6301:                                         be used as is
                   6302:                           - 'answer'
                   6303:                                'response' - new answer or 'none' if blank
                   6304:                                'question' - the bubble line to change
1.503     raeburn  6305:                                'questionnum' - the question identifier,
                   6306:                                                may include subquestion. 
1.423     albertel 6307: 
                   6308:   Returns:
                   6309:     $line - the modified scanline
                   6310: 
                   6311:   Side effects: 
                   6312:     $scan_data - may be updated
                   6313: 
                   6314: =cut
                   6315: 
1.82      albertel 6316: 
1.157     albertel 6317: sub scantron_fixup_scanline {
                   6318:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6319:     if ($field eq 'ID') {
                   6320: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6321: 	    return ($line,1,'New value too large');
1.157     albertel 6322: 	}
                   6323: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6324: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6325: 				     $args->{'newid'});
                   6326: 	}
                   6327: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6328: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6329: 	if ($args->{'newid'}=~/^\s*$/) {
                   6330: 	    &scan_data($scan_data,"$whichline.user",
                   6331: 		       $args->{'username'}.':'.$args->{'domain'});
                   6332: 	}
1.186     albertel 6333:     } elsif ($field eq 'CODE') {
1.192     albertel 6334: 	if ($args->{'CODE_ignore_dup'}) {
                   6335: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6336: 	}
                   6337: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6338: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6339: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6340: 		return ($line,1,'New CODE value too large');
                   6341: 	    }
                   6342: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6343: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6344: 	    }
                   6345: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6346: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6347: 	}
1.157     albertel 6348:     } elsif ($field eq 'answer') {
1.497     foxr     6349: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6350: 	my $off=$scantron_config->{'Qoff'};
                   6351: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6352: 	my $answer=${off}x$length;
                   6353: 	if ($args->{'response'} eq 'none') {
                   6354: 	    &scan_data($scan_data,
1.503     raeburn  6355: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6356: 	} else {
                   6357: 	    if ($on eq 'letter') {
                   6358: 		my @alphabet=('A'..'Z');
                   6359: 		$answer=$alphabet[$args->{'response'}];
                   6360: 	    } elsif ($on eq 'number') {
                   6361: 		$answer=$args->{'response'}+1;
                   6362: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6363: 	    } else {
1.497     foxr     6364: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6365: 	    }
1.497     foxr     6366: 	    &scan_data($scan_data,
1.503     raeburn  6367: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6368: 	}
1.497     foxr     6369: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6370: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6371:     }
                   6372:     return $line;
                   6373: }
1.423     albertel 6374: 
                   6375: =pod
                   6376: 
                   6377: =item scan_data
                   6378: 
                   6379:     Edit or look up  an item in the scan_data hash.
                   6380: 
                   6381:   Arguments:
                   6382:     $scan_data  - The hash (see scantron_getfile)
                   6383:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6384:                   scantronfilename_key).
1.423     albertel 6385:     $data        - New value of the hash entry.
                   6386:     $delete      - If true, the entry is removed from the hash.
                   6387: 
                   6388:   Returns:
                   6389:     The new value of the hash table field (undefined if deleted).
                   6390: 
                   6391: =cut
                   6392: 
                   6393: 
1.157     albertel 6394: sub scan_data {
                   6395:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6396:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6397:     if (defined($value)) {
                   6398: 	$scan_data->{$filename.'_'.$key} = $value;
                   6399:     }
                   6400:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6401:     return $scan_data->{$filename.'_'.$key};
                   6402: }
1.423     albertel 6403: 
1.495     albertel 6404: # ----- These first few routines are general use routines.----
                   6405: 
                   6406: # Return the number of occurences of a pattern in a string.
                   6407: 
                   6408: sub occurence_count {
                   6409:     my ($string, $pattern) = @_;
                   6410: 
                   6411:     my @matches = ($string =~ /$pattern/g);
                   6412: 
                   6413:     return scalar(@matches);
                   6414: }
                   6415: 
                   6416: 
                   6417: # Take a string known to have digits and convert all the
                   6418: # digits into letters in the range J,A..I.
                   6419: 
                   6420: sub digits_to_letters {
                   6421:     my ($input) = @_;
                   6422: 
                   6423:     my @alphabet = ('J', 'A'..'I');
                   6424: 
                   6425:     my @input    = split(//, $input);
                   6426:     my $output ='';
                   6427:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6428: 	if ($input[$i] =~ /\d/) {
                   6429: 	    $output .= $alphabet[$input[$i]];
                   6430: 	} else {
                   6431: 	    $output .= $input[$i];
                   6432: 	}
                   6433:     }
                   6434:     return $output;
                   6435: }
                   6436: 
1.423     albertel 6437: =pod 
                   6438: 
                   6439: =item scantron_parse_scanline
                   6440: 
1.711     bisitz   6441:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6442: 
                   6443:  Arguments:
1.711     bisitz   6444:     line             - The text of the bubblesheet file line to process
1.423     albertel 6445:     whichline        - Line number
1.711     bisitz   6446:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6447:     scan_data        - Hash of extra information about the scanline
                   6448:                        (see scantron_getfile for more information)
                   6449:     just_header      - True if should not process question answers but only
                   6450:                        the stuff to the left of the answers.
1.691     raeburn  6451:     randomorder      - True if randomorder in use
                   6452:     randompick       - True if randompick in use
                   6453:     sequence         - Exam folder URL
                   6454:     master_seq       - Ref to array containing symbs in exam folder
                   6455:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6456:                        (corresponding values are resource objects)
                   6457:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6458:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6459:                        are refs to an array of resource objects, ordered
                   6460:                        according to order used for CODE, when randomorder
                   6461:                        and or randompick are in use.
                   6462:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6463:                        for current line to question number used for same question
                   6464:                         in "Master Sequence" (as seen by Course Coordinator).
                   6465:     startline        - Ref to hash where key is question number (0 is first)
                   6466:                        and value is number of first bubble line for current 
                   6467:                        student or code-based randompick and/or randomorder.
                   6468:     totalref         - Ref of scalar used to score total number of bubble
                   6469:                        lines needed for responses in a scan line (used when
                   6470:                        randompick in use. 
                   6471:     
1.423     albertel 6472:  Returns:
                   6473:    Hash containing the result of parsing the scanline
                   6474: 
                   6475:    Keys are all proceeded by the string 'scantron.'
                   6476: 
                   6477:        CODE    - the CODE in use for this scanline
                   6478:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6479:                  by the operator
                   6480:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6481:                             CODEs were selected, but the usage has been
                   6482:                             forced by the operator
1.556     weissno  6483:        ID  - student/employee ID
1.423     albertel 6484:        PaperID - if used, the ID number printed on the sheet when the 
                   6485:                  paper was scanned
                   6486:        FirstName - first name from the sheet
                   6487:        LastName  - last name from the sheet
                   6488: 
                   6489:      if just_header was not true these key may also exist
                   6490: 
1.447     foxr     6491:        missingerror - a list of bubble ranges that are considered to be answers
                   6492:                       to a single question that don't have any bubbles filled in.
                   6493:                       Of the form questionnumber:firstbubblenumber:count.
                   6494:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6495:                       to a single question that have more than one bubble filled in.
                   6496:                       Of the form questionnumber::firstbubblenumber:count
                   6497:    
                   6498:                 In the above, count is the number of bubble responses in the
                   6499:                 input line needed to represent the possible answers to the question.
                   6500:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6501:                 per line would have count = 2.
                   6502: 
1.423     albertel 6503:        maxquest     - the number of the last bubble line that was parsed
                   6504: 
                   6505:        (<number> starts at 1)
                   6506:        <number>.answer - zero or more letters representing the selected
                   6507:                          letters from the scanline for the bubble line 
                   6508:                          <number>.
                   6509:                          if blank there was either no bubble or there where
                   6510:                          multiple bubbles, (consult the keys missingerror and
                   6511:                          doubleerror if this is an error condition)
                   6512: 
                   6513: =cut
                   6514: 
1.82      albertel 6515: sub scantron_parse_scanline {
1.691     raeburn  6516:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6517:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6518:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6519: 
1.82      albertel 6520:     my %record;
1.691     raeburn  6521:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6522:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6523: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6524: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6525: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6526: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6527: 	    $record{'scantron.CODE'}=substr($data,
                   6528: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6529: 					    $$scantron_config{'CODElength'});
1.191     albertel 6530: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6531: 		$record{'scantron.useCODE'}=1;
                   6532: 	    }
1.192     albertel 6533: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6534: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6535: 	    }
1.82      albertel 6536: 	} else {
                   6537: 	    #FIXME interpret first N questions
                   6538: 	}
                   6539:     }
1.83      albertel 6540:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6541: 				  $$scantron_config{'IDlength'});
1.157     albertel 6542:     $record{'scantron.PaperID'}=
                   6543: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6544: 	       $$scantron_config{'PaperIDlength'});
                   6545:     $record{'scantron.FirstName'}=
                   6546: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6547: 	       $$scantron_config{'FirstNamelength'});
                   6548:     $record{'scantron.LastName'}=
                   6549: 	substr($data,$$scantron_config{'LastName'}-1,
                   6550: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6551:     if ($just_header) { return \%record; }
1.194     albertel 6552: 
1.82      albertel 6553:     my @alphabet=('A'..'Z');
                   6554:     my $questnum=0;
1.447     foxr     6555:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6556: 
1.691     raeburn  6557:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6558:     if ($randompick || $randomorder) {
                   6559:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6560:                                          $master_seq,$symb_to_resource,
                   6561:                                          $partids_by_symb,$orderedforcode,
                   6562:                                          $respnumlookup,$startline);
                   6563:         if ($total) {
                   6564:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6565:         }
                   6566:         if (ref($totalref)) {
                   6567:             $$totalref = $total;
                   6568:         }
                   6569:     }
                   6570:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6571:     chomp($questions);		# Get rid of any trailing \n.
                   6572:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6573:     while (length($questions)) {
1.691     raeburn  6574:         my $answers_needed;
                   6575:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6576:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6577:         } else {
                   6578: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6579:         }
1.503     raeburn  6580:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6581:                              || 1;
                   6582:         $questnum++;
                   6583:         my $quest_id = $questnum;
                   6584:         my $currentquest = substr($questions,0,$answer_length);
                   6585:         $questions       = substr($questions,$answer_length);
                   6586:         if (length($currentquest) < $answer_length) { next; }
                   6587: 
1.691     raeburn  6588:         my $subdivided;
                   6589:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6590:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6591:         } else {
                   6592:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6593:         }
                   6594:         if ($subdivided =~ /,/) {
1.503     raeburn  6595:             my $subquestnum = 1;
                   6596:             my $subquestions = $currentquest;
1.691     raeburn  6597:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6598:             foreach my $subans (@subanswers_needed) {
                   6599:                 my $subans_length =
                   6600:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6601:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6602:                 $subquestions   = substr($subquestions,$subans_length);
                   6603:                 $quest_id = "$questnum.$subquestnum";
                   6604:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6605:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6606:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6607:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6608:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6609:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6610:                 } else {
                   6611:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6612:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6613:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6614:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6615:                 }
                   6616:                 $subquestnum ++;
                   6617:             }
                   6618:         } else {
                   6619:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6620:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6621:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6622:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6623:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6624:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6625:             } else {
                   6626:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6627:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6628:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6629:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6630:             }
                   6631:         }
                   6632:     }
                   6633:     $record{'scantron.maxquest'}=$questnum;
                   6634:     return \%record;
                   6635: }
1.447     foxr     6636: 
1.691     raeburn  6637: sub get_master_seq {
                   6638:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6639:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6640:                    (ref($symb_to_resource) eq 'HASH'));
                   6641:     my $resource_error;
                   6642:     foreach my $resource (@{$resources}) {
                   6643:         my $ressymb;
                   6644:         if (ref($resource)) {
                   6645:             $ressymb = $resource->symb();
                   6646:             push(@{$master_seq},$ressymb);
                   6647:             $symb_to_resource->{$ressymb} = $resource;
                   6648:         } else {
                   6649:             $resource_error = 1;
                   6650:             last;
                   6651:         }
                   6652:     }
                   6653:     return $resource_error;
                   6654: }
                   6655: 
                   6656: sub get_respnum_lookups {
                   6657:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6658:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6659:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6660:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6661:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6662:                    (ref($startline) eq 'HASH'));
                   6663:     my ($user,$scancode);
                   6664:     if ((exists($record->{'scantron.CODE'})) &&
                   6665:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6666:         $scancode = $record->{'scantron.CODE'};
                   6667:     } else {
                   6668:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6669:     }
                   6670:     my @mapresources =
                   6671:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6672:                      $orderedforcode);
                   6673:     my $total = 0;
                   6674:     my $count = 0;
                   6675:     foreach my $resource (@mapresources) {
                   6676:         my $id = $resource->id();
                   6677:         my $symb = $resource->symb();
                   6678:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6679:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6680:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6681:                 if ($respnum ne '') {
                   6682:                     $respnumlookup->{$count} = $respnum;
                   6683:                     $startline->{$count} = $total;
                   6684:                     $total += $bubble_lines_per_response{$respnum};
                   6685:                     $count ++;
                   6686:                 }
                   6687:             }
                   6688:         }
                   6689:     }
                   6690:     return $total;
                   6691: }
                   6692: 
1.503     raeburn  6693: sub scantron_validator_lettnum {
                   6694:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6695:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6696:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6697: 
                   6698:     # Qon 'letter' implies for each slot in currquest we have:
                   6699:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6700:     #    about anything else (esp. a value of Qoff) for missing
                   6701:     #    bubbles.
                   6702:     #
                   6703:     # Qon 'number' implies each slot gives a digit that indexes the
                   6704:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6705:     #    and * or ? for double bubbles on a single line.
                   6706:     #
1.447     foxr     6707: 
1.503     raeburn  6708:     my $matchon;
                   6709:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6710:         $matchon = '[A-Z]';
                   6711:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6712:         $matchon = '\d';
                   6713:     }
                   6714:     my $occurrences = 0;
1.691     raeburn  6715:     my $responsenum = $questnum-1;
                   6716:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6717:        $responsenum = $respnumlookup->{$questnum-1} 
                   6718:     }
                   6719:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6720:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6721:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6722:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6723:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6724:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6725:         my @singlelines = split('',$currquest);
                   6726:         foreach my $entry (@singlelines) {
                   6727:             $occurrences = &occurence_count($entry,$matchon);
                   6728:             if ($occurrences > 1) {
                   6729:                 last;
                   6730:             }
1.691     raeburn  6731:         }
1.503     raeburn  6732:     } else {
                   6733:         $occurrences = &occurence_count($currquest,$matchon); 
                   6734:     }
                   6735:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6736:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6737:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6738:             my $bubble = substr($currquest,$ans,1);
                   6739:             if ($bubble =~ /$matchon/ ) {
                   6740:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6741:                     if ($bubble == 0) {
                   6742:                         $bubble = 10; 
                   6743:                     }
                   6744:                     $record->{"scantron.$ansnum.answer"} = 
                   6745:                         $alphabet->[$bubble-1];
                   6746:                 } else {
                   6747:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6748:                 }
                   6749:             } else {
                   6750:                 $record->{"scantron.$ansnum.answer"}='';
                   6751:             }
                   6752:             $ansnum++;
                   6753:         }
                   6754:     } elsif (!defined($currquest)
                   6755:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6756:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6757:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6758:             $record->{"scantron.$ansnum.answer"}='';
                   6759:             $ansnum++;
                   6760:         }
                   6761:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6762:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6763:         }
                   6764:     } else {
                   6765:         if ($$scantron_config{'Qon'} eq 'number') {
                   6766:             $currquest = &digits_to_letters($currquest);            
                   6767:         }
                   6768:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6769:             my $bubble = substr($currquest,$ans,1);
                   6770:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6771:             $ansnum++;
                   6772:         }
                   6773:     }
                   6774:     return $ansnum;
                   6775: }
1.447     foxr     6776: 
1.503     raeburn  6777: sub scantron_validator_positional {
                   6778:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6779:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6780:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6781: 
1.503     raeburn  6782:     # Otherwise there's a positional notation;
                   6783:     # each bubble line requires Qlength items, and there are filled in
                   6784:     # bubbles for each case where there 'Qon' characters.
                   6785:     #
1.447     foxr     6786: 
1.503     raeburn  6787:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6788: 
1.503     raeburn  6789:     # If the split only gives us one element.. the full length of the
                   6790:     # answer string, no bubbles are filled in:
1.447     foxr     6791: 
1.507     raeburn  6792:     if ($answers_needed eq '') {
                   6793:         return;
                   6794:     }
                   6795: 
1.503     raeburn  6796:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6797:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6798:             $record->{"scantron.$ansnum.answer"}='';
                   6799:             $ansnum++;
                   6800:         }
                   6801:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6802:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6803:         }
                   6804:     } elsif (scalar(@array) == 2) {
                   6805:         my $location = length($array[0]);
                   6806:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6807:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6808:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6809:             if ($ans eq $line_num) {
                   6810:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6811:             } else {
                   6812:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6813:             }
                   6814:             $ansnum++;
                   6815:          }
                   6816:     } else {
                   6817:         #  If there's more than one instance of a bubble character
                   6818:         #  That's a double bubble; with positional notation we can
                   6819:         #  record all the bubbles filled in as well as the
                   6820:         #  fact this response consists of multiple bubbles.
                   6821:         #
1.691     raeburn  6822:         my $responsenum = $questnum-1;
                   6823:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6824:             $responsenum = $respnumlookup->{$questnum-1}
                   6825:         }
                   6826:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6827:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6828:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6829:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6830:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6831:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6832:             my $doubleerror = 0;
                   6833:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6834:                    (!$doubleerror)) {
                   6835:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6836:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6837:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6838:                if (length(@currarray) > 2) {
                   6839:                    $doubleerror = 1;
                   6840:                } 
                   6841:             }
                   6842:             if ($doubleerror) {
                   6843:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6844:             }
                   6845:         } else {
                   6846:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6847:         }
                   6848:         my $item = $ansnum;
                   6849:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6850:             $record->{"scantron.$item.answer"} = '';
                   6851:             $item ++;
                   6852:         }
1.447     foxr     6853: 
1.503     raeburn  6854:         my @ans=@array;
                   6855:         my $i=0;
                   6856:         my $increment = 0;
                   6857:         while ($#ans) {
                   6858:             $i+=length($ans[0]) + $increment;
                   6859:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6860:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6861:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6862:             shift(@ans);
                   6863:             $increment = 1;
                   6864:         }
                   6865:         $ansnum += $answers_needed;
1.82      albertel 6866:     }
1.503     raeburn  6867:     return $ansnum;
1.82      albertel 6868: }
                   6869: 
1.423     albertel 6870: =pod
                   6871: 
                   6872: =item scantron_add_delay
                   6873: 
                   6874:    Adds an error message that occurred during the grading phase to a
                   6875:    queue of messages to be shown after grading pass is complete
                   6876: 
                   6877:  Arguments:
1.424     albertel 6878:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6879:    $scanline    - the scanline that caused the error
                   6880:    $errormesage - the error message
                   6881:    $errorcode   - a numeric code for the error
                   6882: 
                   6883:  Side Effects:
1.424     albertel 6884:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6885: 
                   6886: =cut
                   6887: 
1.82      albertel 6888: sub scantron_add_delay {
1.140     albertel 6889:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6890:     push(@$delayqueue,
                   6891: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6892: 	  'ecode' => $errorcode }
                   6893: 	 );
1.82      albertel 6894: }
                   6895: 
1.423     albertel 6896: =pod
                   6897: 
                   6898: =item scantron_find_student
                   6899: 
1.424     albertel 6900:    Finds the username for the current scanline
                   6901: 
                   6902:   Arguments:
                   6903:    $scantron_record - hash result from scantron_parse_scanline
                   6904:    $scan_data       - hash of correction information 
                   6905:                       (see &scantron_getfile() form more information)
                   6906:    $idmap           - hash from &username_to_idmap()
                   6907:    $line            - number of current scanline
                   6908:  
                   6909:   Returns:
                   6910:    Either 'username:domain' or undef if unknown
                   6911: 
1.423     albertel 6912: =cut
                   6913: 
1.82      albertel 6914: sub scantron_find_student {
1.157     albertel 6915:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6916:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6917:     if ($scanID =~ /^\s*$/) {
                   6918:  	return &scan_data($scan_data,"$line.user");
                   6919:     }
1.83      albertel 6920:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6921:  	if (lc($id) eq lc($scanID)) {
                   6922:  	    return $$idmap{$id};
                   6923:  	}
1.83      albertel 6924:     }
                   6925:     return undef;
                   6926: }
                   6927: 
1.423     albertel 6928: =pod
                   6929: 
                   6930: =item scantron_filter
                   6931: 
1.424     albertel 6932:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6933:    hidden resources was selected
                   6934: 
1.423     albertel 6935: =cut
                   6936: 
1.83      albertel 6937: sub scantron_filter {
                   6938:     my ($curres)=@_;
1.331     albertel 6939: 
                   6940:     if (ref($curres) && $curres->is_problem()) {
                   6941: 	# if the user has asked to not have either hidden
                   6942: 	# or 'randomout' controlled resources to be graded
                   6943: 	# don't include them
                   6944: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6945: 	    && $curres->randomout) {
                   6946: 	    return 0;
                   6947: 	}
1.83      albertel 6948: 	return 1;
                   6949:     }
                   6950:     return 0;
1.82      albertel 6951: }
                   6952: 
1.423     albertel 6953: =pod
                   6954: 
                   6955: =item scantron_process_corrections
                   6956: 
1.424     albertel 6957:    Gets correction information out of submitted form data and corrects
                   6958:    the scanline
                   6959: 
1.423     albertel 6960: =cut
                   6961: 
1.157     albertel 6962: sub scantron_process_corrections {
                   6963:     my ($r) = @_;
1.754     raeburn  6964:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6965:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6966:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6967:     my $which=$env{'form.scantron_line'};
1.200     albertel 6968:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6969:     my ($skip,$err,$errmsg);
1.257     albertel 6970:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6971: 	$skip=1;
1.257     albertel 6972:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6973: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6974: 	    $env{'form.scantron_domain'};
1.157     albertel 6975: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6976: 	($line,$err,$errmsg)=
                   6977: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6978: 				     'ID',{'newid'=>$newid,
1.257     albertel 6979: 				    'username'=>$env{'form.scantron_username'},
                   6980: 				    'domain'=>$env{'form.scantron_domain'}});
                   6981:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6982: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6983: 	my $newCODE;
1.192     albertel 6984: 	my %args;
1.190     albertel 6985: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6986: 	    $newCODE='use_unfound';
1.190     albertel 6987: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6988: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6989: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6990: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6991: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6992: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6993: 	}
1.257     albertel 6994: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6995: 	    $args{'CODE_ignore_dup'}=1;
                   6996: 	}
                   6997: 	$args{'CODE'}=$newCODE;
1.186     albertel 6998: 	($line,$err,$errmsg)=
                   6999: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7000: 				     'CODE',\%args);
1.257     albertel 7001:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7002: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7003: 	    ($line,$err,$errmsg)=
                   7004: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7005: 					 $which,'answer',
                   7006: 					 { 'question'=>$question,
1.503     raeburn  7007: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7008:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7009: 	    if ($err) { last; }
                   7010: 	}
                   7011:     }
                   7012:     if ($err) {
1.703     bisitz   7013:         $r->print(
                   7014:             '<p class="LC_error">'
                   7015:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7016:                 $errmsg)
1.704     raeburn  7017:            .'</p>');
1.157     albertel 7018:     } else {
1.200     albertel 7019: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7020: 	&scantron_putfile($scanlines,$scan_data);
                   7021:     }
                   7022: }
                   7023: 
1.423     albertel 7024: =pod
                   7025: 
                   7026: =item reset_skipping_status
                   7027: 
1.424     albertel 7028:    Forgets the current set of remember skipped scanlines (and thus
                   7029:    reverts back to considering all lines in the
                   7030:    scantron_skipped_<filename> file)
                   7031: 
1.423     albertel 7032: =cut
                   7033: 
1.200     albertel 7034: sub reset_skipping_status {
                   7035:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7036:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7037:     &scantron_putfile(undef,$scan_data);
                   7038: }
                   7039: 
1.423     albertel 7040: =pod
                   7041: 
                   7042: =item start_skipping
                   7043: 
1.424     albertel 7044:    Marks a scanline to be skipped. 
                   7045: 
1.423     albertel 7046: =cut
                   7047: 
1.376     albertel 7048: sub start_skipping {
1.200     albertel 7049:     my ($scan_data,$i)=@_;
                   7050:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7051:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7052: 	$remembered{$i}=2;
                   7053:     } else {
                   7054: 	$remembered{$i}=1;
                   7055:     }
1.200     albertel 7056:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7057: }
                   7058: 
1.423     albertel 7059: =pod
                   7060: 
                   7061: =item should_be_skipped
                   7062: 
1.424     albertel 7063:    Checks whether a scanline should be skipped.
                   7064: 
1.423     albertel 7065: =cut
                   7066: 
1.200     albertel 7067: sub should_be_skipped {
1.376     albertel 7068:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7069:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7070: 	# not redoing old skips
1.376     albertel 7071: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7072: 	return 0;
                   7073:     }
                   7074:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7075: 
                   7076:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7077: 	return 0;
                   7078:     }
1.200     albertel 7079:     return 1;
                   7080: }
                   7081: 
1.423     albertel 7082: =pod
                   7083: 
                   7084: =item remember_current_skipped
                   7085: 
1.424     albertel 7086:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7087:    file and remembers them into scan_data for later use.
                   7088: 
1.423     albertel 7089: =cut
                   7090: 
1.200     albertel 7091: sub remember_current_skipped {
                   7092:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7093:     my %to_remember;
                   7094:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7095: 	if ($scanlines->{'skipped'}[$i]) {
                   7096: 	    $to_remember{$i}=1;
                   7097: 	}
                   7098:     }
1.376     albertel 7099: 
1.200     albertel 7100:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7101:     &scantron_putfile(undef,$scan_data);
                   7102: }
                   7103: 
1.423     albertel 7104: =pod
                   7105: 
                   7106: =item check_for_error
                   7107: 
1.424     albertel 7108:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  7109:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7110:     something went wrong.
                   7111: 
1.423     albertel 7112: =cut
                   7113: 
1.200     albertel 7114: sub check_for_error {
                   7115:     my ($r,$result)=@_;
                   7116:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7117: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7118:     }
                   7119: }
1.157     albertel 7120: 
1.423     albertel 7121: =pod
                   7122: 
                   7123: =item scantron_warning_screen
                   7124: 
1.424     albertel 7125:    Interstitial screen to make sure the operator has selected the
                   7126:    correct options before we start the validation phase.
                   7127: 
1.423     albertel 7128: =cut
                   7129: 
1.203     albertel 7130: sub scantron_warning_screen {
1.650     raeburn  7131:     my ($button_text,$symb)=@_;
1.257     albertel 7132:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  7133:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7134:     my $CODElist;
1.284     albertel 7135:     if ($scantron_config{'CODElocation'} &&
                   7136: 	$scantron_config{'CODEstart'} &&
                   7137: 	$scantron_config{'CODElength'}) {
                   7138: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   7139: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7140: 	$CODElist=
1.492     albertel 7141: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7142: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7143:     }
1.663     raeburn  7144:     my $lastbubblepoints;
                   7145:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7146:         $lastbubblepoints =
                   7147:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7148:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7149:     }
1.770     raeburn  7150:     return '
1.203     albertel 7151: <p>
1.492     albertel 7152: <span class="LC_warning">
1.705     raeburn  7153: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7154: </p>
                   7155: <table>
1.492     albertel 7156: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7157: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  7158: '.$CODElist.$lastbubblepoints.'
1.203     albertel 7159: </table>
1.680     raeburn  7160: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  7161: '.&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  7162: ';
1.203     albertel 7163: }
                   7164: 
1.423     albertel 7165: =pod
                   7166: 
                   7167: =item scantron_do_warning
                   7168: 
1.424     albertel 7169:    Check if the operator has picked something for all required
                   7170:    fields. Error out if something is missing.
                   7171: 
1.423     albertel 7172: =cut
                   7173: 
1.203     albertel 7174: sub scantron_do_warning {
1.608     www      7175:     my ($r,$symb)=@_;
1.203     albertel 7176:     if (!$symb) {return '';}
1.324     albertel 7177:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7178:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7179:     if ( $env{'form.selectpage'} eq '' ||
                   7180: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7181: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7182: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7183: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7184: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7185: 	} 
1.257     albertel 7186: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7187: 	    $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  7188: 	}
1.257     albertel 7189: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7190: 	    $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  7191: 	}
1.237     albertel 7192:     } else {
1.650     raeburn  7193: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  7194:         my ($checksec,@possibles) = &gradable_sections();
                   7195:         my $gradesections;
                   7196:         if ($checksec) {
                   7197:             my $file=$env{'form.scantron_selectfile'};
                   7198:             if (&valid_file($file)) {
                   7199:                 my %bysec = &scantron_get_sections();
                   7200:                 my $table;
                   7201:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   7202:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   7203:                     $table = &Apache::loncommon::start_data_table()."\n".
                   7204:                              &Apache::loncommon::start_data_table_header_row().
                   7205:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   7206:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   7207:                     if ($bysec{'none'}) {
                   7208:                         $table .= &Apache::loncommon::start_data_table_row().
                   7209:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   7210:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7211:                     }
                   7212:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   7213:                         next if ($sec eq 'none');
                   7214:                         $table .= &Apache::loncommon::start_data_table_row().
                   7215:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   7216:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7217:                     }
                   7218:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   7219:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   7220:                                       '<p>'.$table.'</p>';
                   7221:                     if (@possibles) {
                   7222:                         $gradesections .= '<p>'.
                   7223:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   7224:                                               scalar(@possibles)).'<br />'.
                   7225:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   7226:                                               '<i>'.$checksec.'</i>').' ';
                   7227:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   7228:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   7229:                         }
                   7230:                         $gradesections .= '</p>';
                   7231:                     }
                   7232:                 }
                   7233:             } else {
                   7234:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   7235:             }
                   7236:         }
1.663     raeburn  7237:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7238: 	$r->print('
1.770     raeburn  7239: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 7240: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7241: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7242: ');
1.237     albertel 7243:     }
1.614     www      7244:     $r->print("</form><br />");
1.203     albertel 7245:     return '';
                   7246: }
                   7247: 
1.423     albertel 7248: =pod
                   7249: 
                   7250: =item scantron_form_start
                   7251: 
1.424     albertel 7252:     html hidden input for remembering all selected grading options
                   7253: 
1.423     albertel 7254: =cut
                   7255: 
1.203     albertel 7256: sub scantron_form_start {
                   7257:     my ($max_bubble)=@_;
                   7258:     my $result= <<SCANTRONFORM;
                   7259: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7260:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7261:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7262:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7263:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7264:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7265:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7266:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7267:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7268:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7269: SCANTRONFORM
1.447     foxr     7270: 
                   7271:   my $line = 0;
                   7272:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7273:        my $chunk =
                   7274: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7275:        $chunk .=
                   7276: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7277:        $chunk .= 
                   7278:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7279:        $chunk .=
                   7280:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7281:        $chunk .=
                   7282:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7283:        $result .= $chunk;
                   7284:        $line++;
1.691     raeburn  7285:     }
1.203     albertel 7286:     return $result;
                   7287: }
                   7288: 
1.423     albertel 7289: =pod
                   7290: 
                   7291: =item scantron_validate_file
                   7292: 
1.659     raeburn  7293:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7294: 
                   7295:     Also processes any necessary information resets that need to
                   7296:     occur before validation begins (ignore previous corrections,
                   7297:     restarting the skipped records processing)
                   7298: 
1.423     albertel 7299: =cut
                   7300: 
1.157     albertel 7301: sub scantron_validate_file {
1.608     www      7302:     my ($r,$symb) = @_;
1.157     albertel 7303:     if (!$symb) {return '';}
1.324     albertel 7304:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7305:     
1.703     bisitz   7306:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7307:     # them when doing the corrections reset
1.257     albertel 7308:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7309: 	&reset_skipping_status();
                   7310:     }
1.257     albertel 7311:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7312: 	&remember_current_skipped();
1.257     albertel 7313: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7314:     }
                   7315: 
1.257     albertel 7316:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7317: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7318: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7319: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7320: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7321:     }
1.200     albertel 7322: 
1.257     albertel 7323:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7324: 	&scantron_process_corrections($r);
                   7325:     }
1.770     raeburn  7326: 
                   7327:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   7328:     my ($checksec,@gradable);
                   7329:     if ($env{'request.course.sec'}) {
                   7330:         ($checksec,my @possibles) = &gradable_sections();
                   7331:         if ($checksec) {
                   7332:             if (@possibles) {
                   7333:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   7334:                 if (@chosensecs) {
                   7335:                     foreach my $sec (@chosensecs) {
                   7336:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   7337:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   7338:                                 push(@gradable,$sec);
                   7339:                             }
                   7340:                         }
                   7341:                     }
                   7342:                 }
                   7343:             }
                   7344:             $r->print('<p><table>');
                   7345:             if (@gradable) {
                   7346:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   7347:                 $r->print(
                   7348:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   7349:             } else {
                   7350:                 $r->print(
                   7351:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   7352:             }
                   7353:             $r->print('</table></p>');
                   7354:         }
                   7355:     }
                   7356:     $r->rflush();
                   7357: 
1.157     albertel 7358:     #get the student pick code ready
                   7359:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7360:     my $nav_error;
1.754     raeburn  7361:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7362:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7363:     if ($nav_error) {
                   7364:         $r->print(&navmap_errormsg());
                   7365:         return '';
                   7366:     }
1.203     albertel 7367:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7368:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7369:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7370:     }
1.157     albertel 7371:     $r->print($result);
                   7372:     
1.334     albertel 7373:     my @validate_phases=( 'sequence',
                   7374: 			  'ID',
1.157     albertel 7375: 			  'CODE',
                   7376: 			  'doublebubble',
                   7377: 			  'missingbubbles');
1.257     albertel 7378:     if (!$env{'form.validatepass'}) {
                   7379: 	$env{'form.validatepass'} = 0;
1.157     albertel 7380:     }
1.257     albertel 7381:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  7382:     my %skipbysec=();
1.448     foxr     7383: 
1.157     albertel 7384:     my $stop=0;
                   7385:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7386: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7387: 	$r->rflush();
1.691     raeburn  7388:      
1.157     albertel 7389: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7390: 	{
                   7391: 	    no strict 'refs';
1.770     raeburn  7392:             my @extras=();
                   7393:             if ($validate_phases[$currentphase] eq 'ID') {
                   7394:                 @extras = (\%skipbysec,$checksec,@gradable);
                   7395:             }
                   7396: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 7397: 	}
                   7398:     }
                   7399:     if (!$stop) {
1.650     raeburn  7400: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  7401:         my $secinfo;
                   7402:         if (keys(%skipbysec) > 0) {
                   7403:             my $seclist = '<ul>';
                   7404:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   7405:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   7406:             }
                   7407:             $seclist .= '</ul>';
                   7408:             $secinfo = '<p class="LC_info">'.
                   7409:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   7410:                            $seclist).
                   7411:                        '</p>';
                   7412:         }
1.542     raeburn  7413: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  7414:                   $secinfo.$warning.
1.542     raeburn  7415:                   &mt('Perform verification for each student after storage of submissions?').
                   7416:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7417:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7418:                   ('&nbsp;'x3).'<label>'.
                   7419:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7420:                   '</label></span><br />'.
                   7421:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7422:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7423:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7424:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7425:     } else {
                   7426: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7427: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7428:     }
                   7429:     if ($stop) {
1.334     albertel 7430: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7431: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7432: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7433: 
1.650     raeburn  7434: 	    $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 7435: 	} else {
1.503     raeburn  7436:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7437: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7438:             } else {
1.539     riegler  7439:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7440:             }
1.492     albertel 7441: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7442: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7443: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7444: 	}
1.157     albertel 7445:     }
1.614     www      7446:     $r->print(" </form><br />");
1.157     albertel 7447:     return '';
                   7448: }
                   7449: 
1.423     albertel 7450: 
                   7451: =pod
                   7452: 
                   7453: =item scantron_remove_file
                   7454: 
1.659     raeburn  7455:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7456:    scantron_original_<filename> is never removed
                   7457: 
                   7458: 
1.423     albertel 7459: =cut
                   7460: 
1.200     albertel 7461: sub scantron_remove_file {
1.192     albertel 7462:     my ($which)=@_;
1.257     albertel 7463:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7464:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7465:     my $file='scantron_';
1.200     albertel 7466:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7467: 	$file.=$which.'_';
1.192     albertel 7468:     } else {
                   7469: 	return 'refused';
                   7470:     }
1.257     albertel 7471:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7472:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7473: }
                   7474: 
1.423     albertel 7475: 
                   7476: =pod
                   7477: 
                   7478: =item scantron_remove_scan_data
                   7479: 
1.659     raeburn  7480:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7481:    data file.  (In the case that both the are doing skipped records we need
                   7482:    to remember the old skipped lines for the time being so that element
                   7483:    persists for a while.)
                   7484: 
1.423     albertel 7485: =cut
                   7486: 
1.200     albertel 7487: sub scantron_remove_scan_data {
1.257     albertel 7488:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7489:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7490:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7491:     my @todelete;
1.257     albertel 7492:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7493:     foreach my $key (@keys) {
                   7494: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7495: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7496: 		$key=~/remember_skipping/) {
                   7497: 		next;
                   7498: 	    }
1.192     albertel 7499: 	    push(@todelete,$key);
                   7500: 	}
                   7501:     }
1.200     albertel 7502:     my $result;
1.192     albertel 7503:     if (@todelete) {
1.491     albertel 7504: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7505: 				       \@todelete,$cdom,$cname);
                   7506:     } else {
                   7507: 	$result = 'ok';
1.192     albertel 7508:     }
                   7509:     return $result;
                   7510: }
                   7511: 
1.423     albertel 7512: 
                   7513: =pod
                   7514: 
                   7515: =item scantron_getfile
                   7516: 
1.659     raeburn  7517:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7518:     the scan_data hash
                   7519:   
                   7520:   Arguments:
                   7521:     None
                   7522: 
                   7523:   Returns:
                   7524:     2 hash references
                   7525: 
                   7526:      - first one has 
                   7527:          orig      -
                   7528:          corrected -
                   7529:          skipped   -  each of which points to an array ref of the specified
                   7530:                       file broken up into individual lines
                   7531:          count     - number of scanlines
                   7532:  
                   7533:      - second is the scan_data hash possible keys are
1.425     albertel 7534:        ($number refers to scanline numbered $number and thus the key affects
                   7535:         only that scanline
                   7536:         $bubline refers to the specific bubble line element and the aspects
                   7537:         refers to that specific bubble line element)
                   7538: 
                   7539:        $number.user - username:domain to use
                   7540:        $number.CODE_ignore_dup 
                   7541:                     - ignore the duplicate CODE error 
                   7542:        $number.useCODE
                   7543:                     - use the CODE in the scanline as is
                   7544:        $number.no_bubble.$bubline
                   7545:                     - it is valid that there is no bubbled in bubble
                   7546:                       at $number $bubline
                   7547:        remember_skipping
                   7548:                     - a frozen hash containing keys of $number and values
                   7549:                       of either 
                   7550:                         1 - we are on a 'do skipped records pass' and plan
                   7551:                             on processing this line
                   7552:                         2 - we are on a 'do skipped records pass' and this
                   7553:                             scanline has been marked to skip yet again
1.424     albertel 7554: 
1.423     albertel 7555: =cut
                   7556: 
1.157     albertel 7557: sub scantron_getfile {
1.200     albertel 7558:     #FIXME really would prefer a scantron directory
1.257     albertel 7559:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7560:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7561:     my $lines;
                   7562:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7563: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7564:     my %scanlines;
                   7565:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7566:     my $temp=$scanlines{'orig'};
                   7567:     $scanlines{'count'}=$#$temp;
                   7568: 
                   7569:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7570: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7571:     if ($lines eq '-1') {
                   7572: 	$scanlines{'corrected'}=[];
                   7573:     } else {
                   7574: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7575:     }
                   7576:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7577: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7578:     if ($lines eq '-1') {
                   7579: 	$scanlines{'skipped'}=[];
                   7580:     } else {
                   7581: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7582:     }
1.175     albertel 7583:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7584:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7585:     my %scan_data = @tmp;
                   7586:     return (\%scanlines,\%scan_data);
                   7587: }
                   7588: 
1.423     albertel 7589: =pod
                   7590: 
                   7591: =item lonnet_putfile
                   7592: 
1.424     albertel 7593:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7594: 
                   7595:  Arguments:
                   7596:    $contents - data to store
                   7597:    $filename - filename to store $contents into
                   7598: 
                   7599:  Returns:
                   7600:    result value from &Apache::lonnet::finishuserfileupload
                   7601: 
1.423     albertel 7602: =cut
                   7603: 
1.157     albertel 7604: sub lonnet_putfile {
                   7605:     my ($contents,$filename)=@_;
1.257     albertel 7606:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7607:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7608:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7609:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7610: 
                   7611: }
                   7612: 
1.423     albertel 7613: =pod
                   7614: 
                   7615: =item scantron_putfile
                   7616: 
1.659     raeburn  7617:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7618:     scan_data hash. (Does not modify the original version only the
                   7619:     corrected and skipped versions.
                   7620: 
                   7621:  Arguments:
                   7622:     $scanlines - hash ref that looks like the first return value from
                   7623:                  &scantron_getfile()
                   7624:     $scan_data - hash ref that looks like the second return value from
                   7625:                  &scantron_getfile()
                   7626: 
1.423     albertel 7627: =cut
                   7628: 
1.157     albertel 7629: sub scantron_putfile {
                   7630:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7631:     #FIXME really would prefer a scantron directory
1.257     albertel 7632:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7633:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7634:     if ($scanlines) {
                   7635: 	my $prefix='scantron_';
1.157     albertel 7636: # no need to update orig, shouldn't change
                   7637: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7638: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7639: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7640: 			$prefix.'corrected_'.
1.257     albertel 7641: 			$env{'form.scantron_selectfile'});
1.200     albertel 7642: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7643: 			$prefix.'skipped_'.
1.257     albertel 7644: 			$env{'form.scantron_selectfile'});
1.200     albertel 7645:     }
1.175     albertel 7646:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7647: }
                   7648: 
1.423     albertel 7649: =pod
                   7650: 
                   7651: =item scantron_get_line
                   7652: 
1.424     albertel 7653:    Returns the correct version of the scanline
                   7654: 
                   7655:  Arguments:
                   7656:     $scanlines - hash ref that looks like the first return value from
                   7657:                  &scantron_getfile()
                   7658:     $scan_data - hash ref that looks like the second return value from
                   7659:                  &scantron_getfile()
                   7660:     $i         - number of the requested line (starts at 0)
                   7661: 
                   7662:  Returns:
                   7663:    A scanline, (either the original or the corrected one if it
                   7664:    exists), or undef if the requested scanline should be
                   7665:    skipped. (Either because it's an skipped scanline, or it's an
                   7666:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7667:    pass.
                   7668: 
1.423     albertel 7669: =cut
                   7670: 
1.157     albertel 7671: sub scantron_get_line {
1.200     albertel 7672:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7673:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7674:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7675:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7676:     return $scanlines->{'orig'}[$i]; 
                   7677: }
                   7678: 
1.423     albertel 7679: =pod
                   7680: 
                   7681: =item scantron_todo_count
                   7682: 
1.424     albertel 7683:     Counts the number of scanlines that need processing.
                   7684: 
                   7685:  Arguments:
                   7686:     $scanlines - hash ref that looks like the first return value from
                   7687:                  &scantron_getfile()
                   7688:     $scan_data - hash ref that looks like the second return value from
                   7689:                  &scantron_getfile()
                   7690: 
                   7691:  Returns:
                   7692:     $count - number of scanlines to process
                   7693: 
1.423     albertel 7694: =cut
                   7695: 
1.200     albertel 7696: sub get_todo_count {
                   7697:     my ($scanlines,$scan_data)=@_;
                   7698:     my $count=0;
                   7699:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7700: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7701: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7702: 	$count++;
                   7703:     }
                   7704:     return $count;
                   7705: }
                   7706: 
1.423     albertel 7707: =pod
                   7708: 
                   7709: =item scantron_put_line
                   7710: 
1.659     raeburn  7711:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7712:     data file.
                   7713: 
                   7714:  Arguments:
                   7715:     $scanlines - hash ref that looks like the first return value from
                   7716:                  &scantron_getfile()
                   7717:     $scan_data - hash ref that looks like the second return value from
                   7718:                  &scantron_getfile()
                   7719:     $i         - line number to update
                   7720:     $newline   - contents of the updated scanline
                   7721:     $skip      - if true make the line for skipping and update the
                   7722:                  'skipped' file
                   7723: 
1.423     albertel 7724: =cut
                   7725: 
1.157     albertel 7726: sub scantron_put_line {
1.200     albertel 7727:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7728:     if ($skip) {
                   7729: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7730: 	&start_skipping($scan_data,$i);
1.157     albertel 7731: 	return;
                   7732:     }
                   7733:     $scanlines->{'corrected'}[$i]=$newline;
                   7734: }
                   7735: 
1.423     albertel 7736: =pod
                   7737: 
                   7738: =item scantron_clear_skip
                   7739: 
1.424     albertel 7740:    Remove a line from the 'skipped' file
                   7741: 
                   7742:  Arguments:
                   7743:     $scanlines - hash ref that looks like the first return value from
                   7744:                  &scantron_getfile()
                   7745:     $scan_data - hash ref that looks like the second return value from
                   7746:                  &scantron_getfile()
                   7747:     $i         - line number to update
                   7748: 
1.423     albertel 7749: =cut
                   7750: 
1.376     albertel 7751: sub scantron_clear_skip {
                   7752:     my ($scanlines,$scan_data,$i)=@_;
                   7753:     if (exists($scanlines->{'skipped'}[$i])) {
                   7754: 	undef($scanlines->{'skipped'}[$i]);
                   7755: 	return 1;
                   7756:     }
                   7757:     return 0;
                   7758: }
                   7759: 
1.423     albertel 7760: =pod
                   7761: 
                   7762: =item scantron_filter_not_exam
                   7763: 
1.424     albertel 7764:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7765:    filter out resources that are not marked as 'exam' mode
                   7766: 
1.423     albertel 7767: =cut
                   7768: 
1.334     albertel 7769: sub scantron_filter_not_exam {
                   7770:     my ($curres)=@_;
                   7771:     
                   7772:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7773: 	# if the user has asked to not have either hidden
                   7774: 	# or 'randomout' controlled resources to be graded
                   7775: 	# don't include them
                   7776: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7777: 	    && $curres->randomout) {
                   7778: 	    return 0;
                   7779: 	}
                   7780: 	return 1;
                   7781:     }
                   7782:     return 0;
                   7783: }
                   7784: 
1.423     albertel 7785: =pod
                   7786: 
                   7787: =item scantron_validate_sequence
                   7788: 
1.424     albertel 7789:     Validates the selected sequence, checking for resource that are
                   7790:     not set to exam mode.
                   7791: 
1.423     albertel 7792: =cut
                   7793: 
1.334     albertel 7794: sub scantron_validate_sequence {
                   7795:     my ($r,$currentphase) = @_;
                   7796: 
                   7797:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7798:     unless (ref($navmap)) {
                   7799:         $r->print(&navmap_errormsg());
                   7800:         return (1,$currentphase);
                   7801:     }
1.334     albertel 7802:     my (undef,undef,$sequence)=
                   7803: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7804: 
                   7805:     my $map=$navmap->getResourceByUrl($sequence);
                   7806: 
                   7807:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7808:                                     value="ignore" />');
                   7809:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7810: 	my @resources=
                   7811: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7812: 	if (@resources) {
1.675     bisitz   7813: 	    $r->print(
                   7814:                 '<p class="LC_warning">'
                   7815:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7816:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7817:                    .' work correctly.')
                   7818:                .'</p>'
                   7819:             );
1.334     albertel 7820: 	    return (1,$currentphase);
                   7821: 	}
                   7822:     }
                   7823: 
                   7824:     return (0,$currentphase+1);
                   7825: }
                   7826: 
1.423     albertel 7827: 
                   7828: 
1.157     albertel 7829: sub scantron_validate_ID {
1.770     raeburn  7830:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 7831:     
                   7832:     #get student info
                   7833:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7834:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  7835:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 7836: 
                   7837:     #get scantron line setup
1.754     raeburn  7838:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7839:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7840: 
                   7841:     my $nav_error;
1.649     raeburn  7842:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7843:     if ($nav_error) {
                   7844:         $r->print(&navmap_errormsg());
                   7845:         return(1,$currentphase);
                   7846:     }
1.157     albertel 7847: 
                   7848:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  7849:     my $unsavedskips = 0;
1.157     albertel 7850:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7851: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7852: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7853: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7854: 						 $scan_data);
                   7855: 	my $id=$$scan_record{'scantron.ID'};
                   7856: 	my $found;
                   7857: 	foreach my $checkid (keys(%idmap)) {
                   7858: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7859: 	}
                   7860: 	if ($found) {
                   7861: 	    my $username=$idmap{$found};
1.770     raeburn  7862:             if ($checksec) {
                   7863:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   7864:                     my $stusec = $classlist->{$username}->[$secidx];
                   7865:                     if ($stusec ne $checksec) {
                   7866:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7867:                             my $skip=1;
                   7868:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7869:                             if (ref($skipbysec) eq 'HASH') {
                   7870:                                 if ($stusec eq '') {
                   7871:                                     $skipbysec->{'none'} ++;
                   7872:                                 } else {
                   7873:                                     $skipbysec->{$stusec} ++;
                   7874:                                 }
                   7875:                             }
                   7876:                             $unsavedskips ++;
                   7877:                             next;
                   7878:                         }
                   7879:                     }
                   7880:                 }
                   7881:             }
1.157     albertel 7882: 	    if ($found{'ids'}{$found}) {
                   7883: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7884: 					 $line,'duplicateID',$found);
1.770     raeburn  7885:                 if ($unsavedskips) {
                   7886:                     &scantron_putfile($scanlines,$scan_data);
                   7887:                     $unsavedskips = 0;
                   7888:                 }
1.194     albertel 7889: 		return(1,$currentphase);
1.157     albertel 7890: 	    } elsif ($found{'usernames'}{$username}) {
                   7891: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7892: 					 $line,'duplicateID',$username);
1.770     raeburn  7893:                 if ($unsavedskips) {
                   7894:                     &scantron_putfile($scanlines,$scan_data);
                   7895:                     $unsavedskips = 0;
                   7896:                 }
1.194     albertel 7897: 		return(1,$currentphase);
1.157     albertel 7898: 	    }
1.186     albertel 7899: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7900: 	    $found{'ids'}{$found}++;
                   7901: 	    $found{'usernames'}{$username}++;
                   7902: 	} else {
                   7903: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7904: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  7905:                 if (($checksec && $username ne '')) {
                   7906:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   7907:                         my $stusec = $classlist->{$username}->[$secidx];
                   7908:                         if ($stusec ne $checksec) {
                   7909:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7910:                                 my $skip=1;
                   7911:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7912:                                 if (ref($skipbysec) eq 'HASH') {
                   7913:                                     if ($stusec eq '') {
                   7914:                                         $skipbysec->{'none'} ++;
                   7915:                                     } else {
                   7916:                                         $skipbysec->{$stusec} ++;
                   7917:                                     }
                   7918:                                 }
                   7919:                                 $unsavedskips ++;
                   7920:                                 next;
                   7921:                             }
                   7922:                         }
                   7923:                     }
                   7924: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 7925: 		    &scantron_get_correction($r,$i,$scan_record,
                   7926: 					     \%scantron_config,
                   7927: 					     $line,'duplicateID',$username);
1.770     raeburn  7928:                     if ($unsavedskips) {
                   7929:                         &scantron_putfile($scanlines,$scan_data);
                   7930:                         $unsavedskips = 0;
                   7931:                     }
1.194     albertel 7932: 		    return(1,$currentphase);
1.157     albertel 7933: 		} elsif (!defined($username)) {
                   7934: 		    &scantron_get_correction($r,$i,$scan_record,
                   7935: 					     \%scantron_config,
                   7936: 					     $line,'incorrectID');
1.770     raeburn  7937:                     if ($unsavedskips) {
                   7938:                         &scantron_putfile($scanlines,$scan_data);
                   7939:                         $unsavedskips = 0;
                   7940:                     }
1.194     albertel 7941: 		    return(1,$currentphase);
1.157     albertel 7942: 		}
                   7943: 		$found{'usernames'}{$username}++;
                   7944: 	    } else {
                   7945: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7946: 					 $line,'incorrectID');
1.770     raeburn  7947:                 if ($unsavedskips) {
                   7948:                     &scantron_putfile($scanlines,$scan_data);
                   7949:                     $unsavedskips = 0;
                   7950:                 }
1.194     albertel 7951: 		return(1,$currentphase);
1.157     albertel 7952: 	    }
                   7953: 	}
                   7954:     }
1.770     raeburn  7955:     if ($unsavedskips) {
                   7956:         &scantron_putfile($scanlines,$scan_data);
                   7957:         $unsavedskips = 0;
                   7958:     }
1.157     albertel 7959:     return (0,$currentphase+1);
                   7960: }
                   7961: 
1.770     raeburn  7962: sub scantron_get_sections {
                   7963:     my %bysec;
                   7964:     if ($env{'form.scantron_format'} ne '') {
                   7965:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   7966:         my ($scanlines,$scan_data)=&scantron_getfile();
                   7967:         my $classlist=&Apache::loncoursedata::get_classlist();
                   7968:         my %idmap=&username_to_idmap($classlist);
                   7969:         foreach my $key (keys(%idmap)) {
                   7970:             my $lckey = lc($key);
                   7971:             $idmap{$lckey} = $idmap{$key};
                   7972:         }
                   7973:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   7974:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7975:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7976:             if ($line=~/^[\s\cz]*$/) { next; }
                   7977:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7978:                                                      $scan_data);
                   7979:             my $id=lc($$scan_record{'scantron.ID'});
                   7980:             if (exists($idmap{$id})) {
                   7981:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   7982:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   7983:                     if ($stusec eq '') {
                   7984:                         $bysec{'none'} ++;
                   7985:                     } else {
                   7986:                         $bysec{$stusec} ++;
                   7987:                     }
                   7988:                 }
                   7989:             }
                   7990:         }
                   7991:     }
                   7992:     return %bysec;
                   7993: }
1.423     albertel 7994: 
1.157     albertel 7995: sub scantron_get_correction {
1.691     raeburn  7996:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7997:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7998: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7999: #to show both the current line and the previous one and allow skipping
                   8000: #the previous one or the current one
                   8001: 
1.333     albertel 8002:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   8003:         $r->print(
                   8004:             '<p class="LC_warning">'
                   8005:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   8006:                 "<b>$error</b>",
                   8007:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   8008:            ."</p> \n");
1.157     albertel 8009:     } else {
1.658     bisitz   8010:         $r->print(
                   8011:             '<p class="LC_warning">'
                   8012:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8013:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8014:            ."</p> \n");
                   8015:     }
                   8016:     my $message =
                   8017:         '<p>'
                   8018:        .&mt('The ID on the form is [_1]',
                   8019:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8020:        .'<br />'
1.665     raeburn  8021:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   8022:             $$scan_record{'scantron.LastName'},
                   8023:             $$scan_record{'scantron.FirstName'})
                   8024:        .'</p>';
1.242     albertel 8025: 
1.157     albertel 8026:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8027:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8028:                            # Array populated for doublebubble or
                   8029:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8030:                            # to validate radio button checking   
                   8031: 
1.157     albertel 8032:     if ($error =~ /ID$/) {
1.186     albertel 8033: 	if ($error eq 'incorrectID') {
1.658     bisitz   8034:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8035: 		      "</p>\n");
1.157     albertel 8036: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   8037:             $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 8038: 	}
1.242     albertel 8039: 	$r->print($message);
1.492     albertel 8040: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8041: 	$r->print("\n<ul><li> ");
                   8042: 	#FIXME it would be nice if this sent back the user ID and
                   8043: 	#could do partial userID matches
                   8044: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8045: 				       'scantron_username','scantron_domain'));
                   8046: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   8047: 	$r->print("\n:\n".
1.257     albertel 8048: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8049: 
                   8050: 	$r->print('</li>');
1.186     albertel 8051:     } elsif ($error =~ /CODE$/) {
                   8052: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   8053: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8054: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   8055: 	    $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 8056: 	}
1.658     bisitz   8057: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   8058: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8059:                  ."</p>\n");
1.242     albertel 8060: 	$r->print($message);
1.658     bisitz   8061: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8062: 	$r->print("\n<br /> ");
1.194     albertel 8063: 	my $i=0;
1.273     albertel 8064: 	if ($error eq 'incorrectCODE' 
                   8065: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8066: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8067: 	    if ($closest > 0) {
                   8068: 		foreach my $testcode (@{$closest}) {
                   8069: 		    my $checked='';
1.569     bisitz   8070: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8071: 		    $r->print("
                   8072:    <label>
1.569     bisitz   8073:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8074:        ".&mt("Use the similar CODE [_1] instead.",
                   8075: 	    "<b><tt>".$testcode."</tt></b>")."
                   8076:     </label>
                   8077:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8078: 		    $r->print("\n<br />");
                   8079: 		    $i++;
                   8080: 		}
1.194     albertel 8081: 	    }
                   8082: 	}
1.273     albertel 8083: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8084: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8085: 	    $r->print("
                   8086:     <label>
1.569     bisitz   8087:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  8088:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8089: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8090:     </label>");
1.273     albertel 8091: 	    $r->print("\n<br />");
                   8092: 	}
1.194     albertel 8093: 
1.597     wenzelju 8094: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8095: function change_radio(field) {
1.190     albertel 8096:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8097:     var i;
                   8098:     for (i=0;i<slct.length;i++) {
                   8099:         if (slct[i].value==field) { slct[i].checked=true; }
                   8100:     }
                   8101: }
                   8102: ENDSCRIPT
1.187     albertel 8103: 	my $href="/adm/pickcode?".
1.359     www      8104: 	   "form=".&escape("scantronupload").
                   8105: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8106: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8107: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8108: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8109: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8110: 	    $r->print("
                   8111:     <label>
                   8112:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8113:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8114: 	     "<a target='_blank' href='$href'>","</a>")."
                   8115:     </label> 
1.558     bisitz   8116:     ".&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 8117: 	    $r->print("\n<br />");
                   8118: 	}
1.492     albertel 8119: 	$r->print("
                   8120:     <label>
                   8121:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8122:        ".&mt("Use [_1] as the CODE.",
                   8123: 	     "</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 8124: 	$r->print("\n<br /><br />");
1.157     albertel 8125:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   8126: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8127: 
                   8128: 	# The form field scantron_questions is acutally a list of line numbers.
                   8129: 	# represented by this form so:
                   8130: 
1.691     raeburn  8131: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8132:                                                 $respnumlookup,$startline);
1.497     foxr     8133: 
1.157     albertel 8134: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8135: 		  $line_list.'" />');
1.242     albertel 8136: 	$r->print($message);
1.492     albertel 8137: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8138: 	foreach my $question (@{$arg}) {
1.503     raeburn  8139: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8140:                                                    $scan_record, $error,
                   8141:                                                    $randomorder,$randompick,
                   8142:                                                    $respnumlookup,$startline);
1.524     raeburn  8143:             push(@lines_to_correct,@linenums);
1.157     albertel 8144: 	}
1.503     raeburn  8145:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8146:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   8147: 	$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 8148: 	$r->print($message);
1.492     albertel 8149: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8150: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8151: 
1.503     raeburn  8152: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8153: 	# a list of question numbers. Therefore:
                   8154: 	#
1.691     raeburn  8155: 
                   8156: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8157:                                                 $respnumlookup,$startline);
1.497     foxr     8158: 
1.157     albertel 8159: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8160: 		  $line_list.'" />');
1.157     albertel 8161: 	foreach my $question (@{$arg}) {
1.503     raeburn  8162: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8163:                                                    $scan_record, $error,
                   8164:                                                    $randomorder,$randompick,
                   8165:                                                    $respnumlookup,$startline);
1.524     raeburn  8166:             push(@lines_to_correct,@linenums);
1.157     albertel 8167: 	}
1.503     raeburn  8168:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8169:     } else {
                   8170: 	$r->print("\n<ul>");
                   8171:     }
                   8172:     $r->print("\n</li></ul>");
1.497     foxr     8173: }
                   8174: 
1.503     raeburn  8175: sub verify_bubbles_checked {
                   8176:     my (@ansnums) = @_;
                   8177:     my $ansnumstr = join('","',@ansnums);
                   8178:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  8179:     &js_escape(\$warning);
1.767     raeburn  8180:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8181: function verify_bubble_radio(form) {
                   8182:     var ansnumArray = new Array ("$ansnumstr");
                   8183:     var need_bubble_count = 0;
                   8184:     for (var i=0; i<ansnumArray.length; i++) {
                   8185:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8186:             var bubble_picked = 0; 
                   8187:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8188:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8189:                     bubble_picked = 1;
                   8190:                 }
                   8191:             }
                   8192:             if (bubble_picked == 0) {
                   8193:                 need_bubble_count ++;
                   8194:             }
                   8195:         }
                   8196:     }
                   8197:     if (need_bubble_count) {
                   8198:         alert("$warning");
                   8199:         return;
                   8200:     }
                   8201:     form.submit(); 
                   8202: }
                   8203: ENDSCRIPT
                   8204:     return $output;
                   8205: }
                   8206: 
1.497     foxr     8207: =pod
                   8208: 
                   8209: =item  questions_to_line_list
1.157     albertel 8210: 
1.497     foxr     8211: Converts a list of questions into a string of comma separated
                   8212: line numbers in the answer sheet used by the questions.  This is
                   8213: used to fill in the scantron_questions form field.
                   8214: 
                   8215:   Arguments:
                   8216:      questions    - Reference to an array of questions.
1.691     raeburn  8217:      randomorder  - True if randomorder in use.
                   8218:      randompick   - True if randompick in use.
                   8219:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8220:                      for current line to question number used for same question
                   8221:                      in "Master Seqence" (as seen by Course Coordinator).
                   8222:      startline    - Reference to hash where key is question number (0 is first)
                   8223:                     and key is number of first bubble line for current student
                   8224:                     or code-based randompick and/or randomorder.
1.693     raeburn  8225: 
1.497     foxr     8226: =cut
                   8227: 
                   8228: 
                   8229: sub questions_to_line_list {
1.691     raeburn  8230:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8231:     my @lines;
                   8232: 
1.503     raeburn  8233:     foreach my $item (@{$questions}) {
                   8234:         my $question = $item;
                   8235:         my ($first,$count,$last);
                   8236:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8237:             $question = $1;
                   8238:             my $subquestion = $2;
1.691     raeburn  8239:             my $responsenum = $question-1;
                   8240:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8241:                 $responsenum = $respnumlookup->{$question-1};
                   8242:                 if (ref($startline) eq 'HASH') {
                   8243:                     $first = $startline->{$question-1} + 1;
                   8244:                 }
                   8245:             } else {
                   8246:                 $first = $first_bubble_line{$responsenum} + 1;
                   8247:             }
                   8248:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8249:             my $subcount = 1;
                   8250:             while ($subcount<$subquestion) {
                   8251:                 $first += $subans[$subcount-1];
                   8252:                 $subcount ++;
                   8253:             }
                   8254:             $count = $subans[$subquestion-1];
                   8255:         } else {
1.691     raeburn  8256:             my $responsenum = $question-1;
                   8257:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8258:                 $responsenum = $respnumlookup->{$question-1};
                   8259:                 if (ref($startline) eq 'HASH') {
                   8260:                     $first = $startline->{$question-1} + 1;
                   8261:                 }
                   8262:             } else {
                   8263:                 $first = $first_bubble_line{$responsenum} + 1;
                   8264:             }
                   8265: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8266:         }
1.506     raeburn  8267:         $last = $first+$count-1;
1.503     raeburn  8268:         push(@lines, ($first..$last));
1.497     foxr     8269:     }
                   8270:     return join(',', @lines);
                   8271: }
                   8272: 
                   8273: =pod 
                   8274: 
                   8275: =item prompt_for_corrections
                   8276: 
                   8277: Prompts for a potentially multiline correction to the
                   8278: user's bubbling (factors out common code from scantron_get_correction
                   8279: for multi and missing bubble cases).
                   8280: 
                   8281:  Arguments:
                   8282:    $r           - Apache request object.
                   8283:    $question    - The question number to prompt for.
                   8284:    $scan_config - The scantron file configuration hash.
                   8285:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8286:    $error       - Type of error
1.691     raeburn  8287:    $randomorder - True if randomorder in use.
                   8288:    $randompick  - True if randompick in use.
                   8289:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8290:                     for current line to question number used for same question
                   8291:                     in "Master Seqence" (as seen by Course Coordinator).
                   8292:    $startline   - Reference to hash where key is question number (0 is first)
                   8293:                   and value is number of first bubble line for current student
                   8294:                   or code-based randompick and/or randomorder.
                   8295: 
1.497     foxr     8296: 
                   8297:  Implicit inputs:
                   8298:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8299:                                   Numbered from 0 (but question numbers are from
                   8300:                                   1.
                   8301:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8302:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8303:                                   type problems render as separate sub-questions, 
1.503     raeburn  8304:                                   in exam mode. This hash contains a 
                   8305:                                   comma-separated list of the lines per 
                   8306:                                   sub-question.
1.510     raeburn  8307:    %responsetype_per_response   - essayresponse, formularesponse,
                   8308:                                   stringresponse, imageresponse, reactionresponse,
                   8309:                                   and organicresponse type problem parts can have
1.503     raeburn  8310:                                   multiple lines per response if the weight
                   8311:                                   assigned exceeds 10.  In this case, only
                   8312:                                   one bubble per line is permitted, but more 
                   8313:                                   than one line might contain bubbles, e.g.
                   8314:                                   bubbling of: line 1 - J, line 2 - J, 
                   8315:                                   line 3 - B would assign 22 points.  
1.497     foxr     8316: 
                   8317: =cut
                   8318: 
                   8319: sub prompt_for_corrections {
1.691     raeburn  8320:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8321:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8322:     my ($current_line,$lines);
                   8323:     my @linenums;
                   8324:     my $questionnum = $question;
1.691     raeburn  8325:     my ($first,$responsenum);
1.503     raeburn  8326:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8327:         $question = $1;
                   8328:         my $subquestion = $2;
1.691     raeburn  8329:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8330:             $responsenum = $respnumlookup->{$question-1};
                   8331:             if (ref($startline) eq 'HASH') {
                   8332:                 $first = $startline->{$question-1};
                   8333:             }
                   8334:         } else {
                   8335:             $responsenum = $question-1;
1.714     raeburn  8336:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8337:         }
                   8338:         $current_line = $first + 1 ;
                   8339:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8340:         my $subcount = 1;
                   8341:         while ($subcount<$subquestion) {
                   8342:             $current_line += $subans[$subcount-1];
                   8343:             $subcount ++;
                   8344:         }
                   8345:         $lines = $subans[$subquestion-1];
                   8346:     } else {
1.691     raeburn  8347:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8348:             $responsenum = $respnumlookup->{$question-1};
                   8349:             if (ref($startline) eq 'HASH') { 
                   8350:                 $first = $startline->{$question-1};
                   8351:             }
                   8352:         } else {
                   8353:             $responsenum = $question-1;
                   8354:             $first = $first_bubble_line{$responsenum};
                   8355:         }
                   8356:         $current_line = $first + 1;
                   8357:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8358:     }
1.497     foxr     8359:     if ($lines > 1) {
1.503     raeburn  8360:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8361:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8362:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8363:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8364:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8365:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8366:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8367:             $r->print(
                   8368:                 &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)
                   8369:                .'<br /><br />'
                   8370:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8371:                .'<br />'
                   8372:                .&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.')
                   8373:                .'<br />'
                   8374:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8375:                .'<br /><br />'
                   8376:             );
1.503     raeburn  8377:         } else {
                   8378:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8379:         }
1.497     foxr     8380:     }
                   8381:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8382:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8383: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8384: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8385:         push(@linenums,$current_line);
1.497     foxr     8386: 	$current_line++;
                   8387:     }
                   8388:     if ($lines > 1) {
                   8389: 	$r->print("<hr /><br />");
                   8390:     }
1.503     raeburn  8391:     return @linenums;
1.157     albertel 8392: }
1.423     albertel 8393: 
                   8394: =pod
                   8395: 
                   8396: =item scantron_bubble_selector
                   8397:   
                   8398:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8399:    possibly showing the existing the selected bubbles if known
1.423     albertel 8400: 
                   8401:  Arguments:
                   8402:     $r           - Apache request object
1.754     raeburn  8403:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8404:     $line        - Number of the line being displayed.
1.503     raeburn  8405:     $questionnum - Question number (may include subquestion)
                   8406:     $error       - Type of error.
1.497     foxr     8407:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8408: 
                   8409: =cut
                   8410: 
1.157     albertel 8411: sub scantron_bubble_selector {
1.503     raeburn  8412:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8413:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8414: 
                   8415:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8416:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8417:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8418:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8419:             $max=$$scan_config{'BubblesPerRow'};
                   8420:             if (($scmode eq 'number') && ($max > 10)) {
                   8421:                 $max = 10;
                   8422:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8423:                 $max = 26;
                   8424:             }
                   8425:         } else {
                   8426:             $max = 10;
                   8427:         }
                   8428:     }
1.274     albertel 8429: 
1.157     albertel 8430:     my @alphabet=('A'..'Z');
1.503     raeburn  8431:     $r->print(&Apache::loncommon::start_data_table().
                   8432:               &Apache::loncommon::start_data_table_row());
                   8433:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8434:     for (my $i=0;$i<$max+1;$i++) {
                   8435: 	$r->print("\n".'<td align="center">');
                   8436: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8437: 	else { $r->print('&nbsp;'); }
                   8438: 	$r->print('</td>');
                   8439:     }
1.503     raeburn  8440:     $r->print(&Apache::loncommon::end_data_table_row().
                   8441:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8442:     for (my $i=0;$i<$max;$i++) {
                   8443: 	$r->print("\n".
                   8444: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8445: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8446:     }
1.503     raeburn  8447:     my $nobub_checked = ' ';
                   8448:     if ($error eq 'missingbubble') {
                   8449:         $nobub_checked = ' checked = "checked" ';
                   8450:     }
                   8451:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8452: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8453:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8454:               $line.'" value="'.$questionnum.'" /></td>');
                   8455:     $r->print(&Apache::loncommon::end_data_table_row().
                   8456:               &Apache::loncommon::end_data_table());
1.157     albertel 8457: }
                   8458: 
1.423     albertel 8459: =pod
                   8460: 
                   8461: =item num_matches
                   8462: 
1.424     albertel 8463:    Counts the number of characters that are the same between the two arguments.
                   8464: 
                   8465:  Arguments:
                   8466:    $orig - CODE from the scanline
                   8467:    $code - CODE to match against
                   8468: 
                   8469:  Returns:
                   8470:    $count - integer count of the number of same characters between the
                   8471:             two arguments
                   8472: 
1.423     albertel 8473: =cut
                   8474: 
1.194     albertel 8475: sub num_matches {
                   8476:     my ($orig,$code) = @_;
                   8477:     my @code=split(//,$code);
                   8478:     my @orig=split(//,$orig);
                   8479:     my $same=0;
                   8480:     for (my $i=0;$i<scalar(@code);$i++) {
                   8481: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8482:     }
                   8483:     return $same;
                   8484: }
                   8485: 
1.423     albertel 8486: =pod
                   8487: 
                   8488: =item scantron_get_closely_matching_CODEs
                   8489: 
1.424     albertel 8490:    Cycles through all CODEs and finds the set that has the greatest
                   8491:    number of same characters as the provided CODE
                   8492: 
                   8493:  Arguments:
                   8494:    $allcodes - hash ref returned by &get_codes()
                   8495:    $CODE     - CODE from the current scanline
                   8496: 
                   8497:  Returns:
                   8498:    2 element list
                   8499:     - first elements is number of how closely matching the best fit is 
                   8500:       (5 means best set has 5 matching characters)
                   8501:     - second element is an arrary ref containing the set of valid CODEs
                   8502:       that best fit the passed in CODE
                   8503: 
1.423     albertel 8504: =cut
                   8505: 
1.194     albertel 8506: sub scantron_get_closely_matching_CODEs {
                   8507:     my ($allcodes,$CODE)=@_;
                   8508:     my @CODEs;
                   8509:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8510: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8511:     }
                   8512: 
                   8513:     return ($#CODEs,$CODEs[-1]);
                   8514: }
                   8515: 
1.423     albertel 8516: =pod
                   8517: 
                   8518: =item get_codes
                   8519: 
1.424     albertel 8520:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8521:    set of remembered CODEs.
                   8522: 
                   8523:  Arguments:
                   8524:   $old_name - name of the set of remembered CODEs
                   8525:   $cdom     - domain of the course
                   8526:   $cnum     - internal course name
                   8527: 
                   8528:  Returns:
                   8529:   %allcodes - keys are the valid CODEs, values are all 1
                   8530: 
1.423     albertel 8531: =cut
                   8532: 
1.194     albertel 8533: sub get_codes {
1.280     foxr     8534:     my ($old_name, $cdom, $cnum) = @_;
                   8535:     if (!$old_name) {
                   8536: 	$old_name=$env{'form.scantron_CODElist'};
                   8537:     }
                   8538:     if (!$cdom) {
                   8539: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8540:     }
                   8541:     if (!$cnum) {
                   8542: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8543:     }
1.278     albertel 8544:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8545: 				    $cdom,$cnum);
                   8546:     my %allcodes;
                   8547:     if ($result{"type\0$old_name"} eq 'number') {
                   8548: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8549:     } else {
                   8550: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8551:     }
1.194     albertel 8552:     return %allcodes;
                   8553: }
                   8554: 
1.423     albertel 8555: =pod
                   8556: 
                   8557: =item scantron_validate_CODE
                   8558: 
1.424     albertel 8559:    Validates all scanlines in the selected file to not have any
                   8560:    invalid or underspecified CODEs and that none of the codes are
                   8561:    duplicated if this was requested.
                   8562: 
1.423     albertel 8563: =cut
                   8564: 
1.157     albertel 8565: sub scantron_validate_CODE {
                   8566:     my ($r,$currentphase) = @_;
1.754     raeburn  8567:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8568:     if ($scantron_config{'CODElocation'} &&
                   8569: 	$scantron_config{'CODEstart'} &&
                   8570: 	$scantron_config{'CODElength'}) {
1.257     albertel 8571: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8572: 	    &FIXME_blow_up()
                   8573: 	}
                   8574:     } else {
                   8575: 	return (0,$currentphase+1);
                   8576:     }
                   8577:     
                   8578:     my %usedCODEs;
                   8579: 
1.194     albertel 8580:     my %allcodes=&get_codes();
1.186     albertel 8581: 
1.582     raeburn  8582:     my $nav_error;
1.649     raeburn  8583:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8584:     if ($nav_error) {
                   8585:         $r->print(&navmap_errormsg());
                   8586:         return(1,$currentphase);
                   8587:     }
1.447     foxr     8588: 
1.186     albertel 8589:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8590:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8591: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8592: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8593: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8594: 						 $scan_data);
                   8595: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8596: 	my $error=0;
1.224     albertel 8597: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8598: 	    &scantron_get_correction($r,$i,$scan_record,
                   8599: 				     \%scantron_config,
                   8600: 				     $line,'incorrectCODE',\%allcodes);
                   8601: 	    return(1,$currentphase);
                   8602: 	}
1.221     albertel 8603: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8604: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8605: 	    &scantron_get_correction($r,$i,$scan_record,
                   8606: 				     \%scantron_config,
1.194     albertel 8607: 				     $line,'incorrectCODE',\%allcodes);
                   8608: 	    return(1,$currentphase);
1.186     albertel 8609: 	}
1.214     albertel 8610: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8611: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8612: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8613: 	    &scantron_get_correction($r,$i,$scan_record,
                   8614: 				     \%scantron_config,
1.194     albertel 8615: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8616: 	    return(1,$currentphase);
1.186     albertel 8617: 	}
1.524     raeburn  8618: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8619:     }
1.157     albertel 8620:     return (0,$currentphase+1);
                   8621: }
                   8622: 
1.423     albertel 8623: =pod
                   8624: 
                   8625: =item scantron_validate_doublebubble
                   8626: 
1.424     albertel 8627:    Validates all scanlines in the selected file to not have any
                   8628:    bubble lines with multiple bubbles marked.
                   8629: 
1.423     albertel 8630: =cut
                   8631: 
1.157     albertel 8632: sub scantron_validate_doublebubble {
                   8633:     my ($r,$currentphase) = @_;
                   8634:     #get student info
                   8635:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8636:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8637:     my (undef,undef,$sequence)=
                   8638:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8639: 
                   8640:     #get scantron line setup
1.754     raeburn  8641:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8642:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8643: 
                   8644:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8645:     unless (ref($navmap)) {
                   8646:         $r->print(&navmap_errormsg());
                   8647:         return(1,$currentphase);
                   8648:     }
                   8649:     my $map=$navmap->getResourceByUrl($sequence);
                   8650:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8651:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8652:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8653:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8654: 
1.583     raeburn  8655:     my $nav_error;
1.691     raeburn  8656:     if (ref($map)) {
                   8657:         $randomorder = $map->randomorder();
                   8658:         $randompick = $map->randompick();
                   8659:         if ($randomorder || $randompick) {
                   8660:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8661:             if ($nav_error) {
                   8662:                 $r->print(&navmap_errormsg());
                   8663:                 return(1,$currentphase);
                   8664:             }
                   8665:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8666:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8667:         }
                   8668:     } else {
                   8669:         $r->print(&navmap_errormsg());
                   8670:         return(1,$currentphase);
                   8671:     }
                   8672: 
1.649     raeburn  8673:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8674:     if ($nav_error) {
                   8675:         $r->print(&navmap_errormsg());
                   8676:         return(1,$currentphase);
                   8677:     }
1.447     foxr     8678: 
1.157     albertel 8679:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8680: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8681: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8682: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8683: 						 $scan_data,undef,\%idmap,$randomorder,
                   8684:                                                  $randompick,$sequence,\@master_seq,
                   8685:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8686:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8687: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8688: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8689: 				 'doublebubble',
1.691     raeburn  8690: 				 $$scan_record{'scantron.doubleerror'},
                   8691:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8692:     	return (1,$currentphase);
                   8693:     }
                   8694:     return (0,$currentphase+1);
                   8695: }
                   8696: 
1.423     albertel 8697: 
1.503     raeburn  8698: sub scantron_get_maxbubble {
1.649     raeburn  8699:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8700:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8701: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8702: 	&restore_bubble_lines();
1.257     albertel 8703: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8704:     }
1.330     albertel 8705: 
1.447     foxr     8706:     my (undef, undef, $sequence) =
1.257     albertel 8707: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8708: 
1.447     foxr     8709:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8710:     unless (ref($navmap)) {
                   8711:         if (ref($nav_error)) {
                   8712:             $$nav_error = 1;
                   8713:         }
1.591     raeburn  8714:         return;
1.582     raeburn  8715:     }
1.191     albertel 8716:     my $map=$navmap->getResourceByUrl($sequence);
                   8717:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8718:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8719: 
                   8720:     &Apache::lonxml::clear_problem_counter();
                   8721: 
1.557     raeburn  8722:     my $uname       = $env{'user.name'};
                   8723:     my $udom        = $env{'user.domain'};
1.435     foxr     8724:     my $cid         = $env{'request.course.id'};
                   8725:     my $total_lines = 0;
                   8726:     %bubble_lines_per_response = ();
1.447     foxr     8727:     %first_bubble_line         = ();
1.503     raeburn  8728:     %subdivided_bubble_lines   = ();
                   8729:     %responsetype_per_response = ();
1.691     raeburn  8730:     %masterseq_id_responsenum  = ();
1.554     raeburn  8731: 
1.447     foxr     8732:     my $response_number = 0;
                   8733:     my $bubble_line     = 0;
1.191     albertel 8734:     foreach my $resource (@resources) {
1.691     raeburn  8735:         my $resid = $resource->id(); 
1.672     raeburn  8736:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8737:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8738:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8739: 	    foreach my $part_id (@{$parts}) {
                   8740:                 my $lines;
                   8741: 
                   8742: 	        # TODO - make this a persistent hash not an array.
                   8743: 
                   8744:                 # optionresponse, matchresponse and rankresponse type items 
                   8745:                 # render as separate sub-questions in exam mode.
                   8746:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8747:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8748:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8749:                     my ($numbub,$numshown);
                   8750:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8751:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8752:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8753:                         }
                   8754:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8755:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8756:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8757:                         }
                   8758:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8759:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8760:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8761:                         }
                   8762:                     }
                   8763:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8764:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8765:                     }
1.649     raeburn  8766:                     my $bubbles_per_row =
                   8767:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8768:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8769:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8770:                         $inner_bubble_lines++;
                   8771:                     }
                   8772:                     for (my $i=0; $i<$numshown; $i++) {
                   8773:                         $subdivided_bubble_lines{$response_number} .= 
                   8774:                             $inner_bubble_lines.',';
                   8775:                     }
                   8776:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8777:                     $lines = $numshown * $inner_bubble_lines;
                   8778:                 } else {
                   8779:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8780:                 }
1.542     raeburn  8781: 
                   8782:                 $first_bubble_line{$response_number} = $bubble_line;
                   8783: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8784:                 $responsetype_per_response{$response_number} = 
                   8785:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8786:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8787: 	        $response_number++;
                   8788: 
                   8789: 	        $bubble_line +=  $lines;
                   8790: 	        $total_lines +=  $lines;
                   8791: 	    }
                   8792:         }
                   8793:     }
1.552     raeburn  8794:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8795: 
                   8796:     &save_bubble_lines();
                   8797:     $env{'form.scantron_maxbubble'} =
                   8798: 	$total_lines;
                   8799:     return $env{'form.scantron_maxbubble'};
                   8800: }
1.523     raeburn  8801: 
1.649     raeburn  8802: sub bubblesheet_bubbles_per_row {
                   8803:     my ($scantron_config) = @_;
                   8804:     my $bubbles_per_row;
                   8805:     if (ref($scantron_config) eq 'HASH') {
                   8806:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8807:     }
                   8808:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8809:         $bubbles_per_row = 10;
                   8810:     }
                   8811:     return $bubbles_per_row;
                   8812: }
                   8813: 
1.157     albertel 8814: sub scantron_validate_missingbubbles {
                   8815:     my ($r,$currentphase) = @_;
                   8816:     #get student info
                   8817:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8818:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8819:     my (undef,undef,$sequence)=
                   8820:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8821: 
                   8822:     #get scantron line setup
1.754     raeburn  8823:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8824:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8825: 
                   8826:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8827:     unless (ref($navmap)) {
                   8828:         $r->print(&navmap_errormsg());
                   8829:         return(1,$currentphase);
                   8830:     }
                   8831: 
                   8832:     my $map=$navmap->getResourceByUrl($sequence);
                   8833:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8834:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8835:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8836:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8837: 
1.582     raeburn  8838:     my $nav_error;
1.691     raeburn  8839:     if (ref($map)) {
                   8840:         $randomorder = $map->randomorder();
                   8841:         $randompick = $map->randompick();
                   8842:         if ($randomorder || $randompick) {
                   8843:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8844:             if ($nav_error) {
                   8845:                 $r->print(&navmap_errormsg());
                   8846:                 return(1,$currentphase);
                   8847:             }
                   8848:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8849:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8850:         }
                   8851:     } else {
                   8852:         $r->print(&navmap_errormsg());
                   8853:         return(1,$currentphase);
                   8854:     }
                   8855: 
                   8856: 
1.649     raeburn  8857:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8858:     if ($nav_error) {
1.691     raeburn  8859:         $r->print(&navmap_errormsg());
1.693     raeburn  8860:         return(1,$currentphase);
1.582     raeburn  8861:     }
1.691     raeburn  8862: 
1.157     albertel 8863:     if (!$max_bubble) { $max_bubble=2**31; }
                   8864:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8865: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8866: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8867: 	my $scan_record =
                   8868:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8869: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8870:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8871:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8872: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8873: 	my @to_correct;
1.470     foxr     8874: 	
                   8875: 	# Probably here's where the error is...
                   8876: 
1.157     albertel 8877: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8878:             my $lastbubble;
                   8879:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8880:                my $question = $1;
                   8881:                my $subquestion = $2;
1.691     raeburn  8882:                my ($first,$responsenum);
                   8883:                if ($randomorder || $randompick) {
                   8884:                    $responsenum = $respnumlookup{$question-1};
                   8885:                    $first = $startline{$question-1};
                   8886:                } else {
                   8887:                    $responsenum = $question-1; 
                   8888:                    $first = $first_bubble_line{$responsenum};
                   8889:                }
                   8890:                if (!defined($first)) { next; }
                   8891:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8892:                my $subcount = 1;
                   8893:                while ($subcount<$subquestion) {
                   8894:                    $first += $subans[$subcount-1];
                   8895:                    $subcount ++;
                   8896:                }
                   8897:                my $count = $subans[$subquestion-1];
                   8898:                $lastbubble = $first + $count;
                   8899:             } else {
1.691     raeburn  8900:                my ($first,$responsenum);
                   8901:                if ($randomorder || $randompick) {
                   8902:                    $responsenum = $respnumlookup{$missing-1};
                   8903:                    $first = $startline{$missing-1};
                   8904:                } else {
                   8905:                    $responsenum = $missing-1;
                   8906:                    $first = $first_bubble_line{$responsenum};
                   8907:                }
                   8908:                if (!defined($first)) { next; }
                   8909:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8910:             }
                   8911:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8912: 	    push(@to_correct,$missing);
                   8913: 	}
                   8914: 	if (@to_correct) {
                   8915: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8916: 				     $line,'missingbubble',\@to_correct,
                   8917:                                      $randomorder,$randompick,\%respnumlookup,
                   8918:                                      \%startline);
1.157     albertel 8919: 	    return (1,$currentphase);
                   8920: 	}
                   8921: 
                   8922:     }
                   8923:     return (0,$currentphase+1);
                   8924: }
                   8925: 
1.663     raeburn  8926: sub hand_bubble_option {
                   8927:     my (undef, undef, $sequence) =
                   8928:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8929:     return if ($sequence eq '');
                   8930:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8931:     unless (ref($navmap)) {
                   8932:         return;
                   8933:     }
                   8934:     my $needs_hand_bubbles;
                   8935:     my $map=$navmap->getResourceByUrl($sequence);
                   8936:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8937:     foreach my $res (@resources) {
                   8938:         if (ref($res)) {
                   8939:             if ($res->is_problem()) {
                   8940:                 my $partlist = $res->parts();
                   8941:                 foreach my $part (@{ $partlist }) {
                   8942:                     my @types = $res->responseType($part);
                   8943:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8944:                         $needs_hand_bubbles = 1;
                   8945:                         last;
                   8946:                     }
                   8947:                 }
                   8948:             }
                   8949:         }
                   8950:     }
                   8951:     if ($needs_hand_bubbles) {
1.754     raeburn  8952:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  8953:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8954:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8955:                &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 />').
                   8956:                '<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  8957:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8958:     }
                   8959:     return;
                   8960: }
1.423     albertel 8961: 
1.82      albertel 8962: sub scantron_process_students {
1.608     www      8963:     my ($r,$symb) = @_;
1.513     foxr     8964: 
1.257     albertel 8965:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8966:     if (!$symb) {
                   8967: 	return '';
                   8968:     }
1.324     albertel 8969:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8970: 
1.754     raeburn  8971:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8972:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8973:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8974:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8975:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8976:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8977:     unless (ref($navmap)) {
                   8978:         $r->print(&navmap_errormsg());
                   8979:         return '';
1.691     raeburn  8980:     }
1.83      albertel 8981:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8982:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8983:         %grader_randomlists_by_symb);
1.677     raeburn  8984:     if (ref($map)) {
                   8985:         $randomorder = $map->randomorder();
1.689     raeburn  8986:         $randompick = $map->randompick();
1.691     raeburn  8987:     } else {
                   8988:         $r->print(&navmap_errormsg());
                   8989:         return '';
1.677     raeburn  8990:     }
1.691     raeburn  8991:     my $nav_error;
1.83      albertel 8992:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8993:     if ($randomorder || $randompick) {
                   8994:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8995:         if ($nav_error) {
                   8996:             $r->print(&navmap_errormsg());
                   8997:             return '';
                   8998:         }
                   8999:     }
1.557     raeburn  9000:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  9001:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  9002: 
1.554     raeburn  9003:     my ($uname,$udom);
1.82      albertel 9004:     my $result= <<SCANTRONFORM;
1.81      albertel 9005: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   9006:   <input type="hidden" name="command" value="scantron_configphase" />
                   9007:   $default_form_data
                   9008: SCANTRONFORM
1.82      albertel 9009:     $r->print($result);
                   9010: 
1.770     raeburn  9011:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 9012:     my @delayqueue;
1.542     raeburn  9013:     my (%completedstudents,%scandata);
1.770     raeburn  9014: 
1.520     www      9015:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9016:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9017:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   9018:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9019:     $r->print('<br />');
1.140     albertel 9020:     my $start=&Time::HiRes::time();
1.158     albertel 9021:     my $i=-1;
1.542     raeburn  9022:     my $started;
1.447     foxr     9023: 
1.649     raeburn  9024:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9025:     if ($nav_error) {
                   9026:         $r->print(&navmap_errormsg());
                   9027:         return '';
                   9028:     }
                   9029: 
1.513     foxr     9030:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9031:     # the user and return.
                   9032: 
                   9033:     if ($ssi_error) {
                   9034: 	$r->print("</form>");
                   9035: 	&ssi_print_error($r);
1.520     www      9036:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9037: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9038:     }
1.447     foxr     9039: 
1.755     raeburn  9040:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9041:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  9042:     my %orderedforcode;
1.542     raeburn  9043: 
1.157     albertel 9044:     while ($i<$scanlines->{'count'}) {
                   9045:  	($uname,$udom)=('','');
                   9046:  	$i++;
1.200     albertel 9047:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9048:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9049: 	if ($started) {
1.667     www      9050: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9051: 	}
                   9052: 	$started=1;
1.691     raeburn  9053:         my %respnumlookup = ();
                   9054:         my %startline = ();
                   9055:         my $total;
1.157     albertel 9056:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9057:                                                  $scan_data,undef,\%idmap,$randomorder,
                   9058:                                                  $randompick,$sequence,\@master_seq,
                   9059:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9060:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9061:                                                  \$total);
1.157     albertel 9062:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9063:  					      \%idmap,$i)) {
                   9064:   	    &scantron_add_delay(\@delayqueue,$line,
                   9065:  				'Unable to find a student that matches',1);
                   9066:  	    next;
                   9067:   	}
                   9068:  	if (exists $completedstudents{$uname}) {
                   9069:  	    &scantron_add_delay(\@delayqueue,$line,
                   9070:  				'Student '.$uname.' has multiple sheets',2);
                   9071:  	    next;
                   9072:  	}
1.677     raeburn  9073:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  9074:         if (($checksec ne '') && ($checksec ne $usec)) {
                   9075:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   9076:                 &scantron_add_delay(\@delayqueue,$line,
                   9077:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   9078:                 next;
                   9079:             }
                   9080:         }
1.677     raeburn  9081:         my $user = $uname.':'.$usec;
1.157     albertel 9082:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9083: 
1.677     raeburn  9084:         my $scancode;
                   9085:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9086:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9087:             $scancode = $scan_record->{'scantron.CODE'};
                   9088:         } else {
                   9089:             $scancode = '';
                   9090:         }
                   9091: 
                   9092:         my @mapresources = @resources;
1.689     raeburn  9093:         if ($randomorder || $randompick) {
1.678     raeburn  9094:             @mapresources = 
1.691     raeburn  9095:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9096:                              \%orderedforcode);
1.677     raeburn  9097:         }
1.586     raeburn  9098:         my (%partids_by_symb,$res_error);
1.677     raeburn  9099:         foreach my $resource (@mapresources) {
1.586     raeburn  9100:             my $ressymb;
                   9101:             if (ref($resource)) {
                   9102:                 $ressymb = $resource->symb();
                   9103:             } else {
                   9104:                 $res_error = 1;
                   9105:                 last;
                   9106:             }
1.557     raeburn  9107:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9108:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9109:                 my $currcode;
                   9110:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9111:                     $currcode = $scancode;
                   9112:                 }
1.557     raeburn  9113:                 my ($analysis,$parts) =
1.672     raeburn  9114:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  9115:                                               $uname,$udom,undef,$bubbles_per_row,
                   9116:                                               $currcode);
1.557     raeburn  9117:                 $partids_by_symb{$ressymb} = $parts;
                   9118:             } else {
                   9119:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9120:             }
1.554     raeburn  9121:         }
                   9122: 
1.586     raeburn  9123:         if ($res_error) {
                   9124:             &scantron_add_delay(\@delayqueue,$line,
                   9125:                                 'An error occurred while grading student '.$uname,2);
                   9126:             next;
                   9127:         }
                   9128: 
1.330     albertel 9129: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9130:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9131: 
                   9132: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9133: 	    &scantron_putfile($scanlines,$scan_data);
                   9134: 	}
1.161     albertel 9135: 	
1.542     raeburn  9136:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9137:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  9138:                                    $bubbles_per_row,$randomorder,$randompick,
                   9139:                                    \%respnumlookup,\%startline) 
                   9140:             eq 'ssi_error') {
1.542     raeburn  9141:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9142:             $r->print("</form>");
                   9143:             &ssi_print_error($r);
                   9144:             &Apache::lonnet::remove_lock($lock);
                   9145:             return '';      # Why return ''?  Beats me.
                   9146:         }
1.513     foxr     9147: 
1.692     raeburn  9148:         if (($scancode) && ($randomorder || $randompick)) {
                   9149:             my $parmresult =
                   9150:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   9151:                                                        '0_examcode',2,$scancode,
                   9152:                                                        'string_examcode',$uname,
                   9153:                                                        $udom);
                   9154:         }
1.140     albertel 9155: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9156:         if ($env{'form.verifyrecord'}) {
                   9157:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  9158:             if ($randompick) {
                   9159:                 if ($total) {
                   9160:                     $lastpos = $total*$scantron_config{'Qlength'};
                   9161:                 }
                   9162:             }
                   9163: 
1.542     raeburn  9164:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9165:             chomp($studentdata);
                   9166:             $studentdata =~ s/\r$//;
                   9167:             my $studentrecord = '';
                   9168:             my $counter = -1;
1.677     raeburn  9169:             foreach my $resource (@mapresources) {
1.554     raeburn  9170:                 my $ressymb = $resource->symb();
1.542     raeburn  9171:                 ($counter,my $recording) =
                   9172:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9173:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9174:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9175:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9176:                 $studentrecord .= $recording;
                   9177:             }
                   9178:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9179:                 &Apache::lonxml::clear_problem_counter();
                   9180:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9181:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  9182:                                            $bubbles_per_row,$randomorder,$randompick,
                   9183:                                            \%respnumlookup,\%startline) 
                   9184:                     eq 'ssi_error') {
1.554     raeburn  9185:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9186:                     $r->print("</form>");
                   9187:                     &ssi_print_error($r);
                   9188:                     &Apache::lonnet::remove_lock($lock);
                   9189:                     delete($completedstudents{$uname});
                   9190:                     return '';
                   9191:                 }
1.542     raeburn  9192:                 $counter = -1;
                   9193:                 $studentrecord = '';
1.677     raeburn  9194:                 foreach my $resource (@mapresources) {
1.554     raeburn  9195:                     my $ressymb = $resource->symb();
1.542     raeburn  9196:                     ($counter,my $recording) =
                   9197:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9198:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9199:                                                  \%scantron_config,\%lettdig,$numletts,
                   9200:                                                  $randomorder,$randompick,\%respnumlookup,
                   9201:                                                  \%startline);
1.542     raeburn  9202:                     $studentrecord .= $recording;
                   9203:                 }
                   9204:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   9205:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9206:                     if ($scancode eq '') {
1.658     bisitz   9207:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9208:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9209:                     } else {
1.658     bisitz   9210:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9211:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9212:                     }
                   9213:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9214:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9215:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9216:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9217:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9218:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   9219:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9220:                               &Apache::loncommon::end_data_table_row().
                   9221:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9222:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   9223:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9224:                               &Apache::loncommon::end_data_table_row().
                   9225:                               &Apache::loncommon::end_data_table().'</p>');
                   9226:                 } else {
                   9227:                     $r->print('<br /><span class="LC_warning">'.
                   9228:                              &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 />'.
                   9229:                              &mt("As a consequence, this user's submission history records two tries.").
                   9230:                                  '</span><br />');
                   9231:                 }
                   9232:             }
                   9233:         }
1.543     raeburn  9234:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9235:     } continue {
1.330     albertel 9236: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9237: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9238:     }
1.140     albertel 9239:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9240:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9241: #    my $lasttime = &Time::HiRes::time()-$start;
                   9242: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9243: 
1.200     albertel 9244:     $r->print("</form>");
1.157     albertel 9245:     return '';
1.75      albertel 9246: }
1.157     albertel 9247: 
1.557     raeburn  9248: sub graders_resources_pass {
1.649     raeburn  9249:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9250:         $bubbles_per_row) = @_;
1.557     raeburn  9251:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9252:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9253:         foreach my $resource (@{$resources}) {
                   9254:             my $ressymb = $resource->symb();
                   9255:             my ($analysis,$parts) =
                   9256:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  9257:                                           $env{'user.name'},$env{'user.domain'},
                   9258:                                           1,$bubbles_per_row);
1.557     raeburn  9259:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9260:             if (ref($analysis) eq 'HASH') {
                   9261:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9262:                     $grader_randomlists_by_symb->{$ressymb} =
                   9263:                         $analysis->{'parts_withrandomlist'};
                   9264:                 }
                   9265:             }
                   9266:         }
                   9267:     }
                   9268:     return;
                   9269: }
                   9270: 
1.678     raeburn  9271: =pod
                   9272: 
                   9273: =item users_order
                   9274: 
                   9275:   Returns array of resources in current map, ordered based on either CODE,
                   9276:   if this is a CODEd exam, or based on student's identity if this is a 
                   9277:   "NAMEd" exam.
                   9278: 
1.691     raeburn  9279:   Should be used when randomorder and/or randompick applied when the 
                   9280:   corresponding exam was printed, prior to students completing bubblesheets 
                   9281:   for the version of the exam the student received.
1.678     raeburn  9282: 
                   9283: =cut
                   9284: 
                   9285: sub users_order  {
1.691     raeburn  9286:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9287:     my @mapresources;
1.691     raeburn  9288:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9289:         return @mapresources;
1.691     raeburn  9290:     }
                   9291:     if ($scancode) {
                   9292:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9293:             @mapresources = @{$orderedforcode->{$scancode}};
                   9294:         } else {
                   9295:             $env{'form.CODE'} = $scancode;
                   9296:             my $actual_seq =
                   9297:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9298:                                                                $master_seq,
                   9299:                                                                $user,$scancode,1);
                   9300:             if (ref($actual_seq) eq 'ARRAY') {
                   9301:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9302:                 if (ref($orderedforcode) eq 'HASH') {
                   9303:                     if (@mapresources > 0) { 
                   9304:                         $orderedforcode->{$scancode} = \@mapresources;
                   9305:                     }
                   9306:                 }
                   9307:             }
                   9308:             delete($env{'form.CODE'});
1.678     raeburn  9309:         }
                   9310:     } else {
                   9311:         my $actual_seq =
                   9312:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9313:                                                            $master_seq,
1.688     raeburn  9314:                                                            $user,undef,1);
1.678     raeburn  9315:         if (ref($actual_seq) eq 'ARRAY') {
                   9316:             @mapresources = 
                   9317:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9318:         }
1.691     raeburn  9319:     }
                   9320:     return @mapresources;
1.678     raeburn  9321: }
                   9322: 
1.542     raeburn  9323: sub grade_student_bubbles {
1.691     raeburn  9324:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9325:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9326:     my $uselookup = 0;
                   9327:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9328:         (ref($startline) eq 'HASH')) {
                   9329:         $uselookup = 1;
                   9330:     }
                   9331: 
1.554     raeburn  9332:     if (ref($resources) eq 'ARRAY') {
                   9333:         my $count = 0;
                   9334:         foreach my $resource (@{$resources}) {
                   9335:             my $ressymb = $resource->symb();
                   9336:             my %form = ('submitted'      => 'scantron',
                   9337:                         'grade_target'   => 'grade',
                   9338:                         'grade_username' => $uname,
                   9339:                         'grade_domain'   => $udom,
                   9340:                         'grade_courseid' => $env{'request.course.id'},
                   9341:                         'grade_symb'     => $ressymb,
                   9342:                         'CODE'           => $scancode
                   9343:                        );
1.649     raeburn  9344:             if ($bubbles_per_row ne '') {
                   9345:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9346:             }
1.663     raeburn  9347:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9348:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9349:             }
1.554     raeburn  9350:             if (ref($parts) eq 'HASH') {
                   9351:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9352:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9353:                         if ($uselookup) {
                   9354:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9355:                         } else {
                   9356:                             $form{'scantron_questnum_start.'.$part} =
                   9357:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9358:                         }
1.554     raeburn  9359:                         $count++;
                   9360:                     }
                   9361:                 }
                   9362:             }
                   9363:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9364:             return 'ssi_error' if ($ssi_error);
                   9365:             last if (&Apache::loncommon::connection_aborted($r));
                   9366:         }
1.542     raeburn  9367:     }
                   9368:     return;
                   9369: }
                   9370: 
1.157     albertel 9371: sub scantron_upload_scantron_data {
1.767     raeburn  9372:     my ($r,$symb) = @_;
1.565     raeburn  9373:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9374:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9375:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9376:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9377:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9378: 							  'domainid',
1.565     raeburn  9379: 							  'coursename',$dom);
                   9380:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9381:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9382:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9383:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9384:     &js_escape(\$nofile_alert);
1.579     raeburn  9385:     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  9386:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9387:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9388:     function checkUpload(formname) {
                   9389: 	if (formname.upfile.value == "") {
1.579     raeburn  9390: 	    alert("'.$nofile_alert.'");
1.157     albertel 9391: 	    return false;
                   9392: 	}
1.565     raeburn  9393:         if (formname.courseid.value == "") {
1.579     raeburn  9394:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9395:             return false;
                   9396:         }
1.157     albertel 9397: 	formname.submit();
                   9398:     }
1.565     raeburn  9399: 
                   9400:     function ToSyllabus() {
                   9401:         var cdom = '."'$dom'".';
                   9402:         var cnum = document.rules.courseid.value;
                   9403:         if (cdom == "" || cdom == null) {
                   9404:             return;
                   9405:         }
                   9406:         if (cnum == "" || cnum == null) {
                   9407:            return;
                   9408:         }
                   9409:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9410:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9411:         return;
                   9412:     }
                   9413: 
1.754     raeburn  9414:     '.$formatjs.'
1.597     wenzelju 9415: '));
                   9416:     $r->print('
1.648     bisitz   9417: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9418: 
1.492     albertel 9419: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9420: '.$default_form_data.
                   9421:   &Apache::lonhtmlcommon::start_pick_box().
                   9422:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9423:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9424:   &Apache::lonhtmlcommon::row_closure().
                   9425:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9426:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9427:   &Apache::lonhtmlcommon::row_closure().
                   9428:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9429:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9430:   &Apache::lonhtmlcommon::row_closure());
                   9431:     if ($formatoptions) {
                   9432:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9433:                   &Apache::lonhtmlcommon::row_closure());
                   9434:     }
                   9435:     $r->print(
1.565     raeburn  9436:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9437:   '<input type="file" name="upfile" size="50" />'.
                   9438:   &Apache::lonhtmlcommon::row_closure(1).
                   9439:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9440: 
1.492     albertel 9441: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9442: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9443: </form>
1.492     albertel 9444: ');
1.157     albertel 9445:     return '';
                   9446: }
                   9447: 
1.754     raeburn  9448: sub scantron_upload_dataformat {
                   9449:     my ($dom) = @_;
                   9450:     my ($formatoptions,$formattitle,$formatjs);
                   9451:     $formatjs = <<'END';
                   9452: function toggleScantab(form) {
                   9453:    return;
                   9454: }
                   9455: END
                   9456:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9457:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9458:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9459:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9460:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9461:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  9462:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   9463:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9464:                             my ($onclick,$formatextra,$singleline);
                   9465:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9466:                             my $count = 0;
                   9467:                             foreach my $line (@lines) {
                   9468:                                 next if ($line =~ /^#/);
                   9469:                                 $singleline = $line;
                   9470:                                 $count ++;
                   9471:                             }
                   9472:                             if ($count > 1) {
                   9473:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  9474:                                                '<span class="LC_nobreak">'.
1.776     raeburn  9475:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  9476:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  9477:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9478:                                 $formatjs = <<"END";
1.754     raeburn  9479: function toggleScantab(form) {
                   9480:     var divid = 'bubbletype';
                   9481:     if (document.getElementById(divid)) {
                   9482:         var radioname = 'fileformat';
                   9483:         var num = form.elements[radioname].length;
                   9484:         if (num) {
                   9485:             for (var i=0; i<num; i++) {
                   9486:                 if (form.elements[radioname][i].checked) {
                   9487:                     var chosen = form.elements[radioname][i].value;
                   9488:                     if (chosen == 'dat') {
                   9489:                         document.getElementById(divid).style.display = 'none';
                   9490:                     } else if (chosen == 'csv') {
1.757     raeburn  9491:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  9492:                     }
                   9493:                 }
                   9494:             }
                   9495:         }
                   9496:     }
                   9497:     return;
                   9498: }
                   9499: 
                   9500: END
1.756     raeburn  9501:                             } elsif ($count == 1) {
                   9502:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9503:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9504:                             }
                   9505:                             $formattitle = &mt('File format');
                   9506:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9507:                                              &mt('Plain Text (no delimiters)').
                   9508:                                              '</label>'.('&nbsp;'x2).
                   9509:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9510:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9511:                         }
                   9512:                     }
                   9513:                 }
                   9514:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  9515:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9516:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  9517:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  9518:                         $formatoptions = &scantron_scantab();
                   9519:                     }
1.754     raeburn  9520:                 }
                   9521:             }
                   9522:         }
                   9523:     }
                   9524:     return ($formatoptions,$formattitle,$formatjs);
                   9525: }
1.423     albertel 9526: 
1.157     albertel 9527: sub scantron_upload_scantron_data_save {
1.767     raeburn  9528:     my ($r,$symb) = @_;
1.182     albertel 9529:     my $doanotherupload=
                   9530: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9531: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9532: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9533: 	'</form>'."\n";
1.257     albertel 9534:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9535: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  9536: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   9537:         !&Apache::lonnet::allowed('usc',
                   9538:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      9539: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9540: 	unless ($symb) {
1.182     albertel 9541: 	    $r->print($doanotherupload);
                   9542: 	}
1.162     albertel 9543: 	return '';
                   9544:     }
1.257     albertel 9545:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9546:     my $uploadedfile;
1.710     bisitz   9547:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9548:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9549:         $r->print(
                   9550:             &Apache::lonhtmlcommon::confirm_success(
                   9551:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9552:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9553:     } else {
1.754     raeburn  9554:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9555:         my $parser;
                   9556:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9557:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9558:                 my $is_csv;
                   9559:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9560:                 if (@possibles > 1) {
                   9561:                     if ($env{'form.fileformat'} eq 'csv') {
                   9562:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9563:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9564:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9565:                                     $is_csv = 1;
                   9566:                                 }
1.754     raeburn  9567:                             }
                   9568:                         }
                   9569:                     }
                   9570:                 } elsif (@possibles == 1) {
                   9571:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9572:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9573:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9574:                                 $is_csv = 1;
                   9575:                             }
1.754     raeburn  9576:                         }
                   9577:                     }
                   9578:                 }
                   9579:                 if ($is_csv) {
                   9580:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9581:                 }
                   9582:             }
                   9583:         }
                   9584:         my $result =
                   9585:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9586:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9587:         if ($result =~ m{^/uploaded/}) {
                   9588:             $r->print(
                   9589:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9590:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9591:                         (length($env{'form.upfile'})-1),
                   9592:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9593:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  9594:             if ($uploadedfile =~ /^scantron_orig_/) {
                   9595:                 my $logname = $uploadedfile;
                   9596:                 $logname =~ s/^scantron_orig_//;
                   9597:                 if ($logname ne '') {
                   9598:                     my $now = time;
                   9599:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   9600:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9601:                 }
                   9602:             }
1.567     raeburn  9603:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  9604:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   9605:         } else {
                   9606:             $r->print(
                   9607:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9608:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9609:                           $result,
1.568     raeburn  9610: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9611: 	}
                   9612:     }
1.174     albertel 9613:     if ($symb) {
1.612     www      9614: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9615:     } else {
1.182     albertel 9616: 	$r->print($doanotherupload);
1.174     albertel 9617:     }
1.157     albertel 9618:     return '';
                   9619: }
                   9620: 
1.567     raeburn  9621: sub validate_uploaded_scantron_file {
1.770     raeburn  9622:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   9623: 
1.567     raeburn  9624:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9625:     my @lines;
                   9626:     if ($scanlines ne '-1') {
                   9627:         @lines=split("\n",$scanlines,-1);
                   9628:     }
1.770     raeburn  9629:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   9630:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   9631:     if ($context eq 'download') {
                   9632:         $priv = 'mgr';
                   9633:     } else {
                   9634:         $priv = 'usc';
                   9635:     }
                   9636:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   9637:             (($env{'request.course.id'}) &&
                   9638:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   9639:         if ($env{'request.course.sec'} ne '') {
                   9640:             unless (&Apache::lonnet::allowed($priv,
                   9641:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   9642:                 unless ($context eq 'download') {
                   9643:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   9644:                 }
                   9645:                 return $output;
                   9646:             }
                   9647:             ($checksec,@possibles)=&gradable_sections();
                   9648:         }
                   9649:     }
1.567     raeburn  9650:     if (@lines) {
                   9651:         my (%counts,$max_match_format);
1.710     bisitz   9652:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9653:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9654:         my %idmap = &username_to_idmap($classlist);
                   9655:         foreach my $key (keys(%idmap)) {
                   9656:             my $lckey = lc($key);
                   9657:             $idmap{$lckey} = $idmap{$key};
                   9658:         }
                   9659:         my %unique_formats;
1.754     raeburn  9660:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9661:         foreach my $line (@formatlines) {
                   9662:             chomp($line);
                   9663:             my @config = split(/:/,$line);
                   9664:             my $idstart = $config[5];
                   9665:             my $idlength = $config[6];
                   9666:             if (($idstart ne '') && ($idlength > 0)) {
                   9667:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9668:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9669:                 } else {
                   9670:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9671:                 }
                   9672:             }
                   9673:         }
                   9674:         foreach my $key (keys(%unique_formats)) {
                   9675:             my ($idstart,$idlength) = split(':',$key);
                   9676:             %{$counts{$key}} = (
                   9677:                                'found'   => 0,
                   9678:                                'total'   => 0,
1.770     raeburn  9679:                                'totalanysec' => 0,
                   9680:                                'othersec' => 0,
1.567     raeburn  9681:                               );
                   9682:             foreach my $line (@lines) {
                   9683:                 next if ($line =~ /^#/);
                   9684:                 next if ($line =~ /^[\s\cz]*$/);
                   9685:                 my $id = substr($line,$idstart-1,$idlength);
                   9686:                 $id = lc($id);
                   9687:                 if (exists($idmap{$id})) {
1.770     raeburn  9688:                     if ($checksec ne '') {
                   9689:                         $counts{$key}{'totalanysec'} ++;
                   9690:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9691:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9692:                             if ($stusec ne $checksec) {
                   9693:                                 if (@possibles) {
                   9694:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   9695:                                         $counts{$key}{'othersec'} ++;
                   9696:                                         next;
                   9697:                                     }
                   9698:                                 } else {
                   9699:                                     $counts{$key}{'othersec'} ++;
                   9700:                                     next;
                   9701:                                 }
                   9702:                             }
                   9703:                         }
                   9704:                     }
1.567     raeburn  9705:                     $counts{$key}{'found'} ++;
                   9706:                 }
                   9707:                 $counts{$key}{'total'} ++;
                   9708:             }
                   9709:             if ($counts{$key}{'total'}) {
                   9710:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9711:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9712:                     $max_match_pct = $percent_match;
                   9713:                     $max_match_format = $key;
1.710     bisitz   9714:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9715:                     $max_match_count = $counts{$key}{'total'};
                   9716:                 }
                   9717:             }
                   9718:         }
1.770     raeburn  9719:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  9720:             my $format_descs;
                   9721:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9722:             for (my $i=0; $i<$numwithformat; $i++) {
                   9723:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9724:                 if ($i<$numwithformat-2) {
                   9725:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9726:                 } elsif ($i==$numwithformat-2) {
                   9727:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9728:                 } elsif ($i==$numwithformat-1) {
                   9729:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9730:                 }
                   9731:             }
                   9732:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9733:             $output .= '<br />';
                   9734:             if ($found_match_count == $max_match_count) {
                   9735:                 # 100% matching entries
                   9736:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9737:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9738:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9739:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9740:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9741:                     ' in the file (for the format defined for [_3]).',
                   9742:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9743:             } else {
                   9744:                 # Not all entries matching? -> Show warning and additional info
                   9745:                 $output .=
                   9746:                     &Apache::lonhtmlcommon::confirm_success(
                   9747:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9748:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9749:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9750:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9751:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9752:                         ' in the file (for the format defined for [_3]).',
                   9753:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9754:                     '<p class="LC_info">'.
                   9755:                     &mt('A low percentage of matches results from one of the following:').
                   9756:                     '</p><ul>'.
                   9757:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9758:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9759:                                '<i>'.$cdom.'</i>').'</li>'.
                   9760:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9761:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9762:                     '</ul>';
                   9763:             }
1.770     raeburn  9764:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9765:                 if ($counts{$max_match_format}{'othersec'}) {
                   9766:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   9767:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   9768:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   9769:                     &js_escape(\$confirmdel);
                   9770:                     $output .= '<p class="LC_warning">'.
                   9771:                                &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',
                   9772:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   9773:                                '<br />'.
                   9774:                                &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>').
                   9775:                                '</p><p>'.
                   9776:                                &mt('If you prefer to delete the file now, use: [_1]').
                   9777:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   9778:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   9779:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   9780:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   9781:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   9782:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   9783:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   9784:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   9785:                                '</form></p>';
                   9786:                 }
                   9787:             }
1.567     raeburn  9788:         }
1.770     raeburn  9789:         if (($context eq 'download') && ($checksec ne '')) {
                   9790:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9791:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   9792:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   9793:             }
                   9794:         } 
                   9795:     } elsif ($context ne 'download') {
1.710     bisitz   9796:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9797:     }
                   9798:     return $output;
                   9799: }
                   9800: 
1.770     raeburn  9801: sub gradable_sections {
                   9802:     my $checksec = $env{'request.course.sec'};
                   9803:     my @oksecs;
                   9804:     if ($checksec) {
                   9805:         my %availablesecs = &sections_grade_privs();
                   9806:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   9807:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   9808:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   9809:                     push(@oksecs,$sec);
                   9810:                 }
                   9811:             }
                   9812:             if (grep(/^all$/,@oksecs)) {
                   9813:                 undef($checksec);
                   9814:             }
                   9815:         }
                   9816:     }
                   9817:     return($checksec,@oksecs);
                   9818: }
                   9819: 
                   9820: sub sections_grade_privs {
                   9821:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9822:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9823:     my %availablesecs = (
                   9824:                           mgr => [],
                   9825:                           vgr => [],
                   9826:                           usc => [],
                   9827:                         );
                   9828:     my $ccrole = 'cc';
                   9829:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   9830:         $ccrole = 'co';
                   9831:     }
                   9832:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   9833:                                                      'userroles',['active'],
                   9834:                                                      [$ccrole,'in','cr'],$cdom,1);
                   9835:     my $crsid = $cnum.':'.$cdom;
                   9836:     foreach my $item (keys(%crsroleshash)) {
                   9837:         next unless ($item =~ /^$crsid\:/);
                   9838:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   9839:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   9840:         if ($sec ne '') {
                   9841:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   9842:         }
                   9843:         if (($role eq $ccrole) || ($role eq 'in')) {
                   9844:             foreach my $priv ('mgr','vgr','usc') { 
                   9845:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9846:                     if ($sec eq '') {
                   9847:                         $availablesecs{$priv} = ['all'];
                   9848:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   9849:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9850:                             push(@{$availablesecs{$priv}},$sec);
                   9851:                         }
                   9852:                     }
                   9853:                 }
                   9854:             }
                   9855:         } elsif ($role =~ m{^cr/}) {
                   9856:             foreach my $priv ('mgr','vgr','usc') {
                   9857:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9858:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   9859:                         if ($sec eq '') {
                   9860:                             $availablesecs{$priv} = ['all'];
                   9861:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   9862:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9863:                                 push(@{$availablesecs{$priv}},$sec);
                   9864:                             }
                   9865:                         }
                   9866:                     }
                   9867:                 }
                   9868:             }
                   9869:         }
                   9870:     }
                   9871:     return %availablesecs;
                   9872: }
                   9873: 
                   9874: sub scantron_upload_delete {
                   9875:     my ($r,$symb) = @_;
                   9876:     my $filename = $env{'form.uploadedfile'};
                   9877:     if ($filename =~ /^scantron_orig_/) {
                   9878:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   9879:             &Apache::lonnet::allowed('usc',
                   9880:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   9881:             &Apache::lonnet::allowed('usc',
                   9882:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   9883:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   9884:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   9885:             if ($retrieval eq '-1') {
                   9886:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9887:                           &mt('File requested for deletion not found.'));
                   9888:             } else {
                   9889:                 $filename =~ s/^scantron_orig_//;
                   9890:                 if ($filename ne '') {
                   9891:                     my ($is_valid,$numleft);
                   9892:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9893:                     if (keys(%info)) {
                   9894:                         if (ref($info{$filename}) eq 'HASH') {
                   9895:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   9896:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9897:                                     $is_valid = 1;
                   9898:                                     delete($info{$filename}{$timestamp}); 
                   9899:                                 }
                   9900:                             }
                   9901:                             $numleft = scalar(keys(%{$info{$filename}}));
                   9902:                         }
                   9903:                     }
                   9904:                     if ($is_valid) {
                   9905:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   9906:                         if ($result eq 'ok') {
                   9907:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   9908:                             if ($numleft) {
                   9909:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9910:                             } else {
                   9911:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9912:                             }
                   9913:                         } else {
                   9914:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9915:                                       &mt('Result was [_1]',$result));
                   9916:                         }
                   9917:                     } else {
                   9918:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9919:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   9920:                     }
                   9921:                 } else {
                   9922:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9923:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9924:                 }
                   9925:             }
                   9926:         } else {
                   9927:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   9928:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   9929:         }
                   9930:     } else {
                   9931:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9932:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9933:     }
                   9934:     return;
                   9935: }
                   9936: 
1.202     albertel 9937: sub valid_file {
                   9938:     my ($requested_file)=@_;
                   9939:     foreach my $filename (sort(&scantron_filenames())) {
                   9940: 	if ($requested_file eq $filename) { return 1; }
                   9941:     }
                   9942:     return 0;
                   9943: }
                   9944: 
                   9945: sub scantron_download_scantron_data {
1.767     raeburn  9946:     my ($r,$symb) = @_;
1.608     www      9947:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9948:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9949:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9950:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9951:     if (! &valid_file($file)) {
1.492     albertel 9952: 	$r->print('
1.202     albertel 9953: 	<p>
1.686     bisitz   9954: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9955:         </p>
1.492     albertel 9956: ');
1.202     albertel 9957: 	return;
                   9958:     }
1.770     raeburn  9959:     my (%uploader,$is_owner,%counts,$percent);
                   9960:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   9961:     if (ref($uploader{$file}) eq 'HASH') {
                   9962:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   9963:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9964:                 $is_owner = 1;
                   9965:                 last;
                   9966:             }
                   9967:         }
                   9968:     }
                   9969:     unless ($is_owner) {
                   9970:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   9971:         if ($counts{'totalanysec'}) {
                   9972:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   9973:             if ($percent_othersec >= 10) {
                   9974:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   9975:                 $r->print('<p class="LC_warning">'.
                   9976:                           &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).
                   9977:                           '</p>');
                   9978:                 return;
                   9979:             }
                   9980:         }
                   9981:     }
1.202     albertel 9982:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9983:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9984:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9985:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9986:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9987:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9988:     $r->print('
1.202     albertel 9989:     <p>
1.723     raeburn  9990: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9991: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9992:     </p>
                   9993:     <p>
1.492     albertel 9994: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9995: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9996:     </p>
                   9997:     <p>
1.492     albertel 9998: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9999: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 10000:     </p>
1.492     albertel 10001: ');
1.202     albertel 10002:     return '';
                   10003: }
1.157     albertel 10004: 
1.523     raeburn  10005: sub checkscantron_results {
1.608     www      10006:     my ($r,$symb) = @_;
1.523     raeburn  10007:     if (!$symb) {return '';}
                   10008:     my $cid = $env{'request.course.id'};
1.755     raeburn  10009:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  10010:     my $numletts = scalar(keys(%lettdig));
                   10011:     my $cnum = $env{'course.'.$cid.'.num'};
                   10012:     my $cdom = $env{'course.'.$cid.'.domain'};
                   10013:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10014:     my %record;
                   10015:     my %scantron_config =
1.754     raeburn  10016:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  10017:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  10018:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  10019:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10020:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   10021:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10022:     unless (ref($navmap)) {
                   10023:         $r->print(&navmap_errormsg());
                   10024:         return '';
                   10025:     }
1.523     raeburn  10026:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10027:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10028:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  10029:     if (ref($map)) { 
                   10030:         $randomorder=$map->randomorder();
1.689     raeburn  10031:         $randompick=$map->randompick();
1.677     raeburn  10032:     }
1.557     raeburn  10033:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10034:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10035:     if ($nav_error) {
                   10036:         $r->print(&navmap_errormsg());
                   10037:         return '';
1.678     raeburn  10038:     }
1.673     raeburn  10039:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10040:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  10041:     my ($uname,$udom);
1.523     raeburn  10042:     my (%scandata,%lastname,%bylast);
                   10043:     $r->print('
                   10044: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   10045: 
                   10046:     my @delayqueue;
                   10047:     my %completedstudents;
                   10048: 
1.691     raeburn  10049:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10050:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  10051:     my ($username,$domain,$started);
1.649     raeburn  10052:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10053:     if ($nav_error) {
                   10054:         $r->print(&navmap_errormsg());
                   10055:         return '';
                   10056:     }
1.523     raeburn  10057: 
1.667     www      10058:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  10059:     my $start=&Time::HiRes::time();
                   10060:     my $i=-1;
                   10061: 
                   10062:     while ($i<$scanlines->{'count'}) {
                   10063:         ($username,$domain,$uname)=('','','');
                   10064:         $i++;
                   10065:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   10066:         if ($line=~/^[\s\cz]*$/) { next; }
                   10067:         if ($started) {
1.667     www      10068:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  10069:         }
                   10070:         $started=1;
                   10071:         my $scan_record=
                   10072:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   10073:                                                      $scan_data);
1.693     raeburn  10074:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10075:                                               \%idmap,$i)) {
1.523     raeburn  10076:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10077:                                 'Unable to find a student that matches',1);
                   10078:             next;
                   10079:         }
                   10080:         if (exists $completedstudents{$uname}) {
                   10081:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10082:                                 'Student '.$uname.' has multiple sheets',2);
                   10083:             next;
                   10084:         }
                   10085:         my $pid = $scan_record->{'scantron.ID'};
                   10086:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   10087:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  10088:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   10089:         my $user = $uname.':'.$usec;
1.523     raeburn  10090:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  10091: 
1.678     raeburn  10092:         my $scancode;
1.677     raeburn  10093:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10094:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10095:             $scancode = $scan_record->{'scantron.CODE'};
                   10096:         } else {
                   10097:             $scancode = '';
                   10098:         }
                   10099: 
                   10100:         my @mapresources = @resources;
1.691     raeburn  10101:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   10102:         my %respnumlookup=();
                   10103:         my %startline=();
1.689     raeburn  10104:         if ($randomorder || $randompick) {
1.678     raeburn  10105:             @mapresources =
1.691     raeburn  10106:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10107:                              \%orderedforcode);
                   10108:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   10109:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   10110:                                              \%grader_partids_by_symb,\%orderedforcode,
                   10111:                                              \%respnumlookup,\%startline);
                   10112:             if ($randompick && $total) {
                   10113:                 $lastpos = $total*$scantron_config{'Qlength'};
                   10114:             }
1.677     raeburn  10115:         }
1.691     raeburn  10116:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10117:         chomp($scandata{$pid});
                   10118:         $scandata{$pid} =~ s/\r$//;
                   10119: 
1.523     raeburn  10120:         my $counter = -1;
1.677     raeburn  10121:         foreach my $resource (@mapresources) {
1.557     raeburn  10122:             my $parts;
1.554     raeburn  10123:             my $ressymb = $resource->symb();
1.557     raeburn  10124:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10125:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10126:                 my $currcode;
                   10127:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10128:                     $currcode = $scancode;
                   10129:                 }
1.557     raeburn  10130:                 (my $analysis,$parts) =
1.672     raeburn  10131:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   10132:                                               $username,$domain,undef,
1.741     raeburn  10133:                                               $bubbles_per_row,$currcode);
1.557     raeburn  10134:             } else {
                   10135:                 $parts = $grader_partids_by_symb{$ressymb};
                   10136:             }
1.542     raeburn  10137:             ($counter,my $recording) =
                   10138:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  10139:                                          $scandata{$pid},$parts,
1.691     raeburn  10140:                                          \%scantron_config,\%lettdig,$numletts,
                   10141:                                          $randomorder,$randompick,
                   10142:                                          \%respnumlookup,\%startline);
1.542     raeburn  10143:             $record{$pid} .= $recording;
1.523     raeburn  10144:         }
                   10145:     }
                   10146:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   10147:     $r->print('<br />');
                   10148:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   10149:     $passed = 0;
                   10150:     $failed = 0;
                   10151:     $numstudents = 0;
                   10152:     foreach my $last (sort(keys(%bylast))) {
                   10153:         if (ref($bylast{$last}) eq 'ARRAY') {
                   10154:             foreach my $pid (sort(@{$bylast{$last}})) {
                   10155:                 my $showscandata = $scandata{$pid};
                   10156:                 my $showrecord = $record{$pid};
                   10157:                 $showscandata =~ s/\s/&nbsp;/g;
                   10158:                 $showrecord =~ s/\s/&nbsp;/g;
                   10159:                 if ($scandata{$pid} eq $record{$pid}) {
                   10160:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   10161:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      10162: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  10163: '</tr>'."\n".
                   10164: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10165: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  10166:                     $passed ++;
                   10167:                 } else {
                   10168:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      10169:                     $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  10170: '</tr>'."\n".
                   10171: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10172: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  10173: '</tr>'."\n";
                   10174:                     $failed ++;
                   10175:                 }
                   10176:                 $numstudents ++;
                   10177:             }
                   10178:         }
                   10179:     }
1.648     bisitz   10180:     $r->print(
                   10181:         '<p>'
                   10182:        .&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).',
                   10183:             '<b>',
                   10184:             $numstudents,
                   10185:             '</b>',
                   10186:             $env{'form.scantron_maxbubble'})
                   10187:        .'</p>'
                   10188:     );
1.682     raeburn  10189:     $r->print('<p>'
1.683     raeburn  10190:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  10191:              .'<br />'
                   10192:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10193:              .'</p>'
                   10194:     );
1.523     raeburn  10195:     if ($passed) {
1.572     www      10196:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10197:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10198:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10199:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10200:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10201:                  $okstudents."\n".
                   10202:                  &Apache::loncommon::end_data_table().'<br />');
                   10203:     }
                   10204:     if ($failed) {
1.572     www      10205:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10206:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10207:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10208:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10209:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10210:                  $badstudents."\n".
                   10211:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10212:                  &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  10213:     }
1.614     www      10214:     $r->print('</form><br />');
1.523     raeburn  10215:     return;
                   10216: }
                   10217: 
1.542     raeburn  10218: sub verify_scantron_grading {
1.554     raeburn  10219:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  10220:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10221:         $respnumlookup,$startline) = @_;
1.542     raeburn  10222:     my ($record,%expected,%startpos);
                   10223:     return ($counter,$record) if (!ref($resource));
                   10224:     return ($counter,$record) if (!$resource->is_problem());
                   10225:     my $symb = $resource->symb();
1.554     raeburn  10226:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10227:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10228:         $counter ++;
                   10229:         $expected{$part_id} = 0;
1.691     raeburn  10230:         my $respnum = $counter;
                   10231:         if ($randomorder || $randompick) {
                   10232:             $respnum = $respnumlookup->{$counter};
                   10233:             $startpos{$part_id} = $startline->{$counter} + 1;
                   10234:         } else {
                   10235:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10236:         }
                   10237:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10238:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10239:             foreach my $item (@sub_lines) {
                   10240:                 $expected{$part_id} += $item;
                   10241:             }
                   10242:         } else {
1.691     raeburn  10243:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10244:         }
                   10245:     }
                   10246:     if ($symb) {
                   10247:         my %recorded;
                   10248:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10249:         if ($returnhash{'version'}) {
                   10250:             my %lasthash=();
                   10251:             my $version;
                   10252:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10253:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10254:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10255:                 }
                   10256:             }
                   10257:             foreach my $key (keys(%lasthash)) {
                   10258:                 if ($key =~ /\.scantron$/) {
                   10259:                     my $value = &unescape($lasthash{$key});
                   10260:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10261:                     if ($value eq '') {
                   10262:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10263:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10264:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10265:                             }
                   10266:                         }
                   10267:                     } else {
                   10268:                         my @tocheck;
                   10269:                         my @items = split(//,$value);
                   10270:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10271:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10272:                             if (@items < $expected{$part_id}) {
                   10273:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10274:                                 my @singles = split(//,$fragment);
                   10275:                                 foreach my $pos (@singles) {
                   10276:                                     if ($pos eq ' ') {
                   10277:                                         push(@tocheck,$pos);
                   10278:                                     } else {
                   10279:                                         my $next = shift(@items);
                   10280:                                         push(@tocheck,$next);
                   10281:                                     }
                   10282:                                 }
                   10283:                             } else {
                   10284:                                 @tocheck = @items;
                   10285:                             }
                   10286:                             foreach my $letter (@tocheck) {
                   10287:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10288:                                     if ($letter !~ /^[A-J]$/) {
                   10289:                                         $letter = $scantron_config->{'Qoff'};
                   10290:                                     }
                   10291:                                     $recorded{$part_id} .= $letter;
                   10292:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10293:                                     my $digit;
                   10294:                                     if ($letter !~ /^[A-J]$/) {
                   10295:                                         $digit = $scantron_config->{'Qoff'};
                   10296:                                     } else {
                   10297:                                         $digit = $lettdig->{$letter};
                   10298:                                     }
                   10299:                                     $recorded{$part_id} .= $digit;
                   10300:                                 }
                   10301:                             }
                   10302:                         } else {
                   10303:                             @tocheck = @items;
                   10304:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10305:                                 my $curr_sub = shift(@tocheck);
                   10306:                                 my $digit;
                   10307:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10308:                                     $digit = $lettdig->{$curr_sub}-1;
                   10309:                                 }
                   10310:                                 if ($curr_sub eq 'J') {
                   10311:                                     $digit += scalar($numletts);
                   10312:                                 }
                   10313:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10314:                                     if ($j == $digit) {
                   10315:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10316:                                     } else {
                   10317:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10318:                                     }
                   10319:                                 }
                   10320:                             }
                   10321:                         }
                   10322:                     }
                   10323:                 }
                   10324:             }
                   10325:         }
1.554     raeburn  10326:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10327:             if ($recorded{$part_id} eq '') {
                   10328:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10329:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10330:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10331:                     }
                   10332:                 }
                   10333:             }
                   10334:             $record .= $recorded{$part_id};
                   10335:         }
                   10336:     }
                   10337:     return ($counter,$record);
                   10338: }
                   10339: 
1.75      albertel 10340: #-------- end of section for handling grading scantron forms -------
                   10341: #
                   10342: #-------------------------------------------------------------------
                   10343: 
1.72      ng       10344: #-------------------------- Menu interface -------------------------
                   10345: #
1.614     www      10346: #--- Href with symb and command ---
                   10347: 
                   10348: sub href_symb_cmd {
                   10349:     my ($symb,$cmd)=@_;
1.669     raeburn  10350:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       10351: }
                   10352: 
1.443     banghart 10353: sub grading_menu {
1.608     www      10354:     my ($request,$symb) = @_;
1.443     banghart 10355:     if (!$symb) {return '';}
                   10356: 
                   10357:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      10358:                   'command'=>'individual');
1.538     schulted 10359:     
1.598     www      10360:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10361: 
                   10362:     $fields{'command'}='ungraded';
                   10363:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10364: 
                   10365:     $fields{'command'}='table';
                   10366:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10367: 
                   10368:     $fields{'command'}='all_for_one';
                   10369:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10370: 
1.621     www      10371:     $fields{'command'}='downloadfilesselect';
                   10372:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10373: 
1.443     banghart 10374:     $fields{'command'} = 'csvform';
1.538     schulted 10375:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10376:     
1.443     banghart 10377:     $fields{'command'} = 'processclicker';
1.538     schulted 10378:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10379:     
1.443     banghart 10380:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10381:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      10382: 
                   10383:     $fields{'command'} = 'initialverifyreceipt';
                   10384:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 10385:     
1.598     www      10386:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10387:             items =>[
1.598     www      10388:                         {	linktext => 'Select individual students to grade',
                   10389:                     		url => $url1a,
1.538     schulted 10390:                     		permission => 'F',
1.636     wenzelju 10391:                     		icon => 'grade_students.png',
1.598     www      10392:                     		linktitle => 'Grade current resource for a selection of students.'
                   10393:                         }, 
1.764     raeburn  10394:                         {       linktext => 'Grade ungraded submissions',
1.598     www      10395:                                 url => $url1b,
                   10396:                                 permission => 'F',
1.636     wenzelju 10397:                                 icon => 'ungrade_sub.png',
1.598     www      10398:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 10399:                         },
1.598     www      10400: 
                   10401:                         {       linktext => 'Grading table',
                   10402:                                 url => $url1c,
                   10403:                                 permission => 'F',
1.636     wenzelju 10404:                                 icon => 'grading_table.png',
1.598     www      10405:                                 linktitle => 'Grade current resource for all students.'
                   10406:                         },
1.615     www      10407:                         {       linktext => 'Grade page/folder for one student',
1.598     www      10408:                                 url => $url1d,
                   10409:                                 permission => 'F',
1.636     wenzelju 10410:                                 icon => 'grade_PageFolder.png',
1.598     www      10411:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      10412:                         },
                   10413:                         {       linktext => 'Download submissions',
                   10414:                                 url => $url1e,
                   10415:                                 permission => 'F',
1.636     wenzelju 10416:                                 icon => 'download_sub.png',
1.621     www      10417:                                 linktitle => 'Download all students submissions.'
1.598     www      10418:                         }]},
                   10419:                          { categorytitle=>'Automated Grading',
                   10420:                items =>[
                   10421: 
1.538     schulted 10422:                 	    {	linktext => 'Upload Scores',
                   10423:                     		url => $url2,
                   10424:                     		permission => 'F',
                   10425:                     		icon => 'uploadscores.png',
                   10426:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10427:                 	    },
                   10428:                 	    {	linktext => 'Process Clicker',
                   10429:                     		url => $url3,
                   10430:                     		permission => 'F',
                   10431:                     		icon => 'addClickerInfoFile.png',
                   10432:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10433:                 	    },
1.587     raeburn  10434:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10435:                     		url => $url4,
                   10436:                     		permission => 'F',
1.636     wenzelju 10437:                     		icon => 'bubblesheet.png',
1.648     bisitz   10438:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      10439:                 	    },
1.616     www      10440:                             {   linktext => 'Verify Receipt Number',
1.602     www      10441:                                 url => $url5,
                   10442:                                 permission => 'F',
1.636     wenzelju 10443:                                 icon => 'receipt_number.png',
1.602     www      10444:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10445:                             }
                   10446: 
1.538     schulted 10447:                     ]
                   10448:             });
                   10449: 
1.443     banghart 10450:     # Create the menu
                   10451:     my $Str;
1.445     banghart 10452:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10453:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      10454:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 10455: 
1.602     www      10456:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10457:     return $Str;    
                   10458: }
                   10459: 
1.598     www      10460: sub ungraded {
                   10461:     my ($request)=@_;
                   10462:     &submit_options($request);
                   10463: }
                   10464: 
1.599     www      10465: sub submit_options_sequence {
1.608     www      10466:     my ($request,$symb) = @_;
1.599     www      10467:     if (!$symb) {return '';}
1.600     www      10468:     &commonJSfunctions($request);
                   10469:     my $result;
1.599     www      10470: 
1.600     www      10471:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10472:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      10473:     $result.=&selectfield(0).
1.601     www      10474:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      10475:             <div>
                   10476:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10477:             </div>
                   10478:         </div>
                   10479:   </form>';
                   10480:     return $result;
                   10481: }
                   10482: 
                   10483: sub submit_options_table {
1.608     www      10484:     my ($request,$symb) = @_;
1.600     www      10485:     if (!$symb) {return '';}
1.599     www      10486:     &commonJSfunctions($request);
1.746     raeburn  10487:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      10488:     my $result;
                   10489: 
                   10490:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10491:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      10492: 
1.745     raeburn  10493:     $result.=&selectfield(1,$is_tool).
1.601     www      10494:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      10495:             <div>
                   10496:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10497:             </div>
                   10498:         </div>
                   10499:   </form>';
                   10500:     return $result;
                   10501: }
1.443     banghart 10502: 
1.621     www      10503: sub submit_options_download {
                   10504:     my ($request,$symb) = @_;
                   10505:     if (!$symb) {return '';}
                   10506: 
1.773     raeburn  10507:     my $res_error;
                   10508:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10509:         &response_type($symb,\$res_error);
                   10510:     if ($res_error) {
                   10511:         $request->print(&mt('An error occurred retrieving response types'));
                   10512:         return;
                   10513:     }
                   10514:     unless ($numessay) {
                   10515:         $request->print(&mt('No essayresponse items found'));
                   10516:         return;
                   10517:     }
                   10518:     my $table;
                   10519:     if (ref($partlist) eq 'ARRAY') {
                   10520:         if (scalar(@$partlist) > 1 ) {
                   10521:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   10522:         }
                   10523:     }
                   10524: 
1.746     raeburn  10525:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      10526:     &commonJSfunctions($request);
                   10527: 
                   10528:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  10529:                $table."\n".
                   10530:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      10531:     $result.='
                   10532: <h2>
1.750     raeburn  10533:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  10534: </h2>'.&selectfield(1,$is_tool).'
1.621     www      10535:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   10536:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10537:             </div>
                   10538:           </div>
1.600     www      10539: 
                   10540: 
1.621     www      10541:   </form>';
                   10542:     return $result;
                   10543: }
                   10544: 
1.443     banghart 10545: #--- Displays the submissions first page -------
                   10546: sub submit_options {
1.608     www      10547:     my ($request,$symb) = @_;
1.72      ng       10548:     if (!$symb) {return '';}
                   10549: 
1.746     raeburn  10550:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       10551:     &commonJSfunctions($request);
1.473     albertel 10552:     my $result;
1.533     bisitz   10553: 
1.72      ng       10554:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10555: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  10556:     $result.=&selectfield(1,$is_tool).'
1.601     www      10557:                 <input type="hidden" name="command" value="submission" /> 
                   10558: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10559:             </div>
                   10560:           </div>
                   10561:   </form>';
                   10562:     return $result;
                   10563: }
1.533     bisitz   10564: 
1.601     www      10565: sub selectfield {
1.745     raeburn  10566:    my ($full,$is_tool)=@_;
                   10567:    my %options;
                   10568:    if ($is_tool) {
                   10569:        %options =
                   10570:            (&transtatus_options,
                   10571:             'select_form_order' => ['yes','incorrect','all']);
                   10572:    } else {
                   10573:        %options = 
                   10574:            (&substatus_options,
                   10575:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10576:    }
1.601     www      10577:    my $result='<div class="LC_columnSection">
1.537     harmsja  10578:   
1.533     bisitz   10579:     <fieldset>
                   10580:       <legend>
                   10581:        '.&mt('Sections').'
                   10582:       </legend>
1.601     www      10583:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10584:     </fieldset>
1.537     harmsja  10585:   
1.533     bisitz   10586:     <fieldset>
                   10587:       <legend>
                   10588:         '.&mt('Groups').'
                   10589:       </legend>
                   10590:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10591:     </fieldset>
1.537     harmsja  10592:   
1.533     bisitz   10593:     <fieldset>
                   10594:       <legend>
                   10595:         '.&mt('Access Status').'
                   10596:       </legend>
1.601     www      10597:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10598:     </fieldset>';
                   10599:     if ($full) {
1.745     raeburn  10600:         my $heading = &mt('Submission Status');
                   10601:         if ($is_tool) {
                   10602:             $heading = &mt('Transaction Status');
                   10603:         }
                   10604:         $result.='
1.533     bisitz   10605:     <fieldset>
                   10606:       <legend>
1.745     raeburn  10607:         '.$heading.'
1.601     www      10608:       </legend>'.
1.635     raeburn  10609:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      10610:    '</fieldset>';
                   10611:     }
                   10612:     $result.='</div><br />';
1.44      ng       10613:     return $result;
1.2       albertel 10614: }
                   10615: 
1.738     raeburn  10616: sub substatus_options {
                   10617:     return &Apache::lonlocal::texthash(
                   10618:                                       'yes'       => 'with submissions',
                   10619:                                       'queued'    => 'in grading queue',
                   10620:                                       'graded'    => 'with ungraded submissions',
                   10621:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10622:                                       'all'       => 'with any status',
                   10623:                                       );
1.738     raeburn  10624: }
                   10625: 
1.745     raeburn  10626: sub transtatus_options {
                   10627:     return &Apache::lonlocal::texthash(
                   10628:                                        'yes'       => 'with score transactions',
                   10629:                                        'incorrect' => 'with less than full credit',
                   10630:                                        'all'       => 'with any status',
                   10631:                                       );
                   10632: }
                   10633: 
1.285     albertel 10634: sub reset_perm {
                   10635:     undef(%perm);
                   10636: }
                   10637: 
                   10638: sub init_perm {
                   10639:     &reset_perm();
1.770     raeburn  10640:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 10641: 
                   10642: 	my $scope = $env{'request.course.id'};
                   10643: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10644: 
                   10645: 	    $scope .= '/'.$env{'request.course.sec'};
                   10646: 	    if ( $perm{$test_perm}=
                   10647: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10648: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10649: 	    } else {
                   10650: 		delete($perm{$test_perm});
                   10651: 	    }
1.285     albertel 10652: 	}
                   10653:     }
                   10654: }
                   10655: 
1.674     raeburn  10656: sub init_old_essays {
                   10657:     my ($symb,$apath,$adom,$aname) = @_;
                   10658:     if ($symb ne '') {
                   10659:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10660:         if (keys(%essays) > 0) {
                   10661:             $old_essays{$symb} = \%essays;
                   10662:         }
                   10663:     }
                   10664:     return;
                   10665: }
                   10666: 
                   10667: sub reset_old_essays {
                   10668:     undef(%old_essays);
                   10669: }
                   10670: 
1.400     www      10671: sub gather_clicker_ids {
1.408     albertel 10672:     my %clicker_ids;
1.400     www      10673: 
                   10674:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10675: 
                   10676:     # Set up a couple variables.
1.407     albertel 10677:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10678:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10679:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10680: 
1.407     albertel 10681:     foreach my $student (keys(%$classlist)) {
1.438     www      10682:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10683:         my $username = $classlist->{$student}->[$username_idx];
                   10684:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10685:         my $clickers =
1.408     albertel 10686: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10687:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10688:             $id=~s/^[\#0]+//;
1.421     www      10689:             $id=~s/[\-\:]//g;
1.407     albertel 10690:             if (exists($clicker_ids{$id})) {
1.408     albertel 10691: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10692:             } else {
1.408     albertel 10693: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10694:             }
                   10695:         }
                   10696:     }
1.407     albertel 10697:     return %clicker_ids;
1.400     www      10698: }
                   10699: 
1.402     www      10700: sub gather_adv_clicker_ids {
1.408     albertel 10701:     my %clicker_ids;
1.402     www      10702:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10703:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10704:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10705:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10706:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10707:             my ($puname,$pudom)=split(/\:/,$person);
                   10708:             my $clickers =
1.408     albertel 10709: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10710:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10711: 		$id=~s/^[\#0]+//;
1.421     www      10712:                 $id=~s/[\-\:]//g;
1.408     albertel 10713: 		if (exists($clicker_ids{$id})) {
                   10714: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10715: 		} else {
                   10716: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10717: 		}
1.405     www      10718:             }
1.402     www      10719:         }
                   10720:     }
1.407     albertel 10721:     return %clicker_ids;
1.402     www      10722: }
                   10723: 
1.413     www      10724: sub clicker_grading_parameters {
                   10725:     return ('gradingmechanism' => 'scalar',
                   10726:             'upfiletype' => 'scalar',
                   10727:             'specificid' => 'scalar',
                   10728:             'pcorrect' => 'scalar',
                   10729:             'pincorrect' => 'scalar');
                   10730: }
                   10731: 
1.400     www      10732: sub process_clicker {
1.608     www      10733:     my ($r,$symb)=@_;
1.400     www      10734:     if (!$symb) {return '';}
                   10735:     my $result=&checkforfile_js();
1.632     www      10736:     $result.=&Apache::loncommon::start_data_table().
                   10737:              &Apache::loncommon::start_data_table_header_row().
                   10738:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10739:              &Apache::loncommon::end_data_table_header_row().
                   10740:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10741: # Attempt to restore parameters from last session, set defaults if not present
                   10742:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10743:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10744:                                                  \%Saveable_Parameters);
                   10745:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10746:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10747:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10748:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10749: 
                   10750:     my %checked;
1.521     www      10751:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10752:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10753:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10754:        }
                   10755:     }
                   10756: 
1.632     www      10757:     my $upload=&mt("Evaluate File");
1.400     www      10758:     my $type=&mt("Type");
1.402     www      10759:     my $attendance=&mt("Award points just for participation");
                   10760:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10761:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10762:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10763:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10764:     my $pcorrect=&mt("Percentage points for correct solution");
                   10765:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10766:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10767: 						   {'iclicker' => 'i>clicker',
1.666     www      10768:                                                     'interwrite' => 'interwrite PRS',
                   10769:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10770:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10771:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10772: function sanitycheck() {
                   10773: // Accept only integer percentages
                   10774:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10775:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10776: // Find out grading choice
                   10777:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10778:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10779:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10780:       }
                   10781:    }
                   10782: // By default, new choice equals user selection
                   10783:    newgradingchoice=gradingchoice;
                   10784: // Not good to give more points for false answers than correct ones
                   10785:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10786:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10787:    }
                   10788: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10789:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10790:       document.forms.gradesupload.pcorrect.value=100;
                   10791:       document.forms.gradesupload.pincorrect.value=100;
                   10792:    }
                   10793: // If the values are different, cannot be attendance only
                   10794:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10795:        (gradingchoice=='attendance')) {
                   10796:        newgradingchoice='personnel';
                   10797:    }
                   10798: // Change grading choice to new one
                   10799:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10800:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10801:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10802:       } else {
                   10803:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10804:       }
                   10805:    }
                   10806: // Remember the old state
                   10807:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10808: }
1.597     wenzelju 10809: ENDUPFORM
                   10810:     $result.= <<ENDUPFORM;
1.400     www      10811: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10812: <input type="hidden" name="symb" value="$symb" />
                   10813: <input type="hidden" name="command" value="processclickerfile" />
                   10814: <input type="file" name="upfile" size="50" />
                   10815: <br /><label>$type: $selectform</label>
1.632     www      10816: ENDUPFORM
                   10817:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10818:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10819:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10820: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10821: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10822: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10823: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10824: <br />&nbsp;&nbsp;&nbsp;
                   10825: <input type="text" name="givenanswer" size="50" />
1.413     www      10826: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10827: ENDGRADINGFORM
1.766     raeburn  10828:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      10829:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10830:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10831: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10832: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  10833: </form>
1.632     www      10834: ENDPERCFORM
                   10835:     $result.='</td>'.
                   10836:              &Apache::loncommon::end_data_table_row().
                   10837:              &Apache::loncommon::end_data_table();
1.400     www      10838:     return $result;
                   10839: }
                   10840: 
                   10841: sub process_clicker_file {
1.766     raeburn  10842:     my ($r,$symb) = @_;
1.400     www      10843:     if (!$symb) {return '';}
1.413     www      10844: 
                   10845:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10846:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10847:                                               \%Saveable_Parameters);
1.598     www      10848:     my $result='';
1.404     www      10849:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10850: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10851: 	return $result;
1.404     www      10852:     }
1.522     www      10853:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10854:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10855:         return $result;
1.521     www      10856:     }
1.522     www      10857:     my $foundgiven=0;
1.521     www      10858:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10859:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10860:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10861:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10862:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10863:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10864:         $foundgiven=$#answers+1;
1.521     www      10865:     }
1.407     albertel 10866:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10867:     my %correct_ids;
1.404     www      10868:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10869: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10870:     }
                   10871:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10872: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10873: 	   $correct_id=~tr/a-z/A-Z/;
                   10874: 	   $correct_id=~s/\s//gs;
                   10875: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10876:            $correct_id=~s/[\-\:]//g;
1.414     www      10877:            if ($correct_id) {
                   10878: 	      $correct_ids{$correct_id}='specified';
                   10879:            }
                   10880:         }
1.400     www      10881:     }
1.404     www      10882:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10883: 	$result.=&mt('Score based on attendance only');
1.521     www      10884:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10885:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10886:     } else {
1.408     albertel 10887: 	my $number=0;
1.411     www      10888: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10889: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10890: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10891: 	    if ($correct_ids{$id} eq 'specified') {
                   10892: 		$result.=&mt('specified');
                   10893: 	    } else {
                   10894: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10895: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10896: 	    }
                   10897: 	    $number++;
                   10898: 	}
1.411     www      10899:         $result.="</p>\n";
1.710     bisitz   10900:         if ($number==0) {
                   10901:             $result .=
                   10902:                  &Apache::lonhtmlcommon::confirm_success(
                   10903:                      &mt('No IDs found to determine correct answer'),1);
                   10904:             return $result;
                   10905:         }
1.404     www      10906:     }
1.405     www      10907:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10908:         $result .=
                   10909:             &Apache::lonhtmlcommon::confirm_success(
                   10910:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10911:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10912:         return $result;
1.405     www      10913:     }
1.760     raeburn  10914:     my $mimetype;
                   10915:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10916:         my $mm = new File::MMagic;
                   10917:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10918:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10919:             $result.= '<p>'.
                   10920:                 &Apache::lonhtmlcommon::confirm_success(
                   10921:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   10922:             return $result;
                   10923:         }
                   10924:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10925:         $result .= '<p>'.
                   10926:             &Apache::lonhtmlcommon::confirm_success(
                   10927:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   10928:         return $result;
                   10929:     }
1.410     www      10930: 
                   10931: # Were able to get all the info needed, now analyze the file
                   10932: 
1.411     www      10933:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10934:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      10935:     $result.=&Apache::loncommon::start_data_table().
                   10936:              &Apache::loncommon::start_data_table_header_row().
                   10937:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10938:              &Apache::loncommon::end_data_table_header_row().
                   10939:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10940: <td>
1.410     www      10941: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10942: <input type="hidden" name="symb" value="$symb" />
                   10943: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10944: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10945: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10946: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10947: ENDHEADER
1.522     www      10948:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10949:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10950:     } 
1.408     albertel 10951:     my %responses;
                   10952:     my @questiontitles;
1.405     www      10953:     my $errormsg='';
                   10954:     my $number=0;
                   10955:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  10956:         if ($mimetype eq 'text/plain') {
                   10957:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10958:         } elsif ($mimetype eq 'text/html') {
                   10959:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10960:         }
                   10961:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10962:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  10963:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      10964:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10965:     }
1.411     www      10966:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10967:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10968:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10969:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10970:              '<br />';
1.522     www      10971:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10972:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      10973:        return $result;
1.522     www      10974:     } 
1.414     www      10975: # Remember Question Titles
                   10976: # FIXME: Possibly need delimiter other than ":"
                   10977:     for (my $i=0;$i<$number;$i++) {
                   10978:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10979:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10980:     }
1.411     www      10981:     my $correct_count=0;
                   10982:     my $student_count=0;
                   10983:     my $unknown_count=0;
1.414     www      10984: # Match answers with usernames
                   10985: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10986:     foreach my $id (keys(%responses)) {
1.410     www      10987:        if ($correct_ids{$id}) {
1.414     www      10988:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10989:           $correct_count++;
1.410     www      10990:        } elsif ($clicker_ids{$id}) {
1.437     www      10991:           if ($clicker_ids{$id}=~/\,/) {
                   10992: # More than one user with the same clicker!
1.632     www      10993:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10994:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10995:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10996:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10997:                            "<select name='multi".$id."'>";
                   10998:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10999:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   11000:              }
                   11001:              $result.='</select>';
                   11002:              $unknown_count++;
                   11003:           } else {
                   11004: # Good: found one and only one user with the right clicker
                   11005:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   11006:              $student_count++;
                   11007:           }
1.410     www      11008:        } else {
1.632     www      11009:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11010:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11011:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      11012:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11013:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   11014:                    "\n".&mt("Domain").": ".
                   11015:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  11016:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      11017:           $unknown_count++;
1.410     www      11018:        }
1.405     www      11019:     }
1.412     www      11020:     $result.='<hr />'.
                   11021:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      11022:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      11023:        if ($correct_count==0) {
1.696     bisitz   11024:           $errormsg.="Found no correct answers for grading!";
1.412     www      11025:        } elsif ($correct_count>1) {
1.414     www      11026:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      11027:        }
                   11028:     }
1.428     www      11029:     if ($number<1) {
                   11030:        $errormsg.="Found no questions.";
                   11031:     }
1.412     www      11032:     if ($errormsg) {
                   11033:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   11034:     } else {
                   11035:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   11036:     }
1.632     www      11037:     $result.='</form></td>'.
                   11038:              &Apache::loncommon::end_data_table_row().
                   11039:              &Apache::loncommon::end_data_table();
1.614     www      11040:     return $result;
1.400     www      11041: }
                   11042: 
1.405     www      11043: sub iclicker_eval {
1.406     www      11044:     my ($questiontitles,$responses)=@_;
1.405     www      11045:     my $number=0;
                   11046:     my $errormsg='';
                   11047:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      11048:         my %components=&Apache::loncommon::record_sep($line);
                   11049:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 11050: 	if ($entries[0] eq 'Question') {
                   11051: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   11052: 		$$questiontitles[$number]=$entries[$i];
                   11053: 		$number++;
                   11054: 	    }
                   11055: 	}
                   11056: 	if ($entries[0]=~/^\#/) {
                   11057: 	    my $id=$entries[0];
                   11058: 	    my @idresponses;
                   11059: 	    $id=~s/^[\#0]+//;
                   11060: 	    for (my $i=0;$i<$number;$i++) {
                   11061: 		my $idx=3+$i*6;
1.644     www      11062:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 11063: 		push(@idresponses,$entries[$idx]);
                   11064: 	    }
                   11065: 	    $$responses{$id}=join(',',@idresponses);
                   11066: 	}
1.405     www      11067:     }
                   11068:     return ($errormsg,$number);
                   11069: }
                   11070: 
1.760     raeburn  11071: sub iclickerxml_eval {
                   11072:     my ($questiontitles,$responses)=@_;
                   11073:     my $number=0;
                   11074:     my $errormsg='';
                   11075:     my @state;
                   11076:     my %respbyid;
                   11077:     my $p = HTML::Parser->new
                   11078:     (
                   11079:         xml_mode => 1,
                   11080:         start_h =>
                   11081:             [sub {
                   11082:                  my ($tagname,$attr) = @_;
                   11083:                  push(@state,$tagname);
                   11084:                  if ("@state" eq "ssn p") {
                   11085:                      my $title = $attr->{qn};
                   11086:                      $title =~ s/(^\s+|\s+$)//g;
                   11087:                      $questiontitles->[$number]=$title;
                   11088:                  } elsif ("@state" eq "ssn p v") {
                   11089:                      my $id = $attr->{id};
                   11090:                      my $entry = $attr->{ans};
                   11091:                      $id=~s/^[\#0]+//;
                   11092:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   11093:                      $respbyid{$id}[$number] = $entry;
                   11094:                  }
                   11095:             }, "tagname, attr"],
                   11096:          end_h =>
                   11097:                [sub {
                   11098:                    my ($tagname) = @_;
                   11099:                    if ("@state" eq "ssn p") {
                   11100:                        $number++;
                   11101:                    }
                   11102:                    pop(@state);
                   11103:                 }, "tagname"],
                   11104:     );
                   11105: 
                   11106:     $p->parse($env{'form.upfile'});
                   11107:     $p->eof;
                   11108:     foreach my $id (keys(%respbyid)) {
                   11109:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   11110:     }
                   11111:     return ($errormsg,$number);
                   11112: }
                   11113: 
1.419     www      11114: sub interwrite_eval {
                   11115:     my ($questiontitles,$responses)=@_;
                   11116:     my $number=0;
                   11117:     my $errormsg='';
1.420     www      11118:     my $skipline=1;
                   11119:     my $questionnumber=0;
                   11120:     my %idresponses=();
1.419     www      11121:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11122:         my %components=&Apache::loncommon::record_sep($line);
                   11123:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      11124:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   11125:         if ($entries[1] eq 'Response') { $skipline=1; }
                   11126:         next if $skipline;
                   11127:         if ($entries[0]!=$questionnumber) {
                   11128:            $questionnumber=$entries[0];
                   11129:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   11130:            $number++;
1.419     www      11131:         }
1.420     www      11132:         my $id=$entries[4];
                   11133:         $id=~s/^[\#0]+//;
1.421     www      11134:         $id=~s/^v\d*\://i;
                   11135:         $id=~s/[\-\:]//g;
1.420     www      11136:         $idresponses{$id}[$number]=$entries[6];
                   11137:     }
1.524     raeburn  11138:     foreach my $id (keys(%idresponses)) {
1.420     www      11139:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   11140:        $$responses{$id}=~s/^\s*\,//;
1.419     www      11141:     }
                   11142:     return ($errormsg,$number);
                   11143: }
                   11144: 
1.666     www      11145: sub turning_eval {
                   11146:     my ($questiontitles,$responses)=@_;
                   11147:     my $number=0;
                   11148:     my $errormsg='';
                   11149:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11150:         my %components=&Apache::loncommon::record_sep($line);
                   11151:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   11152:         if ($#entries>$number) { $number=$#entries; }
                   11153:         my $id=$entries[0];
                   11154:         my @idresponses;
                   11155:         $id=~s/^[\#0]+//;
                   11156:         unless ($id) { next; }
                   11157:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   11158:             $entries[$idx]=~s/\,/\;/g;
                   11159:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   11160:             push(@idresponses,$entries[$idx]);
                   11161:         }
                   11162:         $$responses{$id}=join(',',@idresponses);
                   11163:     }
                   11164:     for (my $i=1; $i<=$number; $i++) {
                   11165:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   11166:     }
                   11167:     return ($errormsg,$number);
                   11168: }
                   11169: 
                   11170: 
1.414     www      11171: sub assign_clicker_grades {
1.766     raeburn  11172:     my ($r,$symb) = @_;
1.414     www      11173:     if (!$symb) {return '';}
1.416     www      11174: # See which part we are saving to
1.582     raeburn  11175:     my $res_error;
                   11176:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   11177:     if ($res_error) {
                   11178:         return &navmap_errormsg();
                   11179:     }
1.416     www      11180: # FIXME: This should probably look for the first handgradeable part
                   11181:     my $part=$$partlist[0];
                   11182: # Start screen output
1.766     raeburn  11183:     my $result = &Apache::loncommon::start_data_table().
                   11184:                  &Apache::loncommon::start_data_table_header_row().
                   11185:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   11186:                  &Apache::loncommon::end_data_table_header_row().
                   11187:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11188: # Get correct result
                   11189: # FIXME: Possibly need delimiter other than ":"
                   11190:     my @correct=();
1.415     www      11191:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11192:     my $number=$env{'form.number'};
                   11193:     if ($gradingmechanism ne 'attendance') {
1.414     www      11194:        foreach my $key (keys(%env)) {
                   11195:           if ($key=~/^form\.correct\:/) {
                   11196:              my @input=split(/\,/,$env{$key});
                   11197:              for (my $i=0;$i<=$#input;$i++) {
                   11198:                  if (($correct[$i]) && ($input[$i]) &&
                   11199:                      ($correct[$i] ne $input[$i])) {
                   11200:                     $result.='<br /><span class="LC_warning">'.
                   11201:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11202:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      11203:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11204:                     $correct[$i]=$input[$i];
                   11205:                  }
                   11206:              }
                   11207:           }
                   11208:        }
1.415     www      11209:        for (my $i=0;$i<$number;$i++) {
1.644     www      11210:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11211:              $result.='<br /><span class="LC_error">'.
                   11212:                       &mt('No correct result given for question "[_1]"!',
                   11213:                           $env{'form.question:'.$i}).'</span>';
                   11214:           }
                   11215:        }
1.644     www      11216:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11217:     }
                   11218: # Start grading
1.415     www      11219:     my $pcorrect=$env{'form.pcorrect'};
                   11220:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11221:     my $storecount=0;
1.632     www      11222:     my %users=();
1.415     www      11223:     foreach my $key (keys(%env)) {
1.420     www      11224:        my $user='';
1.415     www      11225:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11226:           $user=$1;
                   11227:        }
                   11228:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11229:           my $id=$1;
                   11230:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11231:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11232:           } elsif ($env{'form.multi'.$id}) {
                   11233:              $user=$env{'form.multi'.$id};
1.420     www      11234:           }
                   11235:        }
1.632     www      11236:        if ($user) {
                   11237:           if ($users{$user}) {
                   11238:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   11239:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      11240:                       '</span><br />';
                   11241:           }
                   11242:           $users{$user}=1; 
1.415     www      11243:           my @answer=split(/\,/,$env{$key});
                   11244:           my $sum=0;
1.522     www      11245:           my $realnumber=$number;
1.415     www      11246:           for (my $i=0;$i<$number;$i++) {
1.576     www      11247:              if  ($correct[$i] eq '-') {
                   11248:                 $realnumber--;
1.766     raeburn  11249:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11250:                 if ($gradingmechanism eq 'attendance') {
                   11251:                    $sum+=$pcorrect;
1.576     www      11252:                 } elsif ($correct[$i] eq '*') {
1.522     www      11253:                    $sum+=$pcorrect;
1.415     www      11254:                 } else {
1.644     www      11255: # We actually grade if correct or not
                   11256:                    my $increment=$pincorrect;
                   11257: # Special case: numerical answer "0"
                   11258:                    if ($correct[$i] eq '0') {
                   11259:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11260:                          $increment=$pcorrect;
                   11261:                       }
                   11262: # General numerical answer, both evaluate to something non-zero
                   11263:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11264:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11265:                          $increment=$pcorrect;
                   11266:                       }
                   11267: # Must be just alphanumeric
                   11268:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11269:                       $increment=$pcorrect;
1.415     www      11270:                    }
1.644     www      11271:                    $sum+=$increment;
1.415     www      11272:                 }
                   11273:              }
                   11274:           }
1.522     www      11275:           my $ave=$sum/(100*$realnumber);
1.416     www      11276: # Store
                   11277:           my ($username,$domain)=split(/\:/,$user);
                   11278:           my %grades=();
                   11279:           $grades{"resource.$part.solved"}='correct_by_override';
                   11280:           $grades{"resource.$part.awarded"}=$ave;
                   11281:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11282:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11283:                                                  $env{'request.course.id'},
                   11284:                                                  $domain,$username);
                   11285:           if ($returncode ne 'ok') {
                   11286:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11287:           } else {
                   11288:              $storecount++;
                   11289:           }
1.415     www      11290:        }
                   11291:     }
                   11292: # We are done
1.549     hauer    11293:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      11294:              '</td>'.
                   11295:              &Apache::loncommon::end_data_table_row().
                   11296:              &Apache::loncommon::end_data_table();
1.614     www      11297:     return $result;
1.414     www      11298: }
                   11299: 
1.582     raeburn  11300: sub navmap_errormsg {
                   11301:     return '<div class="LC_error">'.
                   11302:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11303:            &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  11304:            '</div>';
                   11305: }
1.607     droeschl 11306: 
1.609     www      11307: sub startpage {
1.777     raeburn  11308:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  11309:     my %args;
                   11310:     if ($onload) {
                   11311:          my %loaditems = (
                   11312:                         'onload' => $onload,
                   11313:                       );
                   11314:          $args{'add_entries'} = \%loaditems;
                   11315:     }
1.671     raeburn  11316:     if ($nomenu) {
1.754     raeburn  11317:         $args{'only_body'} = 1; 
1.777     raeburn  11318:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  11319:     } else {
                   11320:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.754     raeburn  11321:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  11322:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  11323:         if ($env{'request.course.id'}) {
                   11324:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   11325:         }
1.671     raeburn  11326:     }
1.613     www      11327:     unless ($nodisplayflag) {
1.773     raeburn  11328:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      11329:     }
1.607     droeschl 11330: }
1.582     raeburn  11331: 
1.622     www      11332: sub select_problem {
                   11333:     my ($r)=@_;
1.632     www      11334:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  11335:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      11336:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11337:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11338: }
                   11339: 
1.1       albertel 11340: sub handler {
1.41      ng       11341:     my $request=$_[0];
1.434     albertel 11342:     &reset_caches();
1.646     raeburn  11343:     if ($request->header_only) {
                   11344:         &Apache::loncommon::content_type($request,'text/html');
                   11345:         $request->send_http_header;
                   11346:         return OK;
                   11347:     }
                   11348:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   11349: 
1.664     raeburn  11350: # see what command we need to execute
                   11351: 
                   11352:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11353:     my $command=$commands[0];
                   11354: 
1.646     raeburn  11355:     &init_perm();
                   11356:     if (!$env{'request.course.id'}) {
1.664     raeburn  11357:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11358:                 ($command =~ /^scantronupload/)) {
                   11359:             # Not in a course.
                   11360:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11361:             return HTTP_NOT_ACCEPTABLE;
                   11362:         }
1.646     raeburn  11363:     } elsif (!%perm) {
                   11364:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  11365:         return OK;
1.41      ng       11366:     }
1.646     raeburn  11367:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       11368:     $request->send_http_header;
1.646     raeburn  11369: 
1.160     albertel 11370:     if ($#commands > 0) {
                   11371: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11372:     }
1.608     www      11373: 
                   11374: # see what the symb is
                   11375: 
                   11376:     my $symb=$env{'form.symb'};
                   11377:     unless ($symb) {
                   11378:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11379:        $symb=&Apache::lonnet::symbread($url);
                   11380:     }
1.646     raeburn  11381:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      11382: 
1.513     foxr     11383:     $ssi_error = 0;
1.637     www      11384:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      11385: #
1.637     www      11386: # Not called from a resource, but inside a course
1.601     www      11387: #    
1.622     www      11388:         &startpage($request,undef,[],1,1);
                   11389:         &select_problem($request);
1.41      ng       11390:     } else {
1.104     albertel 11391: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  11392:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  11393:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11394:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11395:                     &choose_task_version_form($symb,$env{'form.student'},
                   11396:                                               $env{'form.userdom'});
                   11397:             }
1.773     raeburn  11398:             my $divforres;
                   11399:             if ($env{'form.student'} eq '') {
                   11400:                 $js .= &part_selector_js();
                   11401:                 $onload = "toggleParts('gradesub');";
                   11402:             } else {
                   11403:                 $divforres = 1;
                   11404:             }
1.778     raeburn  11405:             my $head_extra = $js;
                   11406:             unless ($env{'form.vProb'} eq 'no') {
1.779   ! raeburn  11407:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11408:                 if ($csslinks) {
                   11409:                     $head_extra .= "\n$csslinks";
                   11410:                 }
                   11411:             }
1.777     raeburn  11412:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   11413:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  11414:             if ($versionform) {
1.775     raeburn  11415:                 if ($divforres) {
                   11416:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   11417:                 }
1.671     raeburn  11418:                 $request->print($versionform);
                   11419:             }
1.773     raeburn  11420: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  11421:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11422:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11423:                 &choose_task_version_form($symb,$env{'form.student'},
                   11424:                                           $env{'form.userdom'},
                   11425:                                           $env{'form.inhibitmenu'});
1.778     raeburn  11426:             my $head_extra = $js;
                   11427:             unless ($env{'form.vProb'} eq 'no') {
1.779   ! raeburn  11428:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11429:                 if ($csslinks) {
                   11430:                     $head_extra .= "\n$csslinks";
                   11431:                 }
                   11432:             }
1.777     raeburn  11433:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   11434:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  11435:             if ($versionform) {
                   11436:                 $request->print($versionform);
                   11437:             }
                   11438:             $request->print('<br clear="all" />');
                   11439:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 11440: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      11441:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11442:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      11443: 	    &pickStudentPage($request,$symb);
1.103     albertel 11444: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  11445:             my $csslinks;
                   11446:             unless ($env{'form.vProb'} eq 'no') {
1.779   ! raeburn  11447:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  11448:             }
1.615     www      11449:             &startpage($request,$symb,
                   11450:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11451:                                        {href=>'',text=>'Select student'},
1.777     raeburn  11452:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      11453: 	    &displayPage($request,$symb);
1.104     albertel 11454: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      11455:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11456:                                        {href=>'',text=>'Select student'},
                   11457:                                        {href=>'',text=>'Grade student'},
                   11458:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      11459: 	    &updateGradeByPage($request,$symb);
1.104     albertel 11460: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  11461:             my $csslinks;
                   11462:             unless ($env{'form.vProb'} eq 'no') {
1.779   ! raeburn  11463:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11464:             }
1.619     www      11465:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  11466:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      11467: 	    &processGroup($request,$symb);
1.104     albertel 11468: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      11469:             &startpage($request,$symb);
                   11470: 	    $request->print(&grading_menu($request,$symb));
1.598     www      11471: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      11472:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      11473: 	    $request->print(&submit_options($request,$symb));
1.598     www      11474:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  11475:             my $js = &part_selector_js();
                   11476:             my $onload = "toggleParts('gradesub');";
                   11477:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11478:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      11479:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      11480:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      11481:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      11482:             $request->print(&submit_options_table($request,$symb));
1.598     www      11483:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      11484:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      11485:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 11486: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      11487:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      11488: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 11489: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      11490:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11491:                                        {href=>'',text=>'Store grades'}]);
1.608     www      11492: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 11493: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      11494:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11495:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11496:                                                                              text=>"Modify grades"},
                   11497:                                        {href=>'', text=>"Store grades"}]);
1.608     www      11498: 	    $request->print(&editgrades($request,$symb));
1.602     www      11499:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      11500:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      11501:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 11502: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      11503:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11504:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      11505: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      11506:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      11507:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      11508:             $request->print(&process_clicker($request,$symb));
1.400     www      11509:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      11510:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11511:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      11512:             $request->print(&process_clicker_file($request,$symb));
1.414     www      11513:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      11514:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11515:                                        {href=>'', text=>'Process clicker file'},
                   11516:                                        {href=>'', text=>'Store grades'}]);
1.608     www      11517:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 11518: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      11519:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11520: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 11521: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      11522:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11523: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 11524: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      11525:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11526: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 11527: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 11528: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      11529:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11530: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       11531: 	    } else {
1.257     albertel 11532: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11533: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       11534: 		} else {
1.257     albertel 11535: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       11536: 		}
1.627     www      11537:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11538: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       11539: 	    }
1.246     albertel 11540: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      11541:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11542: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 11543: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  11544:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11545:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      11546: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 11547:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      11548:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11549:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 11550: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      11551:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11552: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 11553: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      11554:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11555: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 11556:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  11557:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  11558:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11559:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      11560:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 11561:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  11562:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      11563:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11564:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  11565:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      11566:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11567:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  11568:         } elsif ($command eq 'scantronupload_delete' &&
                   11569:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   11570:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11571:             &scantron_upload_delete($request,$symb);
1.523     raeburn  11572:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      11573:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      11574:             $request->print(&checkscantron_results($request,$symb));
                   11575:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  11576:             my $js = &part_selector_js();
                   11577:             my $onload = "toggleParts('gradingMenu');";
                   11578:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11579:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      11580:             $request->print(&submit_options_download($request,$symb));
                   11581:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11582:             &startpage($request,$symb,
                   11583:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  11584:     {href=>'', text=>'Download submitted files'}],
                   11585:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  11586:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      11587:             &submit_download_link($request,$symb);
1.106     albertel 11588: 	} elsif ($command) {
1.620     www      11589:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   11590: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 11591: 	}
1.2       albertel 11592:     }
1.513     foxr     11593:     if ($ssi_error) {
                   11594: 	&ssi_print_error($request);
                   11595:     }
1.671     raeburn  11596:     if ($env{'form.inhibitmenu'}) {
                   11597:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  11598:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  11599:         &Apache::lonquickgrades::endGradeScreen($request);
                   11600:     }
1.434     albertel 11601:     &reset_caches();
1.646     raeburn  11602:     return OK;
1.44      ng       11603: }
                   11604: 
1.1       albertel 11605: 1;
                   11606: 
1.13      albertel 11607: __END__;
1.531     jms      11608: 
                   11609: 
                   11610: =head1 NAME
                   11611: 
                   11612: Apache::grades
                   11613: 
                   11614: =head1 SYNOPSIS
                   11615: 
                   11616: Handles the viewing of grades.
                   11617: 
                   11618: This is part of the LearningOnline Network with CAPA project
                   11619: described at http://www.lon-capa.org.
                   11620: 
                   11621: =head1 OVERVIEW
                   11622: 
                   11623: Do an ssi with retries:
1.715     bisitz   11624: While I'd love to factor out this with the version in lonprintout,
1.531     jms      11625: 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
                   11626: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11627: 
                   11628: At least the logic that drives this has been pulled out into loncommon.
                   11629: 
                   11630: 
                   11631: 
                   11632: ssi_with_retries - Does the server side include of a resource.
                   11633:                      if the ssi call returns an error we'll retry it up to
                   11634:                      the number of times requested by the caller.
1.715     bisitz   11635:                      If we still have a problem, no text is appended to the
1.531     jms      11636:                      output and we set some global variables.
                   11637:                      to indicate to the caller an SSI error occurred.  
                   11638:                      All of this is supposed to deal with the issues described
1.715     bisitz   11639:                      in LON-CAPA BZ 5631 see:
1.531     jms      11640:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11641:                      by informing the user that this happened.
                   11642: 
                   11643: Parameters:
                   11644:   resource   - The resource to include.  This is passed directly, without
                   11645:                interpretation to lonnet::ssi.
                   11646:   form       - The form hash parameters that guide the interpretation of the resource
                   11647:                
                   11648:   retries    - Number of retries allowed before giving up completely.
                   11649: Returns:
                   11650:   On success, returns the rendered resource identified by the resource parameter.
                   11651: Side Effects:
                   11652:   The following global variables can be set:
                   11653:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11654:                               It is up to the caller to initialize this to false
                   11655:                               if desired.
                   11656:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11657:                               of the resource that could not be rendered by the ssi
                   11658:                               call.
                   11659:    ssi_error_message   - The error string fetched from the ssi response
                   11660:                               in the event of an error.
                   11661: 
                   11662: 
                   11663: =head1 HANDLER SUBROUTINE
                   11664: 
                   11665: ssi_with_retries()
                   11666: 
                   11667: =head1 SUBROUTINES
                   11668: 
                   11669: =over
                   11670: 
1.671     raeburn  11671: =head1 Routines to display previous version of a Task for a specific student
                   11672: 
                   11673: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   11674: can receive another opportunity. Access to tasks is slot-based. If a slot
                   11675: requires a proctor to check-in the student, a new version of the Task will
                   11676: be created when the student is checked in to the new opportunity.
                   11677: 
                   11678: If a particular student has tried two or more versions of a particular task,
                   11679: the submission screen provides a user with vgr privileges (e.g., a Course
                   11680: Coordinator) the ability to display a previous version worked on by the
                   11681: student.  By default, the current version is displayed. If a previous version
                   11682: has been selected for display, submission data are only shown that pertain
                   11683: to that particular version, and the interface to submit grades is not shown.
                   11684: 
                   11685: =over 4
                   11686: 
                   11687: =item show_previous_task_version()
                   11688: 
                   11689: Displays a specified version of a student's Task, as the student sees it.
                   11690: 
                   11691: Inputs: 2
                   11692:         request - request object
                   11693:         symb    - unique symb for current instance of resource
                   11694: 
                   11695: Output: None.
                   11696: 
                   11697: Side Effects: calls &show_problem() to print version of Task, with
                   11698:               version contained in form item: $env{'form.previousversion'}
                   11699: 
                   11700: =item choose_task_version_form()
                   11701: 
                   11702: Displays a web form used to select which version of a student's view of a
                   11703: Task should be displayed.  Either launches a pop-up window, or replaces
                   11704: content in existing pop-up, or replaces page in main window.
                   11705: 
                   11706: Inputs: 4
                   11707:         symb    - unique symb for current instance of resource
                   11708:         uname   - username of student
                   11709:         udom    - domain of student
                   11710:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11711:                   breadcrumbs etc., are displayed
                   11712: 
                   11713: Output: 4
                   11714:         current   - student's current version
                   11715:         displayed - student's version being displayed
                   11716:         result    - scalar containing HTML for web form used to switch to
                   11717:                     a different version (or a link to close window, if pop-up).
                   11718:         js        - javascript for processing selection in versions web form
                   11719: 
                   11720: Side Effects: None.
                   11721: 
                   11722: =item previous_display_javascript()
                   11723: 
                   11724: Inputs: 2
                   11725:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11726:                   breadcrumbs etc., are displayed.
                   11727:         current - student's current version number.
                   11728: 
                   11729: Output: 1
                   11730:         js      - javascript for processing selection in versions web form.
                   11731: 
                   11732: Side Effects: None.
                   11733: 
                   11734: =back
                   11735: 
                   11736: =head1 Routines to process bubblesheet data.
                   11737: 
                   11738: =over 4
                   11739: 
1.531     jms      11740: =item scantron_get_correction() : 
                   11741: 
                   11742:    Builds the interface screen to interact with the operator to fix a
                   11743:    specific error condition in a specific scanline
                   11744: 
                   11745:  Arguments:
                   11746:     $r           - Apache request object
                   11747:     $i           - number of the current scanline
                   11748:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  11749:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11750:     $line        - full contents of the current scanline
                   11751:     $error       - error condition, valid values are
                   11752:                    'incorrectCODE', 'duplicateCODE',
                   11753:                    'doublebubble', 'missingbubble',
                   11754:                    'duplicateID', 'incorrectID'
                   11755:     $arg         - extra information needed
                   11756:        For errors:
                   11757:          - duplicateID   - paper number that this studentID was seen before on
                   11758:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11759:                            seen on before
                   11760:          - incorrectCODE - current incorrect CODE 
                   11761:          - doublebubble  - array ref of the bubble lines that have double
                   11762:                            bubble errors
                   11763:          - missingbubble - array ref of the bubble lines that have missing
                   11764:                            bubble errors
                   11765: 
1.691     raeburn  11766:    $randomorder - True if exam folder has randomorder set
                   11767:    $randompick  - True if exam folder has randompick set
                   11768:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11769:                      for current line to question number used for same question
                   11770:                      in "Master Seqence" (as seen by Course Coordinator).
                   11771:    $startline   - Reference to hash where key is question number (0 is first)
                   11772:                   and value is number of first bubble line for current student
                   11773:                   or code-based randompick and/or randomorder.
                   11774: 
                   11775: 
                   11776: 
1.531     jms      11777: =item  scantron_get_maxbubble() : 
                   11778: 
1.582     raeburn  11779:    Arguments:
                   11780:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11781:                       failure to retrieve a navmap object.
                   11782:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11783:        calling routine should trap the error condition and display the warning
                   11784:        found in &navmap_errormsg().
                   11785: 
1.649     raeburn  11786:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11787: 
1.531     jms      11788:    Returns the maximum number of bubble lines that are expected to
                   11789:    occur. Does this by walking the selected sequence rendering the
                   11790:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11791:    for what the current value of the problem counter is.
                   11792: 
                   11793:    Caches the results to $env{'form.scantron_maxbubble'},
                   11794:    $env{'form.scantron.bubble_lines.n'}, 
                   11795:    $env{'form.scantron.first_bubble_line.n'} and
                   11796:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11797:    which are the total number of bubble lines, the number of bubble
1.531     jms      11798:    lines for response n and number of the first bubble line for response n,
                   11799:    and a comma separated list of numbers of bubble lines for sub-questions
                   11800:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11801: 
                   11802: 
                   11803: =item  scantron_validate_missingbubbles() : 
                   11804: 
                   11805:    Validates all scanlines in the selected file to not have any
                   11806:     answers that don't have bubbles that have not been verified
                   11807:     to be bubble free.
                   11808: 
                   11809: =item  scantron_process_students() : 
                   11810: 
1.659     raeburn  11811:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11812: 
                   11813:    The parsed scanline hash is added to %env 
                   11814: 
                   11815:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11816:    foreach resource , with the form data of
                   11817: 
                   11818: 	'submitted'     =>'scantron' 
                   11819: 	'grade_target'  =>'grade',
                   11820: 	'grade_username'=> username of student
                   11821: 	'grade_domain'  => domain of student
                   11822: 	'grade_courseid'=> of course
                   11823: 	'grade_symb'    => symb of resource to grade
                   11824: 
                   11825:     This triggers a grading pass. The problem grading code takes care
                   11826:     of converting the bubbled letter information (now in %env) into a
                   11827:     valid submission.
                   11828: 
                   11829: =item  scantron_upload_scantron_data() :
                   11830: 
1.659     raeburn  11831:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11832: 
                   11833: =item  scantron_upload_scantron_data_save() : 
                   11834: 
                   11835:    Adds a provided bubble information data file to the course if user
1.770     raeburn  11836:    has the correct privileges to do so.
                   11837: 
                   11838: = item scantron_upload_delete() :
                   11839: 
                   11840:    Deletes a previously uploaded bubble information data file, if user
                   11841:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      11842: 
                   11843: =item  valid_file() :
                   11844: 
                   11845:    Validates that the requested bubble data file exists in the course.
                   11846: 
                   11847: =item  scantron_download_scantron_data() : 
                   11848: 
                   11849:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11850:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11851:    course.
                   11852: 
                   11853: =item  scantron_validate_ID() : 
                   11854: 
                   11855:    Validates all scanlines in the selected file to not have any
1.556     weissno  11856:    invalid or underspecified student/employee IDs
1.531     jms      11857: 
1.582     raeburn  11858: =item navmap_errormsg() :
                   11859: 
                   11860:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11861:    Should be called whenever the request to instantiate a navmap object fails.
                   11862: 
                   11863: =back
1.582     raeburn  11864: 
1.531     jms      11865: =back
                   11866: 
                   11867: =cut

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