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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.782   ! raeburn     4: # $Id: grades.pm,v 1.781 2021/01/05 21:53:44 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.752     raeburn    49: use Apache::lontexconvert();
1.170     albertel   50: use String::Similarity;
1.760     raeburn    51: use HTML::Parser();
                     52: use File::MMagic;
1.359     www        53: use LONCAPA;
                     54: 
1.315     bowersj2   55: use POSIX qw(floor);
1.87      www        56: 
1.435     foxr       57: 
1.513     foxr       58: 
1.435     foxr       59: my %perm=();
1.674     raeburn    60: my %old_essays=();
1.447     foxr       61: 
1.513     foxr       62: #  These variables are used to recover from ssi errors
                     63: 
                     64: my $ssi_retries = 5;
                     65: my $ssi_error;
                     66: my $ssi_error_resource;
                     67: my $ssi_error_message;
                     68: 
                     69: 
                     70: sub ssi_with_retries {
                     71:     my ($resource, $retries, %form) = @_;
                     72:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     73:     if ($response->is_error) {
                     74: 	$ssi_error          = 1;
                     75: 	$ssi_error_resource = $resource;
                     76: 	$ssi_error_message  = $response->code . " " . $response->message;
                     77:     }
                     78: 
                     79:     return $content;
                     80: 
                     81: }
                     82: #
                     83: #  Prodcuces an ssi retry failure error message to the user:
                     84: #
                     85: 
                     86: sub ssi_print_error {
                     87:     my ($r) = @_;
1.516     raeburn    88:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     89:     $r->print('
                     90: <br />
                     91: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     92: <p>
                     93: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     94: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     95: '.&mt('Error:').' '.$ssi_error_message.'
                     96: </p>
                     97: <p>'.
                     98: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     99: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                    100: '</p>');
                    101:     return;
1.513     foxr      102: }
                    103: 
1.44      ng        104: #
1.146     albertel  105: # --- Retrieve the parts from the metadata file.---
1.598     www       106: # Returns an array of everything that the resources stores away
                    107: #
                    108: 
1.44      ng        109: sub getpartlist {
1.582     raeburn   110:     my ($symb,$errorref) = @_;
1.439     albertel  111: 
                    112:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   113:     unless (ref($navmap)) {
                    114:         if (ref($errorref)) { 
                    115:             $$errorref = 'navmap';
                    116:             return;
                    117:         }
                    118:     }
1.439     albertel  119:     my $res      = $navmap->getBySymb($symb);
                    120:     my $partlist = $res->parts();
                    121:     my $url      = $res->src();
1.745     raeburn   122:     my $toolsymb;
                    123:     if ($url =~ /ext\.tool$/) {
                    124:         $toolsymb = $symb;
                    125:     }
                    126:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
1.439     albertel  127: 
1.146     albertel  128:     my @stores;
1.439     albertel  129:     foreach my $part (@{ $partlist }) {
1.146     albertel  130: 	foreach my $key (@metakeys) {
                    131: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    132: 	}
                    133:     }
                    134:     return @stores;
1.2       albertel  135: }
                    136: 
1.129     ng        137: #--- Format fullname, username:domain if different for display
                    138: #--- Use anywhere where the student names are listed
                    139: sub nameUserString {
                    140:     my ($type,$fullname,$uname,$udom) = @_;
                    141:     if ($type eq 'header') {
1.485     albertel  142: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        143:     } else {
1.398     albertel  144: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    145: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        146:     }
                    147: }
                    148: 
1.44      ng        149: #--- Get the partlist and the response type for a given problem. ---
1.773     raeburn   150: #--- Count responseIDs, essayresponse items, and dropbox items ---
1.623     www       151: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        152: sub response_type {
1.582     raeburn   153:     my ($symb,$response_error) = @_;
1.377     albertel  154: 
                    155:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   156:     unless (ref($navmap)) {
                    157:         if (ref($response_error)) {
                    158:             $$response_error = 1;
                    159:         }
                    160:         return;
                    161:     }
1.377     albertel  162:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   163:     unless (ref($res)) {
                    164:         $$response_error = 1;
                    165:         return;
                    166:     }
1.377     albertel  167:     my $partlist = $res->parts();
1.773     raeburn   168:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
1.392     albertel  169:     my %vPart = 
                    170: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  171:     my (%response_types,%handgrade);
                    172:     foreach my $part (@{ $partlist }) {
1.392     albertel  173: 	next if (%vPart && !exists($vPart{$part}));
                    174: 
1.377     albertel  175: 	my @types = $res->responseType($part);
                    176: 	my @ids = $res->responseIds($part);
                    177: 	for (my $i=0; $i < scalar(@ids); $i++) {
1.773     raeburn   178:             $numresp ++;
1.377     albertel  179: 	    $response_types{$part}{$ids[$i]} = $types[$i];
1.773     raeburn   180:             if ($types[$i] eq 'essay') {
                    181:                 $numessay ++;
                    182:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
                    183:                     $numdropbox ++;
                    184:                 }
                    185:             }
1.377     albertel  186: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    187: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    188: 				     '.handgrade',$symb);
1.41      ng        189: 	}
                    190:     }
1.773     raeburn   191:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
1.39      ng        192: }
                    193: 
1.375     albertel  194: sub flatten_responseType {
                    195:     my ($responseType) = @_;
                    196:     my @part_response_id =
                    197: 	map { 
                    198: 	    my $part = $_;
                    199: 	    map {
                    200: 		[$part,$_]
                    201: 		} sort(keys(%{ $responseType->{$part} }));
                    202: 	} sort(keys(%$responseType));
                    203:     return @part_response_id;
                    204: }
                    205: 
1.207     albertel  206: sub get_display_part {
1.324     albertel  207:     my ($partID,$symb)=@_;
1.207     albertel  208:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    209:     if (defined($display) and $display ne '') {
1.577     bisitz    210:         $display.= ' (<span class="LC_internal_info">'
                    211:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  212:     } else {
                    213: 	$display=$partID;
                    214:     }
                    215:     return $display;
                    216: }
1.269     raeburn   217: 
1.773     raeburn   218: #--- Show parts and response type
                    219: sub showResourceInfo {
                    220:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
                    221:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
                    222:         return '<br clear="all">';
                    223:     }
                    224:     my $coltitle = &mt('Problem Part Shown');
                    225:     if ($checkboxes) {
                    226:         $coltitle = &mt('Problem Part');
                    227:     } else {
                    228:         my $checkedparts = 0;
                    229:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                    230:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
                    231:                 $checkedparts ++;
                    232:             }
                    233:         }
                    234:         if ($checkedparts == scalar(@{$partlist})) {
                    235:             return '<br clear="all">';
                    236:         }
                    237:         if ($uploads) {
                    238:             $coltitle = &mt('Problem Part Selected');
                    239:         }
                    240:     }
                    241:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
                    242:     if ($checkboxes) {
                    243:         my $legend = &mt('Parts to display');
                    244:         if ($uploads) {
                    245:             $legend = &mt('Part(s) with dropbox');
                    246:         }
                    247:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
                    248:                    '<span class="LC_nobreak">'.
                    249:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
                    250:                    &mt('All parts').'</label>'.('&nbsp;'x2).
                    251:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
                    252:                    &mt('Selected parts').'</label></span>'.
                    253:                    '<div id="LC_partselector" style="display:none">';
                    254:     }
                    255:     $result .= &Apache::loncommon::start_data_table()
                    256:               .&Apache::loncommon::start_data_table_header_row();
                    257:     if ($checkboxes) {
                    258:         $result .= '<th>'.&mt('Display?').'</th>';
                    259:     }
                    260:     $result .= '<th>'.$coltitle.'</th>'
                    261:               .'<th>'.&mt('Res. ID').'</th>'
                    262:               .'<th>'.&mt('Type').'</th>'
                    263:               .&Apache::loncommon::end_data_table_header_row();
                    264:     my %partsseen;
                    265:     foreach my $partID (sort(keys(%$responseType))) {
                    266:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    267:             my $responsetype = $responseType->{$partID}->{$resID};
                    268:             if ($uploads) {
                    269:                 next unless ($responsetype eq 'essay');
                    270:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
                    271:             }
                    272:             my $display_part=&get_display_part($partID,$symb);
                    273:             if (exists($partsseen{$partID})) {
                    274:                 $result.=&Apache::loncommon::continue_data_table_row();
                    275:             } else {
                    276:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
                    277:                 $result.=&Apache::loncommon::start_data_table_row().
                    278:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
                    279:                 if ($checkboxes) {
                    280:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
                    281:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
                    282:                 } else {
                    283:                     $result.=$display_part.'</td>';
                    284:                 }
                    285:             }
                    286:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
                    287:                     .'<td>'.&mt($responsetype).'</td>'
                    288:                     .&Apache::loncommon::end_data_table_row();
                    289:         }
                    290:     }
                    291:     $result.=&Apache::loncommon::end_data_table();
                    292:     if ($checkboxes) {
                    293:         $result .= '</div></fieldset>';
                    294:     }
                    295:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
1.775     raeburn   296:     if (!keys(%partsseen)) {
                    297:         $result = '';
                    298:         if ($uploads) {
                    299:             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
                    300:                    '<p class="LC_info">'.
                    301:                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
                    302:                    '</p>';
                    303:         } else {
                    304:             return '<br clear="all" />';
                    305:         }
                    306:     }
1.773     raeburn   307:     return $result;
                    308: }
                    309: 
                    310: sub part_selector_js {
                    311:     my $js = <<"END";
                    312: function toggleParts(formname) {
                    313:     if (document.getElementById('LC_partselector')) {
                    314:         var index = '';
                    315:         if (document.forms.length) {
                    316:             for (var i=0; i<document.forms.length; i++) {
                    317:                 if (document.forms[i].name == formname) {
                    318:                     index = i;
                    319:                     break;
                    320:                 }
                    321:             }
                    322:         }
                    323:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
                    324:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
                    325:                 if (document.forms[index].elements['chooseparts'][i].checked) {
                    326:                    var val = document.forms[index].elements['chooseparts'][i].value;
                    327:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
                    328:                         document.getElementById('LC_partselector').style.display = 'block';
                    329:                     } else {
                    330:                         document.getElementById('LC_partselector').style.display = 'none';
                    331:                     }
                    332:                 }
                    333:             }
                    334:         }
                    335:     }
                    336: }
                    337: END
                    338:     return &Apache::lonhtmlcommon::scripttag($js);
                    339: }
                    340: 
1.434     albertel  341: sub reset_caches {
                    342:     &reset_analyze_cache();
                    343:     &reset_perm();
1.674     raeburn   344:     &reset_old_essays();
1.434     albertel  345: }
                    346: 
                    347: {
                    348:     my %analyze_cache;
1.557     raeburn   349:     my %analyze_cache_formkeys;
1.148     albertel  350: 
1.434     albertel  351:     sub reset_analyze_cache {
                    352: 	undef(%analyze_cache);
1.557     raeburn   353:         undef(%analyze_cache_formkeys);
1.434     albertel  354:     }
                    355: 
                    356:     sub get_analyze {
1.649     raeburn   357: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  358: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   359:         if ($type eq 'randomizetry') {
                    360:             if ($trial ne '') {
                    361:                 $key .= "\0".$trial;
                    362:             }
                    363:         }
1.557     raeburn   364: 	if (exists($analyze_cache{$key})) {
                    365:             my $getupdate = 0;
                    366:             if (ref($add_to_hash) eq 'HASH') {
                    367:                 foreach my $item (keys(%{$add_to_hash})) {
                    368:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    369:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    370:                             $getupdate = 1;
                    371:                             last;
                    372:                         }
                    373:                     } else {
                    374:                         $getupdate = 1;
                    375:                     }
                    376:                 }
                    377:             }
                    378:             if (!$getupdate) {
                    379:                 return $analyze_cache{$key};
                    380:             }
                    381:         }
1.434     albertel  382: 
                    383: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    384: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   385:         my %form = ('grade_target'      => 'analyze',
                    386:                     'grade_domain'      => $udom,
                    387:                     'grade_symb'        => $symb,
                    388:                     'grade_courseid'    =>  $env{'request.course.id'},
                    389:                     'grade_username'    => $uname,
                    390:                     'grade_noincrement' => $no_increment);
1.649     raeburn   391:         if ($bubbles_per_row ne '') {
                    392:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    393:         }
1.640     raeburn   394:         if ($type eq 'randomizetry') {
                    395:             $form{'grade_questiontype'} = $type;
                    396:             if ($rndseed ne '') {
                    397:                 $form{'grade_rndseed'} = $rndseed;
                    398:             }
                    399:         }
1.557     raeburn   400:         if (ref($add_to_hash)) {
                    401:             %form = (%form,%{$add_to_hash});
1.640     raeburn   402:         }
1.557     raeburn   403: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  404: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    405: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   406:         if (ref($add_to_hash) eq 'HASH') {
                    407:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    408:         } else {
                    409:             $analyze_cache_formkeys{$key} = {};
                    410:         }
1.434     albertel  411: 	return $analyze_cache{$key} = \%analyze;
                    412:     }
                    413: 
                    414:     sub get_order {
1.640     raeburn   415: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    416: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  417: 	return $analyze->{"$partid.$respid.shown"};
                    418:     }
                    419: 
                    420:     sub get_radiobutton_correct_foil {
1.640     raeburn   421: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    422: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    423:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   424:         if (ref($foils) eq 'ARRAY') {
                    425: 	    foreach my $foil (@{$foils}) {
                    426: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    427: 		    return $foil;
                    428: 	        }
1.434     albertel  429: 	    }
                    430: 	}
                    431:     }
1.554     raeburn   432: 
                    433:     sub scantron_partids_tograde {
1.741     raeburn   434:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   435:         my (%analysis,@parts);
                    436:         if (ref($resource)) {
                    437:             my $symb = $resource->symb();
1.557     raeburn   438:             my $add_to_form;
                    439:             if ($check_for_randomlist) {
                    440:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    441:             }
1.741     raeburn   442:             if ($scancode) {
                    443:                 if (ref($add_to_form) eq 'HASH') {
                    444:                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    445:                 } else {
                    446:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    447:                 }
                    448:             }
1.767     raeburn   449:             my $analyze =
1.649     raeburn   450:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    451:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   452:             if (ref($analyze) eq 'HASH') {
                    453:                 %analysis = %{$analyze};
                    454:             }
                    455:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    456:                 foreach my $part (@{$analysis{'parts'}}) {
                    457:                     my ($id,$respid) = split(/\./,$part);
                    458:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    459:                         push(@parts,$part);
                    460:                     }
                    461:                 }
                    462:             }
                    463:         }
                    464:         return (\%analysis,\@parts);
                    465:     }
                    466: 
1.148     albertel  467: }
1.434     albertel  468: 
1.118     ng        469: #--- Clean response type for display
1.335     albertel  470: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    471: #        response types only.
1.118     ng        472: sub cleanRecord {
1.336     albertel  473:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   474: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  475:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  476:     if ($response =~ /^(option|rank)$/) {
                    477: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     478:         my @answer = %answer;
1.767     raeburn   479:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  480: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    481: 	my ($toprow,$bottomrow);
                    482: 	foreach my $foil (@$order) {
                    483: 	    if ($grading{$foil} == 1) {
                    484: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    485: 	    } else {
                    486: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    487: 	    }
1.398     albertel  488: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  489: 	}
                    490: 	return '<blockquote><table border="1">'.
1.466     albertel  491: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    492: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   493: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  494:     } elsif ($response eq 'match') {
                    495: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     496:         my @answer = %answer;
1.767     raeburn   497:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  498: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    499: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    500: 	my ($toprow,$middlerow,$bottomrow);
                    501: 	foreach my $foil (@$order) {
                    502: 	    my $item=shift(@items);
                    503: 	    if ($grading{$foil} == 1) {
                    504: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  505: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  506: 	    } else {
                    507: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  508: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  509: 	    }
1.398     albertel  510: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        511: 	}
1.126     ng        512: 	return '<blockquote><table border="1">'.
1.466     albertel  513: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    514: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  515: 	    $middlerow.'</tr>'.
1.466     albertel  516: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   517: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  518:     } elsif ($response eq 'radiobutton') {
                    519: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     520:         my @answer = %answer;
                    521:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  522: 	my ($toprow,$bottomrow);
1.434     albertel  523: 	my $correct = 
1.640     raeburn   524: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  525: 	foreach my $foil (@$order) {
1.148     albertel  526: 	    if (exists($answer{$foil})) {
1.434     albertel  527: 		if ($foil eq $correct) {
1.466     albertel  528: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  529: 		} else {
1.466     albertel  530: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  531: 		}
                    532: 	    } else {
1.466     albertel  533: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  534: 	    }
1.398     albertel  535: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  536: 	}
                    537: 	return '<blockquote><table border="1">'.
1.466     albertel  538: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    539: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   540: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  541:     } elsif ($response eq 'essay') {
1.257     albertel  542: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        543: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  544: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    545: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        546: 
1.257     albertel  547: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    548: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    549: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    550: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    551: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    552: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        553: 	}
1.751     raeburn   554:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
1.730     kruse     555: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  556:     } elsif ( $response eq 'organic') {
1.721     bisitz    557:         my $result=&mt('Smile representation: [_1]',
                    558:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  559: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    560: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    561: 	return $result;
1.335     albertel  562:     } elsif ( $response eq 'Task') {
                    563: 	if ( $answer eq 'SUBMITTED') {
                    564: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  565: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  566: 	    return $result;
                    567: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    568: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    569: 			       keys(%{$record}));
                    570: 	    return join('<br />',($version,@matches));
                    571: 			       
                    572: 			       
                    573: 	} else {
                    574: 	    my $result =
                    575: 		'<p>'
                    576: 		.&mt('Overall result: [_1]',
                    577: 		     $record->{$version."resource.$respid.$partid.status"})
                    578: 		.'</p>';
                    579: 	    
                    580: 	    $result .= '<ul>';
                    581: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    582: 			     keys(%{$record}));
                    583: 	    foreach my $grade (sort(@grade)) {
                    584: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    585: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    586: 				     $dim, $record->{$grade}).
                    587: 			  '</li>';
                    588: 	    }
                    589: 	    $result.='</ul>';
                    590: 	    return $result;
                    591: 	}
1.716     bisitz    592:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    593:         # Respect multiple input fields, see Bug #5409
1.440     albertel  594: 	$answer = 
                    595: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    596: 							      $answer);
1.720     kruse     597: 	return $answer;
1.122     ng        598:     }
1.720     kruse     599:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        600: }
                    601: 
                    602: #-- A couple of common js functions
                    603: sub commonJSfunctions {
                    604:     my $request = shift;
1.597     wenzelju  605:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        606:     function radioSelection(radioButton) {
                    607: 	var selection=null;
                    608: 	if (radioButton.length > 1) {
                    609: 	    for (var i=0; i<radioButton.length; i++) {
                    610: 		if (radioButton[i].checked) {
                    611: 		    return radioButton[i].value;
                    612: 		}
                    613: 	    }
                    614: 	} else {
                    615: 	    if (radioButton.checked) return radioButton.value;
                    616: 	}
                    617: 	return selection;
                    618:     }
                    619: 
                    620:     function pullDownSelection(selectOne) {
                    621: 	var selection="";
                    622: 	if (selectOne.length > 1) {
                    623: 	    for (var i=0; i<selectOne.length; i++) {
                    624: 		if (selectOne[i].selected) {
                    625: 		    return selectOne[i].value;
                    626: 		}
                    627: 	    }
                    628: 	} else {
1.138     albertel  629:             // only one value it must be the selected one
                    630: 	    return selectOne.value;
1.118     ng        631: 	}
                    632:     }
                    633: COMMONJSFUNCTIONS
                    634: }
                    635: 
1.44      ng        636: #--- Dumps the class list with usernames,list of sections,
                    637: #--- section, ids and fullnames for each user.
                    638: sub getclasslist {
1.750     raeburn   639:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  640:     my @getsec;
1.450     banghart  641:     my @getgroup;
1.442     banghart  642:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  643:     if (!ref($getsec)) {
                    644: 	if ($getsec ne '' && $getsec ne 'all') {
                    645: 	    @getsec=($getsec);
                    646: 	}
                    647:     } else {
                    648: 	@getsec=@{$getsec};
                    649:     }
                    650:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  651:     if (!ref($getgroup)) {
                    652: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    653: 	    @getgroup=($getgroup);
                    654: 	}
                    655:     } else {
                    656: 	@getgroup=@{$getgroup};
                    657:     }
                    658:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  659: 
1.449     banghart  660:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  661:     # Bail out if we were unable to get the classlist
1.56      matthew   662:     return if (! defined($classlist));
1.449     banghart  663:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   664:     #
                    665:     my %sections;
                    666:     my %fullnames;
1.750     raeburn   667:     my ($cdom,$cnum,$partlist);
                    668:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    669:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    670:         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    671:         my $res_error;
1.773     raeburn   672:         ($partlist) = &response_type($symb,\$res_error);
1.750     raeburn   673:     }
1.205     matthew   674:     foreach my $student (keys(%$classlist)) {
                    675:         my $end      = 
                    676:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    677:         my $start    = 
                    678:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    679:         my $id       = 
                    680:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    681:         my $section  = 
                    682:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    683:         my $fullname = 
                    684:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    685:         my $status   = 
                    686:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  687:         my $group   = 
                    688:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        689: 	# filter students according to status selected
1.750     raeburn   690: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  691: 	    if (!($stu_status =~ $status)) {
1.450     banghart  692: 		delete($classlist->{$student});
1.76      ng        693: 		next;
                    694: 	    }
                    695: 	}
1.450     banghart  696: 	# filter students according to groups selected
1.453     banghart  697: 	my @stu_groups = split(/,/,$group);
1.450     banghart  698: 	if (@getgroup) {
                    699: 	    my $exclude = 1;
1.454     banghart  700: 	    foreach my $grp (@getgroup) {
                    701: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  702: 	            if ($stu_group eq $grp) {
                    703: 	                $exclude = 0;
                    704:     	            } 
1.450     banghart  705: 	        }
1.453     banghart  706:     	        if (($grp eq 'none') && !$group) {
1.750     raeburn   707:         	    $exclude = 0;
1.453     banghart  708:         	}
1.450     banghart  709: 	    }
                    710: 	    if ($exclude) {
                    711: 	        delete($classlist->{$student});
1.750     raeburn   712: 		next;
1.450     banghart  713: 	    }
                    714: 	}
1.750     raeburn   715:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    716:             my $udom =
                    717:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    718:             my $uname =
                    719:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    720:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    721:                 if ($submitonly eq 'queued') {
                    722:                     my %queue_status =
                    723:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    724:                                                                 $udom,$uname);
                    725:                     if (!defined($queue_status{'gradingqueue'})) {
                    726:                         delete($classlist->{$student});
                    727:                         next;
                    728:                     }
                    729:                 } else {
                    730:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    731:                     my $submitted = 0;
                    732:                     my $graded = 0;
                    733:                     my $incorrect = 0;
                    734:                     foreach (keys(%status)) {
                    735:                         $submitted = 1 if ($status{$_} ne 'nothing');
                    736:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    737:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    738: 
                    739:                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    740:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    741:                             $submitted = 0;
                    742:                         }
                    743:                     }
                    744:                     if (!$submitted && ($submitonly eq 'yes' ||
                    745:                                         $submitonly eq 'incorrect' ||
                    746:                                         $submitonly eq 'graded')) {
                    747:                         delete($classlist->{$student});
                    748:                         next;
                    749:                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    750:                         delete($classlist->{$student});
                    751:                         next;
                    752:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    753:                         delete($classlist->{$student});
                    754:                         next;
                    755:                     }
                    756:                 }
                    757:             }
                    758:         }
1.205     matthew   759: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  760: 	if (&canview($section)) {
1.291     albertel  761: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  762: 		$sections{$section}++;
1.450     banghart  763: 		if ($classlist->{$student}) {
                    764: 		    $fullnames{$student}=$fullname;
                    765: 		}
1.103     albertel  766: 	    } else {
1.205     matthew   767: 		delete($classlist->{$student});
1.103     albertel  768: 	    }
                    769: 	} else {
1.205     matthew   770: 	    delete($classlist->{$student});
1.103     albertel  771: 	}
1.44      ng        772:     }
1.56      matthew   773:     my @sections = sort(keys(%sections));
                    774:     return ($classlist,\@sections,\%fullnames);
1.44      ng        775: }
                    776: 
1.103     albertel  777: sub canmodify {
                    778:     my ($sec)=@_;
                    779:     if ($perm{'mgr'}) {
                    780: 	if (!defined($perm{'mgr_section'})) {
                    781: 	    # can modify whole class
                    782: 	    return 1;
                    783: 	} else {
                    784: 	    if ($sec eq $perm{'mgr_section'}) {
                    785: 		#can modify the requested section
                    786: 		return 1;
                    787: 	    } else {
1.763     raeburn   788: 		# can't modify the requested section
1.103     albertel  789: 		return 0;
                    790: 	    }
                    791: 	}
                    792:     }
                    793:     #can't modify
                    794:     return 0;
                    795: }
                    796: 
                    797: sub canview {
                    798:     my ($sec)=@_;
                    799:     if ($perm{'vgr'}) {
                    800: 	if (!defined($perm{'vgr_section'})) {
1.763     raeburn   801: 	    # can view whole class
1.103     albertel  802: 	    return 1;
                    803: 	} else {
                    804: 	    if ($sec eq $perm{'vgr_section'}) {
1.763     raeburn   805: 		#can view the requested section
1.103     albertel  806: 		return 1;
                    807: 	    } else {
1.763     raeburn   808: 		# can't view the requested section
1.103     albertel  809: 		return 0;
                    810: 	    }
                    811: 	}
                    812:     }
1.763     raeburn   813:     #can't view
1.103     albertel  814:     return 0;
                    815: }
                    816: 
1.44      ng        817: #--- Retrieve the grade status of a student for all the parts
                    818: sub student_gradeStatus {
1.324     albertel  819:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  820:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        821:     my %partstatus = ();
                    822:     foreach (@$partlist) {
1.128     ng        823: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        824: 	$status              = 'nothing' if ($status eq '');
                    825: 	$partstatus{$_}      = $status;
                    826: 	my $subkey           = "resource.$_.submitted_by";
                    827: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    828:     }
                    829:     return %partstatus;
                    830: }
                    831: 
1.45      ng        832: # hidden form and javascript that calls the form
                    833: # Use by verifyscript and viewgrades
                    834: # Shows a student's view of problem and submission
                    835: sub jscriptNform {
1.324     albertel  836:     my ($symb) = @_;
1.442     banghart  837:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  838:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        839: 	'    function viewOneStudent(user,domain) {'."\n".
                    840: 	'	document.onestudent.student.value = user;'."\n".
                    841: 	'	document.onestudent.userdom.value = domain;'."\n".
                    842: 	'	document.onestudent.submit();'."\n".
                    843: 	'    }'."\n".
1.597     wenzelju  844: 	"\n");
1.45      ng        845:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  846: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  847: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        848: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    849: 	'<input type="hidden" name="student" value="" />'."\n".
                    850: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    851: 	'</form>'."\n";
                    852:     return $jscript;
                    853: }
1.39      ng        854: 
1.447     foxr      855: 
                    856: 
1.315     bowersj2  857: # Given the score (as a number [0-1] and the weight) what is the final
                    858: # point value? This function will round to the nearest tenth, third,
                    859: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  860: sub compute_points {
1.315     bowersj2  861:     my ($score, $weight) = @_;
                    862:     
                    863:     my $tolerance = .00001;
                    864:     my $points = $score * $weight;
                    865: 
                    866:     # Check for nearness to 1/x.
                    867:     my $check_for_nearness = sub {
                    868:         my ($factor) = @_;
                    869:         my $num = ($points * $factor) + $tolerance;
                    870:         my $floored_num = floor($num);
1.316     albertel  871:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  872:             return $floored_num / $factor;
                    873:         }
                    874:         return $points;
                    875:     };
                    876: 
                    877:     $points = $check_for_nearness->(10);
                    878:     $points = $check_for_nearness->(3);
                    879:     $points = $check_for_nearness->(4);
                    880:     
                    881:     return $points;
                    882: }
                    883: 
1.44      ng        884: #------------------ End of general use routines --------------------
1.87      www       885: 
                    886: #
                    887: # Find most similar essay
                    888: #
                    889: 
                    890: sub most_similar {
1.674     raeburn   891:     my ($uname,$udom,$symb,$uessay)=@_;
                    892: 
                    893:     unless ($symb) { return ''; }
                    894: 
                    895:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       896: 
                    897: # ignore spaces and punctuation
                    898: 
                    899:     $uessay=~s/\W+/ /gs;
                    900: 
1.282     www       901: # ignore empty submissions (occuring when only files are sent)
                    902: 
1.598     www       903:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       904: 
1.87      www       905: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       906:     my $limit=0.6;
1.87      www       907:     my $sname='';
                    908:     my $sdom='';
                    909:     my $scrsid='';
                    910:     my $sessay='';
                    911: # go through all essays ...
1.674     raeburn   912:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  913: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       914: # ... except the same student
1.426     albertel  915:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   916: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  917: 	$tessay=~s/\W+/ /gs;
1.87      www       918: # String similarity gives up if not even limit
1.426     albertel  919: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       920: # Found one
1.426     albertel  921: 	if ($tsimilar>$limit) {
                    922: 	    $limit=$tsimilar;
                    923: 	    $sname=$tname;
                    924: 	    $sdom=$tdom;
                    925: 	    $scrsid=$tcrsid;
1.674     raeburn   926: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  927: 	}
1.87      www       928:     }
1.88      www       929:     if ($limit>0.6) {
1.87      www       930:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    931:     } else {
                    932:        return ('','','','',0);
                    933:     }
                    934: }
                    935: 
1.44      ng        936: #-------------------------------------------------------------------
                    937: 
                    938: #------------------------------------ Receipt Verification Routines
1.45      ng        939: #
1.602     www       940: 
                    941: sub initialverifyreceipt {
1.608     www       942:    my ($request,$symb) = @_;
1.602     www       943:    &commonJSfunctions($request);
1.694     bisitz    944:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       945:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    946:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       947:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    948:         '<input type="hidden" name="command" value="verify" />'.
                    949:         "</form>\n";
1.602     www       950: }
                    951: 
1.44      ng        952: #--- Check whether a receipt number is valid.---
                    953: sub verifyreceipt {
1.766     raeburn   954:     my ($request,$symb) = @_;
1.44      ng        955: 
1.257     albertel  956:     my $courseid = $env{'request.course.id'};
1.184     www       957:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  958: 	$env{'form.receipt'};
1.44      ng        959:     $receipt     =~ s/[^\-\d]//g;
                    960: 
1.766     raeburn   961:     my $title =
1.487     albertel  962: 	'<h3><span class="LC_info">'.
1.605     www       963: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    964: 	'</span></h3>'."\n";
1.44      ng        965: 
                    966:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   967:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  968:     
                    969:     my $receiptparts=0;
1.390     albertel  970:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    971: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  972:     my $parts=['0'];
1.582     raeburn   973:     if ($receiptparts) {
                    974:         my $res_error; 
                    975:         ($parts)=&response_type($symb,\$res_error);
                    976:         if ($res_error) {
                    977:             return &navmap_errormsg();
                    978:         } 
                    979:     }
1.486     albertel  980:     
                    981:     my $header = 
                    982: 	&Apache::loncommon::start_data_table().
                    983: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  984: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    985: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    986: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  987:     if ($receiptparts) {
1.487     albertel  988: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  989:     }
                    990:     $header.=
                    991: 	&Apache::loncommon::end_data_table_header_row();
                    992: 
1.294     albertel  993:     foreach (sort 
                    994: 	     {
                    995: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    996: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    997: 		 }
                    998: 		 return $a cmp $b;
                    999: 	     } (keys(%$fullname))) {
1.44      ng       1000: 	my ($uname,$udom)=split(/\:/);
1.177     albertel 1001: 	foreach my $part (@$parts) {
                   1002: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel 1003: 		$contents.=
                   1004: 		    &Apache::loncommon::start_data_table_row().
                   1005: 		    '<td>&nbsp;'."\n".
1.177     albertel 1006: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 1007: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel 1008: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                   1009: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                   1010: 		if ($receiptparts) {
                   1011: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                   1012: 		}
1.486     albertel 1013: 		$contents.= 
                   1014: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel 1015: 		
                   1016: 		$matches++;
                   1017: 	    }
1.44      ng       1018: 	}
                   1019:     }
                   1020:     if ($matches == 0) {
1.584     bisitz   1021:         $string = $title
                   1022:                  .'<p class="LC_warning">'
                   1023:                  .&mt('No match found for the above receipt number.')
                   1024:                  .'</p>';
1.44      ng       1025:     } else {
1.324     albertel 1026: 	$string = &jscriptNform($symb).$title.
1.487     albertel 1027: 	    '<p>'.
1.584     bisitz   1028: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel 1029: 	    '</p>'.
1.486     albertel 1030: 	    $header.
                   1031: 	    $contents.
                   1032: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng       1033:     }
1.614     www      1034:     return $string;
1.44      ng       1035: }
                   1036: 
                   1037: #--- This is called by a number of programs.
                   1038: #--- Called from the Grading Menu - View/Grade an individual student
                   1039: #--- Also called directly when one clicks on the subm button 
                   1040: #    on the problem page.
1.30      ng       1041: sub listStudents {
1.773     raeburn  1042:     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1043: 
1.747     raeburn  1044:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1045:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1046:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1047:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1048:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www      1049:     unless ($submitonly) {
1.766     raeburn  1050:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www      1051:     }
1.49      albertel 1052: 
1.632     www      1053:     my $result='';
1.623     www      1054:     my $res_error;
1.773     raeburn  1055:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   1056: 
                   1057:     my $table;
                   1058:     if (ref($partlist) eq 'ARRAY') {
                   1059:         if (scalar(@$partlist) > 1 ) {
                   1060:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1061:         } elsif ($divforres) {
                   1062:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1063:         } else {
                   1064:             $table = '<br clear="all" />';
                   1065:         }
                   1066:     }
1.49      albertel 1067: 
1.736     damieng  1068:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn  1069: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   1070: 		'single'   => 'Please select the student before clicking on the Next button.',
                   1071: 	     );
1.736     damieng  1072:     &js_escape(\%js_lt);
1.597     wenzelju 1073:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1074:     function checkSelect(checkBox) {
                   1075: 	var ctr=0;
                   1076: 	var sense="";
                   1077: 	if (checkBox.length > 1) {
                   1078: 	    for (var i=0; i<checkBox.length; i++) {
                   1079: 		if (checkBox[i].checked) {
                   1080: 		    ctr++;
                   1081: 		}
                   1082: 	    }
1.736     damieng  1083: 	    sense = '$js_lt{'multiple'}';
1.110     ng       1084: 	} else {
                   1085: 	    if (checkBox.checked) {
                   1086: 		ctr = 1;
                   1087: 	    }
1.736     damieng  1088: 	    sense = '$js_lt{'single'}';
1.110     ng       1089: 	}
                   1090: 	if (ctr == 0) {
1.485     albertel 1091: 	    alert(sense);
1.110     ng       1092: 	    return false;
                   1093: 	}
                   1094: 	document.gradesub.submit();
                   1095:     }
                   1096: 
                   1097:     function reLoadList(formname) {
1.112     ng       1098: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1099: 	formname.command.value = 'submission';
                   1100: 	formname.submit();
                   1101:     }
1.45      ng       1102: LISTJAVASCRIPT
                   1103: 
1.118     ng       1104:     &commonJSfunctions($request);
1.41      ng       1105:     $request->print($result);
1.39      ng       1106: 
1.154     albertel 1107:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.773     raeburn  1108: 	"\n".$table;
                   1109: 
1.561     bisitz   1110:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn  1111:     unless ($is_tool) {
                   1112:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1113:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1114:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1115:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1116:                       .&Apache::lonhtmlcommon::row_closure();
                   1117:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1118:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1119:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1120:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1121:                       .&Apache::lonhtmlcommon::row_closure();
                   1122:     }
1.485     albertel 1123: 
1.442     banghart 1124:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1125:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1126:     $env{'form.Status'} = $saveStatus;
1.745     raeburn  1127:     my %optiontext;
                   1128:     if ($is_tool) {
                   1129:         %optiontext = &Apache::lonlocal::texthash (
                   1130:                           lastonly => 'last transaction',
                   1131:                           last     => 'last transaction with details',
                   1132:                           datesub  => 'all transactions',
                   1133:                           all      => 'all transactions with details',
                   1134:                       );
                   1135:     } else {
                   1136:         %optiontext = &Apache::lonlocal::texthash (
                   1137:                           lastonly => 'last submission',
                   1138:                           last     => 'last submission with details',
                   1139:                           datesub  => 'all submissions',
                   1140:                           all      => 'all submissions with details',
                   1141:                       );
                   1142:     }
1.773     raeburn  1143:     my $submission_options =
1.592     bisitz   1144:         '<span class="LC_nobreak">'.
1.624     www      1145:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  1146:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1147:         '<span class="LC_nobreak">'.
                   1148:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  1149:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1150:         '<span class="LC_nobreak">'.
1.628     www      1151:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  1152:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1153:         '<span class="LC_nobreak">'.
                   1154:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  1155:         $optiontext{'all'}.'</label></span>';
                   1156:     my $viewtitle;
                   1157:     if ($is_tool) {
                   1158:         $viewtitle = &mt('View Transactions');
                   1159:     } else {
                   1160:         $viewtitle = &mt('View Submissions');
                   1161:     }
1.773     raeburn  1162:     my ($compmsg,$nocompmsg);
                   1163:     $nocompmsg = ' checked="checked"';
                   1164:     if ($numessay) {
                   1165:         $compmsg = $nocompmsg;
                   1166:         $nocompmsg = '';
                   1167:     }
1.745     raeburn  1168:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.780     raeburn  1169:                   .$submission_options;
                   1170: # Check if any gradable
                   1171:     my $showmore;
                   1172:     if ($perm{'mgr'}) {
                   1173:         my @sections;
                   1174:         if ($env{'request.course.sec'} ne '') {
                   1175:             @sections = ($env{'request.course.sec'});
                   1176:         } else {
                   1177:             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1178:         }
                   1179:         if (grep(/^all$/,@sections)) {
                   1180:             $showmore = 1;
                   1181:         } else {
                   1182:             foreach my $sec (@sections) {
                   1183:                 if (&canmodify($sec)) {
                   1184:                     $showmore = 1;
                   1185:                     last;
                   1186:                 }
                   1187:             }
                   1188:         }
                   1189:     }
                   1190: 
                   1191:     if ($showmore) {
                   1192:         $gradeTable .=
                   1193:                    &Apache::lonhtmlcommon::row_closure()
1.773     raeburn  1194:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   1195:                   .'<span class="LC_nobreak">'
                   1196:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   1197:                   .&mt('No').('&nbsp;'x2).'</label>'
                   1198:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   1199:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1200:                   .&Apache::lonhtmlcommon::row_closure();
                   1201: 
1.780     raeburn  1202:         $gradeTable .= 
                   1203:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   1204:                   .'<select name="increment">'
                   1205:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1206:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1207:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1208:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773     raeburn  1209:                   .'</select>';
1.780     raeburn  1210:     }
1.485     albertel 1211:     $gradeTable .= 
1.432     banghart 1212:         &build_section_inputs().
1.45      ng       1213: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1214: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1215: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      1216:     if (exists($env{'form.Status'})) {
1.561     bisitz   1217: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1218:     } else {
1.773     raeburn  1219:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1220:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1221:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773     raeburn  1222:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1223:     }
1.773     raeburn  1224:     if ($numessay) {
                   1225:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1226:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1227:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  1228:     }
1.773     raeburn  1229:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
                   1230:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  1231:     my $regrademsg;
                   1232:     if ($is_tool) {
                   1233:         $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.");
                   1234:     } else {
                   1235:         $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.");
                   1236:     }
1.561     bisitz   1237:     $gradeTable .= '<p>'
1.745     raeburn  1238:                   .$regrademsg."\n"
1.561     bisitz   1239:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1240:                   .'</p>';
1.249     albertel 1241: 
                   1242: # checkall buttons
                   1243:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1244:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1245:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1246:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1247:     $gradeTable.=&check_buttons();
1.450     banghart 1248:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1249:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1250: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1251:     my $loop = 0;
                   1252:     while ($loop < 2) {
1.485     albertel 1253: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1254: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1255: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1256: 	    foreach my $part (sort(@$partlist)) {
                   1257: 		my $display_part=
                   1258: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1259: 		$gradeTable.=
                   1260: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1261: 	    }
1.301     albertel 1262: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1263: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1264: 	}
                   1265: 	$loop++;
1.126     ng       1266: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1267:     }
1.474     albertel 1268:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1269: 
1.45      ng       1270:     my $ctr = 0;
1.294     albertel 1271:     foreach my $student (sort 
                   1272: 			 {
                   1273: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1274: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1275: 			     }
                   1276: 			     return $a cmp $b;
                   1277: 			 }
                   1278: 			 (keys(%$fullname))) {
1.41      ng       1279: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1280: 
1.110     ng       1281: 	my %status = ();
1.301     albertel 1282: 
                   1283: 	if ($submitonly eq 'queued') {
                   1284: 	    my %queue_status = 
                   1285: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1286: 							$udom,$uname);
                   1287: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1288: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1289: 	}
                   1290: 
1.618     www      1291: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1292: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1293: 	    my $submitted = 0;
1.164     albertel 1294: 	    my $graded = 0;
1.248     albertel 1295: 	    my $incorrect = 0;
1.110     ng       1296: 	    foreach (keys(%status)) {
1.145     albertel 1297: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1298: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1299: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1300: 		
1.110     ng       1301: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1302: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1303: 		    $submitted = 0;
1.150     albertel 1304: 		    my ($part)=split(/\./,$partid);
1.110     ng       1305: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1306: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1307: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1308: 		}
1.41      ng       1309: 	    }
1.248     albertel 1310: 	    
1.156     albertel 1311: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1312: 				     $submitonly eq 'incorrect' ||
                   1313: 				     $submitonly eq 'graded'));
1.248     albertel 1314: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1315: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1316: 	}
1.34      ng       1317: 
1.45      ng       1318: 	$ctr++;
1.249     albertel 1319: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1320:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1321: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1322: 	    if ($ctr%2 ==1) {
                   1323: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1324: 	    }
1.126     ng       1325: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1326:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1327:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1328: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1329: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1330: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1331: 
1.618     www      1332: 	    if ($submitonly ne 'all') {
1.524     raeburn  1333: 		foreach (sort(keys(%status))) {
1.485     albertel 1334: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1335: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1336: 		}
1.41      ng       1337: 	    }
1.126     ng       1338: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1339: 	    if ($ctr%2 ==0) {
                   1340: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1341: 	    }
1.41      ng       1342: 	}
                   1343:     }
1.110     ng       1344:     if ($ctr%2 ==1) {
1.126     ng       1345: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1346: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1347: 		foreach (@$partlist) {
                   1348: 		    $gradeTable.='<td>&nbsp;</td>';
                   1349: 		}
1.301     albertel 1350: 	    } elsif ($submitonly eq 'queued') {
                   1351: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1352: 	    }
1.474     albertel 1353: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1354:     }
                   1355: 
1.474     albertel 1356:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1357:         '<input type="button" '.
                   1358:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1359:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1360:     if ($ctr == 0) {
1.96      albertel 1361: 	my $num_students=(scalar(keys(%$fullname)));
                   1362: 	if ($num_students eq 0) {
1.485     albertel 1363: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1364: 	} else {
1.171     albertel 1365: 	    my $submissions='submissions';
                   1366: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1367: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1368: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1369: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1370: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1371: 		    $num_students).
                   1372: 		'</span><br />';
1.96      albertel 1373: 	}
1.46      ng       1374:     } elsif ($ctr == 1) {
1.474     albertel 1375: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1376:     }
                   1377:     $request->print($gradeTable);
1.44      ng       1378:     return '';
1.10      ng       1379: }
                   1380: 
1.44      ng       1381: #---- Called from the listStudents routine
1.249     albertel 1382: 
                   1383: sub check_script {
1.766     raeburn  1384:     my ($form,$type) = @_;
                   1385:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1386:     function checkall() {
                   1387:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1388:             ele = document.forms.'.$form.'.elements[i];
                   1389:             if (ele.name == "'.$type.'") {
                   1390:             document.forms.'.$form.'.elements[i].checked=true;
                   1391:                                        }
                   1392:         }
                   1393:     }
                   1394: 
                   1395:     function checksec() {
                   1396:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1397:             ele = document.forms.'.$form.'.elements[i];
                   1398:            string = document.forms.'.$form.'.chksec.value;
                   1399:            if
                   1400:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1401:               document.forms.'.$form.'.elements[i].checked=true;
                   1402:             }
                   1403:         }
                   1404:     }
                   1405: 
                   1406: 
                   1407:     function uncheckall() {
                   1408:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1409:             ele = document.forms.'.$form.'.elements[i];
                   1410:             if (ele.name == "'.$type.'") {
                   1411:             document.forms.'.$form.'.elements[i].checked=false;
                   1412:                                        }
                   1413:         }
                   1414:     }
                   1415: 
1.597     wenzelju 1416: '."\n");
1.249     albertel 1417:     return $chkallscript;
                   1418: }
                   1419: 
                   1420: sub check_buttons {
1.485     albertel 1421:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1422:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1423:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1424:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1425:     return $buttons;
                   1426: }
                   1427: 
1.44      ng       1428: #     Displays the submissions for one student or a group of students
1.34      ng       1429: sub processGroup {
1.766     raeburn  1430:     my ($request,$symb) = @_;
1.41      ng       1431:     my $ctr        = 0;
1.155     albertel 1432:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1433:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1434: 
1.396     banghart 1435:     foreach my $student (@stuchecked) {
                   1436: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1437: 	$env{'form.student'}        = $uname;
                   1438: 	$env{'form.userdom'}        = $udom;
                   1439: 	$env{'form.fullname'}       = $fullname;
1.619     www      1440: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1441: 	$ctr++;
                   1442:     }
                   1443:     return '';
1.35      ng       1444: }
1.34      ng       1445: 
1.44      ng       1446: #------------------------------------------------------------------------------------
                   1447: #
                   1448: #-------------------------- Next few routines handles grading by student, essentially
                   1449: #                           handles essay response type problem/part
                   1450: #
                   1451: #--- Javascript to handle the submission page functionality ---
                   1452: sub sub_page_js {
                   1453:     my $request = shift;
1.736     damieng  1454:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1455:     &js_escape(\$alertmsg);
1.597     wenzelju 1456:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1457:     function updateRadio(formname,id,weight) {
1.125     ng       1458: 	var gradeBox = formname["GD_BOX"+id];
                   1459: 	var radioButton = formname["RADVAL"+id];
                   1460: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1461: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1462: 	gradeBox.value = pts;
                   1463: 	var resetbox = false;
                   1464: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1465: 	    alert("$alertmsg"+pts);
1.71      ng       1466: 	    for (var i=0; i<radioButton.length; i++) {
                   1467: 		if (radioButton[i].checked) {
                   1468: 		    gradeBox.value = i;
                   1469: 		    resetbox = true;
                   1470: 		}
                   1471: 	    }
                   1472: 	    if (!resetbox) {
                   1473: 		formtextbox.value = "";
                   1474: 	    }
                   1475: 	    return;
1.44      ng       1476: 	}
1.71      ng       1477: 
                   1478: 	if (pts > weight) {
                   1479: 	    var resp = confirm("You entered a value ("+pts+
                   1480: 			       ") greater than the weight for the part. Accept?");
                   1481: 	    if (resp == false) {
1.125     ng       1482: 		gradeBox.value = oldpts;
1.71      ng       1483: 		return;
                   1484: 	    }
1.44      ng       1485: 	}
1.13      albertel 1486: 
1.71      ng       1487: 	for (var i=0; i<radioButton.length; i++) {
                   1488: 	    radioButton[i].checked=false;
                   1489: 	    if (pts == i && pts != "") {
                   1490: 		radioButton[i].checked=true;
                   1491: 	    }
                   1492: 	}
                   1493: 	updateSelect(formname,id);
1.125     ng       1494: 	formname["stores"+id].value = "0";
1.41      ng       1495:     }
1.5       albertel 1496: 
1.72      ng       1497:     function writeBox(formname,id,pts) {
1.125     ng       1498: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1499: 	if (checkSolved(formname,id) == 'update') {
                   1500: 	    gradeBox.value = pts;
                   1501: 	} else {
1.125     ng       1502: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1503: 	    gradeBox.value = oldpts;
1.125     ng       1504: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1505: 	    for (var i=0; i<radioButton.length; i++) {
                   1506: 		radioButton[i].checked=false;
1.72      ng       1507: 		if (i == oldpts) {
1.71      ng       1508: 		    radioButton[i].checked=true;
                   1509: 		}
                   1510: 	    }
1.41      ng       1511: 	}
1.125     ng       1512: 	formname["stores"+id].value = "0";
1.71      ng       1513: 	updateSelect(formname,id);
                   1514: 	return;
1.41      ng       1515:     }
1.44      ng       1516: 
1.71      ng       1517:     function clearRadBox(formname,id) {
                   1518: 	if (checkSolved(formname,id) == 'noupdate') {
                   1519: 	    updateSelect(formname,id);
                   1520: 	    return;
                   1521: 	}
1.125     ng       1522: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1523: 	for (var i=0; i<gradeSelect.length; i++) {
                   1524: 	    if (gradeSelect[i].selected) {
                   1525: 		var selectx=i;
                   1526: 	    }
                   1527: 	}
1.125     ng       1528: 	var stores = formname["stores"+id];
1.71      ng       1529: 	if (selectx == stores.value) { return };
1.125     ng       1530: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1531: 	gradeBox.value = "";
1.125     ng       1532: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1533: 	for (var i=0; i<radioButton.length; i++) {
                   1534: 	    radioButton[i].checked=false;
                   1535: 	}
                   1536: 	stores.value = selectx;
                   1537:     }
1.5       albertel 1538: 
1.71      ng       1539:     function checkSolved(formname,id) {
1.125     ng       1540: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1541: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1542: 	    if (!reply) {return "noupdate";}
1.120     ng       1543: 	    formname.overRideScore.value = 'yes';
1.41      ng       1544: 	}
1.71      ng       1545: 	return "update";
1.13      albertel 1546:     }
1.71      ng       1547: 
                   1548:     function updateSelect(formname,id) {
1.125     ng       1549: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1550: 	return;
1.41      ng       1551:     }
1.33      ng       1552: 
1.121     ng       1553: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1554:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1555: 	formname.gradeOpt.value = val;
1.71      ng       1556: 	if (val == "Save & Next") {
                   1557: 	    for (i=0;i<=total;i++) {
                   1558: 		for (j=0;j<parttot;j++) {
1.125     ng       1559: 		    var partid = formname["partid"+i+"_"+j].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;
1.71      ng       1562: 			if (points == "") {
1.125     ng       1563: 			    var name = formname["name"+i].value;
1.129     ng       1564: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1565: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1566: 					       ", part "+partid+". Continue?");
1.71      ng       1567: 			    if (resp == false) {
1.125     ng       1568: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1569: 				return false;
                   1570: 			    }
                   1571: 			}
                   1572: 		    }
                   1573: 		}
                   1574: 	    }
                   1575: 	}
1.120     ng       1576: 	formname.submit();
                   1577:     }
                   1578: 
1.71      ng       1579: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1580:     function checkSubmitPage(formname,total) {
                   1581: 	noscore = new Array(100);
                   1582: 	var ptr = 0;
                   1583: 	for (i=1;i<total;i++) {
1.125     ng       1584: 	    var partid = formname["q_"+i].value;
1.127     ng       1585: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1586: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1587: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1588: 		if (points == "" && status != "correct_by_student") {
                   1589: 		    noscore[ptr] = i;
                   1590: 		    ptr++;
                   1591: 		}
                   1592: 	    }
                   1593: 	}
                   1594: 	if (ptr != 0) {
                   1595: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1596: 	    var prolist = "";
                   1597: 	    if (ptr == 1) {
                   1598: 		prolist = noscore[0];
                   1599: 	    } else {
                   1600: 		var i = 0;
                   1601: 		while (i < ptr-1) {
                   1602: 		    prolist += noscore[i]+", ";
                   1603: 		    i++;
                   1604: 		}
                   1605: 		prolist += "and "+noscore[i];
                   1606: 	    }
                   1607: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1608: 	    if (resp == false) {
                   1609: 		return false;
                   1610: 	    }
                   1611: 	}
1.45      ng       1612: 
1.71      ng       1613: 	formname.submit();
                   1614:     }
                   1615: SUBJAVASCRIPT
                   1616: }
1.45      ng       1617: 
1.773     raeburn  1618: #--- javascript for grading message center
                   1619: sub sub_grademessage_js {
1.71      ng       1620:     my $request = shift;
1.80      ng       1621:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1622:     &commonJSfunctions($request);
1.350     albertel 1623: 
1.629     www      1624:     my $inner_js_msg_central= (<<INNERJS);
                   1625: <script type="text/javascript">
1.350     albertel 1626:     function checkInput() {
                   1627:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1628:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1629:       var usrctr = document.msgcenter.usrctr.value;
                   1630:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1631:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1632: 
                   1633:       var msgchk = "";
                   1634:       if (document.msgcenter.subchk.checked) {
                   1635:          msgchk = "msgsub,";
                   1636:       }
                   1637:       var includemsg = 0;
                   1638:       for (var i=1; i<=nmsg; i++) {
                   1639:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1640:           var frmmsg = document.msgcenter["msg"+i];
                   1641:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1642:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1643:           showflg.value = "1";
                   1644:           var chkbox = document.msgcenter["msgn"+i];
                   1645:           if (chkbox.checked) {
                   1646:              msgchk += "savemsg"+i+",";
                   1647:              includemsg = 1;
                   1648:           }
                   1649:       }
                   1650:       if (document.msgcenter.newmsgchk.checked) {
                   1651:          msgchk += "newmsg"+usrctr;
                   1652:          includemsg = 1;
                   1653:       }
                   1654:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1655:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1656:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1657:       includemsg.value = msgchk;
                   1658: 
                   1659:       self.close()
                   1660: 
                   1661:     }
1.629     www      1662: </script>
1.350     albertel 1663: INNERJS
                   1664: 
1.773     raeburn  1665:     my $start_page_msg_central =
1.351     albertel 1666:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1667: 				       {'js_ready'  => 1,
                   1668: 					'only_body' => 1,
                   1669: 					'bgcolor'   =>'#FFFFFF',});
1.773     raeburn  1670:     my $end_page_msg_central =
1.350     albertel 1671: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1672: 
1.219     www      1673:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1674:     $docopen=~s/^document\.//;
1.773     raeburn  1675: 
1.736     damieng  1676:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1677:                 comp => 'Compose Message for: ',
                   1678:                 incl => 'Include',
1.656     raeburn  1679:                 type => 'Type',
1.652     raeburn  1680:                 subj => 'Subject',
                   1681:                 mesa => 'Message',
                   1682:                 new  => 'New',
                   1683:                 save => 'Save',
                   1684:                 canc => 'Cancel',
                   1685:              );
1.736     damieng  1686:     &html_escape(\%html_js_lt);
                   1687:     &js_escape(\%html_js_lt);
1.597     wenzelju 1688:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1689: 
1.44      ng       1690: //===================== Script to view submitted by ==================
                   1691:   function viewSubmitter(submitter) {
                   1692:     document.SCORE.refresh.value = "on";
                   1693:     document.SCORE.NCT.value = "1";
                   1694:     document.SCORE.unamedom0.value = submitter;
                   1695:     document.SCORE.submit();
                   1696:     return;
                   1697:   }
                   1698: 
                   1699: //====================== Script for composing message ==============
1.80      ng       1700:    // preload images
                   1701:    img1 = new Image();
                   1702:    img1.src = "$iconpath/mailbkgrd.gif";
                   1703:    img2 = new Image();
                   1704:    img2.src = "$iconpath/mailto.gif";
                   1705: 
1.44      ng       1706:   function msgCenter(msgform,usrctr,fullname) {
                   1707:     var Nmsg  = msgform.savemsgN.value;
                   1708:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1709:     var subject = msgform.msgsub.value;
1.127     ng       1710:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1711:     re = /msgsub/;
                   1712:     var shwsel = "";
                   1713:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1714:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1715:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1716:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1717: 	var testmsg = "savemsg"+i+",";
                   1718: 	re = new RegExp(testmsg,"g");
1.44      ng       1719: 	shwsel = "";
                   1720: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1721: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1722: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1723: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1724: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1725:     }
1.125     ng       1726:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1727:     shwsel = "";
                   1728:     re = /newmsg/;
                   1729:     if (re.test(msgchk)) { shwsel = "checked" }
                   1730:     newMsg(newmsg,shwsel);
                   1731:     msgTail(); 
                   1732:     return;
                   1733:   }
                   1734: 
1.123     ng       1735:   function checkEntities(strx) {
                   1736:     if (strx.length == 0) return strx;
                   1737:     var orgStr = ["&", "<", ">", '"']; 
                   1738:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1739:     var counter = 0;
                   1740:     while (counter < 4) {
                   1741: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1742: 	counter++;
                   1743:     }
                   1744:     return strx;
                   1745:   }
                   1746: 
                   1747:   function strReplace(strx, orgStr, newStr) {
                   1748:     return strx.split(orgStr).join(newStr);
                   1749:   }
                   1750: 
1.44      ng       1751:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1752:     var height = 70*Nmsg+250;
1.44      ng       1753:     if (height > 600) {
                   1754: 	height = 600;
                   1755:     }
1.118     ng       1756:     var xpos = (screen.width-600)/2;
                   1757:     xpos = (xpos < 0) ? '0' : xpos;
                   1758:     var ypos = (screen.height-height)/2-30;
                   1759:     ypos = (ypos < 0) ? '0' : ypos;
                   1760: 
1.668     www      1761:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1762:     pWin.focus();
                   1763:     pDoc = pWin.document;
1.219     www      1764:     pDoc.$docopen;
1.351     albertel 1765:     pDoc.write('$start_page_msg_central');
1.76      ng       1766: 
                   1767:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1768:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1769:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1770: 
1.676     golterma 1771:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1772:     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       1773: }
                   1774:     function displaySubject(msg,shwsel) {
1.76      ng       1775:     pDoc = pWin.document;
1.676     golterma 1776:     pDoc.write("<tr>");
                   1777:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1778:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1779:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1780: }
                   1781: 
1.72      ng       1782:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1783:     pDoc = pWin.document;
1.676     golterma 1784:     pDoc.write("<tr>");
                   1785:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1786:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1787:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1788: }
                   1789: 
                   1790:   function newMsg(newmsg,shwsel) {
1.76      ng       1791:     pDoc = pWin.document;
1.676     golterma 1792:     pDoc.write("<tr>");
                   1793:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1794:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1795:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1796: }
                   1797: 
                   1798:   function msgTail() {
1.76      ng       1799:     pDoc = pWin.document;
1.676     golterma 1800:     //pDoc.write("<\\/table>");
1.465     albertel 1801:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1802:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1803:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1804:     pDoc.write("<\\/form>");
1.351     albertel 1805:     pDoc.write('$end_page_msg_central');
1.128     ng       1806:     pDoc.close();
1.44      ng       1807: }
                   1808: 
1.773     raeburn  1809: SUBJAVASCRIPT
                   1810: }
                   1811: 
                   1812: #--- javascript for essay type problem --
                   1813: sub sub_page_kw_js {
                   1814:     my $request = shift;
                   1815: 
                   1816:     unless ($env{'form.compmsg'}) {
                   1817:         &commonJSfunctions($request);
                   1818:     }
                   1819: 
                   1820:     my $inner_js_highlight_central= (<<INNERJS);
                   1821: <script type="text/javascript">
                   1822:     function updateChoice(flag) {
                   1823:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1824:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1825:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1826:       opener.document.SCORE.refresh.value = "on";
                   1827:       if (opener.document.SCORE.keywords.value!=""){
                   1828:          opener.document.SCORE.submit();
                   1829:       }
                   1830:       self.close()
                   1831:     }
                   1832: </script>
                   1833: INNERJS
                   1834: 
                   1835:     my $start_page_highlight_central =
                   1836:         &Apache::loncommon::start_page('Highlight Central',
                   1837:                                        $inner_js_highlight_central,
                   1838:                                        {'js_ready'  => 1,
                   1839:                                         'only_body' => 1,
                   1840:                                         'bgcolor'   =>'#FFFFFF',});
                   1841:     my $end_page_highlight_central =
                   1842:         &Apache::loncommon::end_page({'js_ready' => 1});
                   1843: 
                   1844:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   1845:     $docopen=~s/^document\.//;
                   1846: 
                   1847:     my %js_lt = &Apache::lonlocal::texthash(
                   1848:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1849:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1850:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1851:                 col1 => 'red',
                   1852:                 col2 => 'green',
                   1853:                 col3 => 'blue',
                   1854:                 siz1 => 'normal',
                   1855:                 siz2 => '+1',
                   1856:                 siz3 => '+2',
                   1857:                 sty1 => 'normal',
                   1858:                 sty2 => 'italic',
                   1859:                 sty3 => 'bold',
                   1860:              );
                   1861:     my %html_js_lt = &Apache::lonlocal::texthash(
                   1862:                 save => 'Save',
                   1863:                 canc => 'Cancel',
                   1864:                 kehi => 'Keyword Highlight Options',
                   1865:                 txtc => 'Text Color',
                   1866:                 font => 'Font Size',
                   1867:                 fnst => 'Font Style',
                   1868:              );
                   1869:     &js_escape(\%js_lt);
                   1870:     &html_escape(\%html_js_lt);
                   1871:     &js_escape(\%html_js_lt);
                   1872:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   1873: 
                   1874: //===================== Show list of keywords ====================
                   1875:   function keywords(formname) {
                   1876:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   1877:     if (nret==null) return;
                   1878:     formname.keywords.value = nret;
                   1879: 
                   1880:     if (formname.keywords.value != "") {
                   1881:         formname.refresh.value = "on";
                   1882:         formname.submit();
                   1883:     }
                   1884:     return;
                   1885:   }
                   1886: 
                   1887: //===================== Script to add keyword(s) ==================
                   1888:   function getSel() {
                   1889:     if (document.getSelection) txt = document.getSelection();
                   1890:     else if (document.selection) txt = document.selection.createRange().text;
                   1891:     else return;
                   1892:     if (typeof(txt) != 'string') {
                   1893:         txt = String(txt);
                   1894:     }
                   1895:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1896:     if (cleantxt=="") {
                   1897:         alert("$js_lt{'plse'}");
                   1898:         return;
                   1899:     }
                   1900:     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   1901:     if (nret==null) return;
                   1902:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   1903:     if (document.SCORE.keywords.value != "") {
                   1904:         document.SCORE.refresh.value = "on";
                   1905:         document.SCORE.submit();
                   1906:     }
                   1907:     return;
                   1908:   }
                   1909: 
1.44      ng       1910: //====================== Script for keyword highlight options ==============
                   1911:   function kwhighlight() {
                   1912:     var kwclr    = document.SCORE.kwclr.value;
                   1913:     var kwsize   = document.SCORE.kwsize.value;
                   1914:     var kwstyle  = document.SCORE.kwstyle.value;
                   1915:     var redsel = "";
                   1916:     var grnsel = "";
                   1917:     var blusel = "";
1.736     damieng  1918:     var txtcol1 = "$js_lt{'col1'}";
                   1919:     var txtcol2 = "$js_lt{'col2'}";
                   1920:     var txtcol3 = "$js_lt{'col3'}";
                   1921:     var txtsiz1 = "$js_lt{'siz1'}";
                   1922:     var txtsiz2 = "$js_lt{'siz2'}";
                   1923:     var txtsiz3 = "$js_lt{'siz3'}";
                   1924:     var txtsty1 = "$js_lt{'sty1'}";
                   1925:     var txtsty2 = "$js_lt{'sty2'}";
                   1926:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1927:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1928:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1929:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1930:     var sznsel = "";
                   1931:     var sz1sel = "";
                   1932:     var sz2sel = "";
1.718     bisitz   1933:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1934:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1935:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1936:     var synsel = "";
                   1937:     var syisel = "";
                   1938:     var sybsel = "";
1.718     bisitz   1939:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1940:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1941:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1942:     highlightCentral();
1.718     bisitz   1943:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1944:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1945:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1946:     highlightend();
                   1947:     return;
                   1948:   }
                   1949: 
                   1950:   function highlightCentral() {
1.76      ng       1951: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1952:     var xpos = (screen.width-400)/2;
                   1953:     xpos = (xpos < 0) ? '0' : xpos;
                   1954:     var ypos = (screen.height-330)/2-30;
                   1955:     ypos = (ypos < 0) ? '0' : ypos;
                   1956: 
1.206     albertel 1957:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1958:     hwdWin.focus();
                   1959:     var hDoc = hwdWin.document;
1.219     www      1960:     hDoc.$docopen;
1.351     albertel 1961:     hDoc.write('$start_page_highlight_central');
1.76      ng       1962:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1963:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1964: 
1.718     bisitz   1965:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1966:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1967:   }
                   1968: 
                   1969:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1970:     var hDoc = hwdWin.document;
1.718     bisitz   1971:     hDoc.write("<tr>");
1.76      ng       1972:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1973:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1974:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1975:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1976:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1977:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1978:     hDoc.write("<\\/tr>");
1.44      ng       1979:   }
                   1980: 
                   1981:   function highlightend() { 
1.76      ng       1982:     var hDoc = hwdWin.document;
1.718     bisitz   1983:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1984:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1985:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1986:     hDoc.write("<\\/form>");
1.351     albertel 1987:     hDoc.write('$end_page_highlight_central');
1.128     ng       1988:     hDoc.close();
1.44      ng       1989:   }
                   1990: 
                   1991: SUBJAVASCRIPT
                   1992: }
                   1993: 
1.349     albertel 1994: sub get_increment {
1.348     bowersj2 1995:     my $increment = $env{'form.increment'};
                   1996:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1997:         $increment != .1) {
                   1998:         $increment = 1;
                   1999:     }
                   2000:     return $increment;
                   2001: }
                   2002: 
1.585     bisitz   2003: sub gradeBox_start {
                   2004:     return (
                   2005:         &Apache::loncommon::start_data_table()
                   2006:        .&Apache::loncommon::start_data_table_header_row()
                   2007:        .'<th>'.&mt('Part').'</th>'
                   2008:        .'<th>'.&mt('Points').'</th>'
                   2009:        .'<th>&nbsp;</th>'
                   2010:        .'<th>'.&mt('Assign Grade').'</th>'
                   2011:        .'<th>'.&mt('Weight').'</th>'
                   2012:        .'<th>'.&mt('Grade Status').'</th>'
                   2013:        .&Apache::loncommon::end_data_table_header_row()
                   2014:     );
                   2015: }
                   2016: 
                   2017: sub gradeBox_end {
                   2018:     return (
                   2019:         &Apache::loncommon::end_data_table()
                   2020:     );
                   2021: }
1.71      ng       2022: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   2023: sub gradeBox {
1.322     albertel 2024:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 2025:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2026: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2027:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2028:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2029:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2030:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2031:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2032: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   2033:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2034:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2035:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2036: 				       [$partid]);
                   2037:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2038:     if ($last_resets{$partid}) {
                   2039:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2040:     }
1.695     bisitz   2041:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2042:     my $ctr = 0;
1.348     bowersj2 2043:     my $thisweight = 0;
1.349     albertel 2044:     my $increment = &get_increment();
1.485     albertel 2045: 
                   2046:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2047:     while ($thisweight<=$wgt) {
1.532     bisitz   2048: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2049:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2050: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2051: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2052: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2053:         $thisweight += $increment;
1.71      ng       2054: 	$ctr++;
                   2055:     }
1.485     albertel 2056:     $radio.='</tr></table>';
                   2057: 
                   2058:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2059: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2060: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2061: 	$wgt.')" /></td>'."\n";
1.485     albertel 2062:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2063: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2064: 	' </td>'."\n";
                   2065:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2066: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2067:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2068: 	$line.='<option></option>'.
                   2069: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2070:     } else {
1.485     albertel 2071: 	$line.='<option selected="selected"></option>'.
                   2072: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2073:     }
1.485     albertel 2074:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2075: 
                   2076: 
                   2077:     $result .= 
1.695     bisitz   2078: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   2079:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   2080:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2081:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2082: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2083: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2084: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2085:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2086:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2087:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2088:         $aggtries.'" />'."\n";
1.582     raeburn  2089:     my $res_error;
                   2090:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   2091:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2092:     if ($res_error) {
                   2093:         return &navmap_errormsg();
                   2094:     }
1.318     banghart 2095:     return $result;
                   2096: }
1.322     albertel 2097: 
                   2098: sub handback_box {
1.623     www      2099:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773     raeburn  2100:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   2101:     return unless ($numessay);
1.323     banghart 2102:     my (@respids);
1.652     raeburn  2103:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2104:     foreach my $part_response_id (@part_response_id) {
                   2105:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2106:         if ($part eq $partid) {
1.375     albertel 2107:             push(@respids,$resp);
1.323     banghart 2108:         }
                   2109:     }
1.318     banghart 2110:     my $result;
1.323     banghart 2111:     foreach my $respid (@respids) {
1.322     albertel 2112: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2113: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2114: 	next if (!@$files);
1.654     raeburn  2115: 	my $file_counter = 0;
1.313     banghart 2116: 	foreach my $file (@$files) {
1.368     banghart 2117: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  2118:                 $file_counter++;
1.368     banghart 2119:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  2120:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 2121:     	        $file_disp = "$name.$ext";
                   2122:     	        $file = $file_path.$file_disp;
                   2123:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2124:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2125:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  2126:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2127: 	    }
1.322     albertel 2128: 	}
1.654     raeburn  2129:         if ($file_counter) {
                   2130:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2131:                        '<span class="LC_info">'.
                   2132:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2133:         }
1.313     banghart 2134:     }
1.318     banghart 2135:     return $result;    
1.71      ng       2136: }
1.44      ng       2137: 
1.58      albertel 2138: sub show_problem {
1.382     albertel 2139:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2140:     my $rendered;
1.382     albertel 2141:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2142:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2143:     if ($mode eq 'both' or $mode eq 'text') {
                   2144: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2145: 						       $env{'request.course.id'},
                   2146: 						       undef,\%form);
1.144     albertel 2147:     }
1.58      albertel 2148:     if ($removeform) {
                   2149: 	$rendered=~s|<form(.*?)>||g;
                   2150: 	$rendered=~s|</form>||g;
1.374     albertel 2151: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2152:     }
1.144     albertel 2153:     my $companswer;
                   2154:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2155: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2156: 	$companswer=
                   2157: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2158: 						    $env{'request.course.id'},
                   2159: 						    %form);
1.144     albertel 2160:     }
1.58      albertel 2161:     if ($removeform) {
                   2162: 	$companswer=~s|<form(.*?)>||g;
                   2163: 	$companswer=~s|</form>||g;
1.144     albertel 2164: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2165:     }
1.671     raeburn  2166:     my $renderheading = &mt('View of the problem');
                   2167:     my $answerheading = &mt('Correct answer');
                   2168:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2169:         my $stu_fullname = $env{'form.fullname'};
                   2170:         if ($stu_fullname eq '') {
                   2171:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2172:         }
                   2173:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2174:         if ($forwhom ne '') {
                   2175:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2176:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2177:         }
                   2178:     }
1.468     albertel 2179:     $rendered=
1.588     bisitz   2180:         '<div class="LC_Box">'
1.671     raeburn  2181:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2182:        .$rendered
                   2183:        .'</div>';
1.468     albertel 2184:     $companswer=
1.588     bisitz   2185:         '<div class="LC_Box">'
1.671     raeburn  2186:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2187:        .$companswer
                   2188:        .'</div>';
1.468     albertel 2189:     my $result;
1.144     albertel 2190:     if ($mode eq 'both') {
1.588     bisitz   2191:         $result=$rendered.$companswer;
1.144     albertel 2192:     } elsif ($mode eq 'text') {
1.588     bisitz   2193:         $result=$rendered;
1.144     albertel 2194:     } elsif ($mode eq 'answer') {
1.588     bisitz   2195:         $result=$companswer;
1.144     albertel 2196:     }
1.71      ng       2197:     return $result;
1.58      albertel 2198: }
1.397     albertel 2199: 
1.396     banghart 2200: sub files_exist {
                   2201:     my ($r, $symb) = @_;
                   2202:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2203:     foreach my $student (@students) {
                   2204:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2205:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2206: 					      $udom,$uname);
1.396     banghart 2207:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2208:         foreach my $submission (@$string) {
                   2209:             my ($partid,$respid) =
                   2210: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2211:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2212: 					   \%record);
                   2213:             return 1 if (@$files);
1.396     banghart 2214:         }
                   2215:     }
1.397     albertel 2216:     return 0;
1.396     banghart 2217: }
1.397     albertel 2218: 
1.394     banghart 2219: sub download_all_link {
                   2220:     my ($r,$symb) = @_;
1.621     www      2221:     unless (&files_exist($r, $symb)) {
1.766     raeburn  2222:         $r->print(&mt('There are currently no submitted documents.'));
                   2223:         return;
1.621     www      2224:     }
1.395     albertel 2225:     my $all_students = 
                   2226: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2227: 
                   2228:     my $parts =
                   2229: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2230: 
1.394     banghart 2231:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2232:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2233:                              'cgi.'.$identifier.'.symb' => $symb,
                   2234:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2235:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2236: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2237:     return;
                   2238: }
                   2239: 
                   2240: sub submit_download_link {
                   2241:     my ($request,$symb) = @_;
                   2242:     if (!$symb) { return ''; }
1.750     raeburn  2243:     my $res_error;
1.773     raeburn  2244:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   2245:         &response_type($symb,\$res_error);
                   2246:     if ($res_error) {
                   2247:         $request->print(&mt('An error occurred retrieving response types'));
                   2248:         return;
                   2249:     }
                   2250:     unless ($numessay) {
                   2251:         $request->print(&mt('No essayresponse items found'));
                   2252:         return;
1.750     raeburn  2253:     }
1.773     raeburn  2254:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2255:     if (@chosenparts) {
                   2256:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   2257:                                           undef,undef,1));
1.750     raeburn  2258:     }
1.773     raeburn  2259:     if ($numessay) {
1.750     raeburn  2260:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2261:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2262:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2263:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2264:         if (ref($fullname) eq 'HASH') {
                   2265:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2266:             if (@students) {
                   2267:                 @{$env{'form.stuinfo'}} = @students;
1.773     raeburn  2268:                 if ($numdropbox) {
1.750     raeburn  2269:                     &download_all_link($request,$symb);
1.773     raeburn  2270:                 } else {
                   2271:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  2272:                 }
1.773     raeburn  2273: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  2274: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2275:             } else {
                   2276:                 $request->print(&mt('No students match the criteria you selected'));
                   2277:             }
                   2278:         } else {
                   2279:             $request->print(&mt('Could not retrieve student information'));
                   2280:         }
                   2281:     } else {
                   2282:         $request->print(&mt('No essayresponse items found'));
                   2283:     }
                   2284:     return;
1.394     banghart 2285: }
1.395     albertel 2286: 
1.432     banghart 2287: sub build_section_inputs {
                   2288:     my $section_inputs;
                   2289:     if ($env{'form.section'} eq '') {
                   2290:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2291:     } else {
                   2292:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2293:         foreach my $section (@sections) {
1.432     banghart 2294:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2295:         }
                   2296:     }
                   2297:     return $section_inputs;
                   2298: }
                   2299: 
1.44      ng       2300: # --------------------------- show submissions of a student, option to grade 
                   2301: sub submission {
1.773     raeburn  2302:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2303:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2304:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2305:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2306:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2307: 
1.324     albertel 2308:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773     raeburn  2309:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  2310:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  2311:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2312: 
                   2313:     if (!&canview($usec)) {
1.712     bisitz   2314:         $request->print(
                   2315:             '<span class="LC_warning">'.
1.713     bisitz   2316:             &mt('Unable to view requested student.').
1.712     bisitz   2317:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2318:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2319:             '</span>');
1.104     albertel 2320: 	return;
                   2321:     }
                   2322: 
1.773     raeburn  2323:     my $res_error;
                   2324:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   2325:         &response_type($symb,\$res_error);
                   2326:     if ($res_error) {
                   2327:         $request->print(&navmap_errormsg());
                   2328:         return;
                   2329:     }
                   2330: 
1.257     albertel 2331:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2332:     unless ($is_tool) { 
                   2333:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2334:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2335:     }
1.773     raeburn  2336:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   2337:         $env{'form.compmsg'} = 1;
                   2338:     }
1.257     albertel 2339:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2340:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2341: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2342: 	'/check.gif" height="16" border="0" />';
1.41      ng       2343: 
                   2344:     # header info
                   2345:     if ($counter == 0) {
1.773     raeburn  2346:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2347:         if (@chosenparts) {
                   2348:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   2349:         } elsif ($divforres) {
                   2350:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   2351:         } else {
                   2352:             $request->print('<br clear="all" />');
                   2353:         }
1.41      ng       2354: 	&sub_page_js($request);
1.773     raeburn  2355:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   2356: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       2357: 
1.44      ng       2358: 	# option to display problem, only once else it cause problems 
                   2359:         # with the form later since the problem has a form.
1.257     albertel 2360: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2361: 	    my $mode;
1.257     albertel 2362: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2363: 		$mode='both';
1.257     albertel 2364: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2365: 		$mode='text';
1.257     albertel 2366: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2367: 		$mode='answer';
                   2368: 	    }
1.329     albertel 2369: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2370: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2371: 	}
1.441     www      2372: 
1.41      ng       2373: 	my %keyhash = ();
1.773     raeburn  2374: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       2375: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2376: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2377: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773     raeburn  2378: 	}
                   2379: 	# kwclr is the only variable that is guaranteed not to be blank
                   2380: 	# if this subroutine has been called once.
                   2381: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 2382: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2383: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2384: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2385: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2386: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773     raeburn  2387: 	}
                   2388: 	if ($env{'form.compmsg'}) {
                   2389: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      2390: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2391: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2392: 	}
1.773     raeburn  2393: 
1.257     albertel 2394: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2395: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2396: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2397: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2398: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2399: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2400: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2401: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2402: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2403: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2404: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2405: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2406: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773     raeburn  2407: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 2408: 			&build_section_inputs().
1.326     albertel 2409: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2410: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2411: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773     raeburn  2412: 	if ($env{'form.compmsg'}) {
                   2413: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   2414: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   2415: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   2416: 	}
                   2417: 	if ($numessay) {
1.257     albertel 2418: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2419: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2420: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773     raeburn  2421: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       2422: 	}
1.773     raeburn  2423: 
1.41      ng       2424: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2425: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2426: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2427: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2428: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2429: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2430: 		'" />'."\n".
                   2431: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2432: 	    $cts++;
                   2433: 	}
                   2434: 	$request->print($prnmsg);
1.32      ng       2435: 
1.773     raeburn  2436: 	if ($numessay) {
1.652     raeburn  2437: 
                   2438:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2439:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2440:                           keyw => 'Keyword Options',
1.655     raeburn  2441:                           list => 'List',
1.652     raeburn  2442:                           past => 'Paste Selection to List',
1.661     www      2443:                           high => 'Highlight Attribute',
1.773     raeburn  2444:                      );
1.88      www      2445: #
                   2446: # Print out the keyword options line
                   2447: #
1.718     bisitz   2448: 	    $request->print(
                   2449:                 '<div class="LC_columnSection">'
                   2450:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2451:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2452:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2453:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2454:  class="page">'.$lt{'past'}.'</a>',
                   2455:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2456:                     {legend => $lt{'keyw'}})
                   2457:                .'</fieldset></div>'
                   2458:             );
                   2459: 
1.88      www      2460: #
                   2461: # Load the other essays for similarity check
                   2462: #
1.753     raeburn  2463:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2464:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2465:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2466:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2467:                 if ($cdom ne '' && $cnum ne '') {
                   2468:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2469:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2470:                         my $apath = $1.'_'.$id;
                   2471:                         $apath=~s/\W/\_/gs;
                   2472:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2473:                     }
                   2474:                 }
                   2475:             } else {
                   2476: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2477: 	        $apath=&escape($apath);
                   2478: 	        $apath=~s/\W/\_/gs;
                   2479:                 &init_old_essays($symb,$apath,$adom,$aname);
                   2480:             }
1.41      ng       2481:         }
                   2482:     }
1.44      ng       2483: 
1.441     www      2484: # This is where output for one specific student would start
1.592     bisitz   2485:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2486:     $request->print(
                   2487:         "\n\n"
                   2488:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2489:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2490:        ."\n"
                   2491:     );
1.441     www      2492: 
1.592     bisitz   2493:     # Show additional functions if allowed
                   2494:     if ($perm{'vgr'}) {
                   2495:         $request->print(
                   2496:             &Apache::loncommon::track_student_link(
1.708     bisitz   2497:                 'View recent activity',
1.592     bisitz   2498:                 $uname,$udom,'check')
                   2499:            .' '
                   2500:         );
                   2501:     }
                   2502:     if ($perm{'opa'}) {
                   2503:         $request->print(
                   2504:             &Apache::loncommon::pprmlink(
                   2505:                 &mt('Set/Change parameters'),
                   2506:                 $uname,$udom,$symb,'check'));
                   2507:     }
                   2508: 
                   2509:     # Show Problem
1.257     albertel 2510:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2511: 	my $mode;
1.257     albertel 2512: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2513: 	    $mode='both';
1.257     albertel 2514: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2515: 	    $mode='text';
1.257     albertel 2516: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2517: 	    $mode='answer';
                   2518: 	}
1.329     albertel 2519: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2520: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2521:     }
1.144     albertel 2522: 
1.257     albertel 2523:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       2524: 
1.44      ng       2525:     # Display student info
1.41      ng       2526:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2527: 
1.745     raeburn  2528:     my $boxtitle = &mt('Submissions');
                   2529:     if ($is_tool) {
                   2530:         $boxtitle = &mt('Transactions')
                   2531:     }
1.590     bisitz   2532:     my $result='<div class="LC_Box">'
1.745     raeburn  2533:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2534:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2535:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773     raeburn  2536:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   2537:         $result.='<p class="LC_info">'
                   2538:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2539:                 ."</p>\n";
1.469     albertel 2540:     }
                   2541: 
1.773     raeburn  2542:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 2543:     my $fullname;
                   2544:     my $col_fullnames = [];
1.773     raeburn  2545:     if ($numessay) {
1.464     albertel 2546: 	(my $sub_result,$fullname,$col_fullnames)=
                   2547: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2548: 				 $counter);
                   2549: 	$result.=$sub_result;
1.41      ng       2550:     }
1.44      ng       2551:     $request->print($result."\n");
1.773     raeburn  2552: 
1.44      ng       2553:     # print student answer/submission
1.773     raeburn  2554:     # Options are (1) Last submission only
                   2555:     #             (2) Last submission (with detailed information for that submission)
                   2556:     #             (3) All transactions (by date)
                   2557:     #             (4) The whole record (with detailed information for all transactions)
                   2558: 
1.745     raeburn  2559:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.773     raeburn  2560: 
1.702     kruse    2561:     my $lastsubonly;
1.468     albertel 2562: 
1.702     kruse    2563:     if ($$timestamp eq '') {
                   2564:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2565:     } elsif ($is_tool) {
                   2566:         $lastsubonly =
                   2567:             '<div class="LC_grade_submissions_body">'
                   2568:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2569:     } else {
                   2570:         $lastsubonly =
                   2571:             '<div class="LC_grade_submissions_body">'
                   2572:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2573: 
                   2574: 	my %seenparts;
                   2575: 	my @part_response_id = &flatten_responseType($responseType);
                   2576: 	foreach my $part (@part_response_id) {
                   2577: 	    my ($partid,$respid) = @{ $part };
                   2578: 	    my $display_part=&get_display_part($partid,$symb);
                   2579: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2580: 		if (exists($seenparts{$partid})) { next; }
                   2581: 		$seenparts{$partid}=1;
                   2582:                 $request->print(
                   2583:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2584:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2585:                                '<a href="javascript:viewSubmitter(\''.
                   2586:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2587:                                '\');" target="_self">'.
                   2588:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2589:                     '<br />');
                   2590: 		next;
1.773     raeburn  2591: 	    }
1.702     kruse    2592: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2593: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2594:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2595:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2596:                     ' <span class="LC_internal_info">'.
                   2597:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2598:                     '</span>&nbsp; &nbsp;'.
                   2599: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2600: 		next;
                   2601: 	    }
                   2602: 	    foreach my $submission (@$string) {
                   2603: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2604: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2605: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2606: 		# Similarity check
                   2607:                 my $similar='';
                   2608:                 my ($type,$trial,$rndseed);
                   2609:                 if ($hide eq 'rand') {
                   2610:                     $type = 'randomizetry';
                   2611:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2612:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2613:                 }
                   2614: 	        if ($env{'form.checkPlag'}) {
1.774     raeburn  2615: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2616: 		    &most_similar($uname,$udom,$symb,$subval);
1.702     kruse    2617: 		    if ($osim) {
                   2618: 			$osim=int($osim*100.0);
                   2619:                         if ($hide eq 'anon') {
                   2620:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2621:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2622:                         } else {
1.753     raeburn  2623: 			    $similar='<hr />';
                   2624:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2625:                                 $similar .= '<h3><span class="LC_warning">'.
                   2626:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2627:                                                 $osim,
                   2628:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2629:                                             '</span></h3>';
                   2630:                             } else {
                   2631:                                 my %old_course_desc;
                   2632:                                 if ($ocrsid ne '') {
                   2633:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2634:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
                   2635:                                     } else {
                   2636:                                         my $args;
                   2637:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   2638:                                             $args = {'one_time' => 1};
                   2639:                                         }
                   2640:                                         %old_course_desc =
                   2641:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
                   2642:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
                   2643:                                     }
                   2644:                                     $similar .=
                   2645:                                         '<h3><span class="LC_warning">'.
                   2646:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2647:                                             $osim,
                   2648:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2649:                                             $old_course_desc{'description'},
                   2650:                                             $old_course_desc{'num'},
                   2651:                                             $old_course_desc{'domain'}).
                   2652:                                         '</span></h3>';
                   2653:                                 } else {
                   2654:                                     $similar .=
                   2655:                                         '<h3><span class="LC_warning">'.
                   2656:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2657:                                             $osim,
                   2658:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2659:                                         '</span></h3>';
                   2660:                                 }
                   2661:                             }
                   2662:                             $similar .= '<blockquote><i>'.
                   2663:                                         &keywords_highlight($oessay).
                   2664:                                         '</i></blockquote><hr />';
1.702     kruse    2665:                         }
                   2666: 	            }
                   2667: 		}
                   2668: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2669:                                      undef,$type,$trial,$rndseed);
1.773     raeburn  2670:                 if (($env{'form.lastSub'} eq 'lastonly') ||
                   2671:                     ($env{'form.lastSub'} eq 'datesub')  ||
                   2672:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
1.702     kruse    2673: 		    my $display_part=&get_display_part($partid,$symb);
                   2674:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2675:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2676:                         ' <span class="LC_internal_info">'.
                   2677:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2678:                         '</span>&nbsp; &nbsp;';
                   2679: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2680: 		    if (@$files) {
                   2681:                         if ($hide eq 'anon') {
                   2682:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2683:                         } else {
                   2684:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2685:                                         .'<br /><span class="LC_warning">';
                   2686:                             if(@$files == 1) {
                   2687:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2688:                             } else {
1.702     kruse    2689:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2690:                             }
1.774     raeburn  2691:                             $lastsubonly .= '</span>';
1.702     kruse    2692:                             foreach my $file (@$files) {
                   2693:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2694:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2695:                             }
                   2696:                         }
1.702     kruse    2697: 			$lastsubonly.='<br />';
                   2698:                     }
                   2699:                     if ($hide eq 'anon') {
                   2700:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2701:                     } else {
1.774     raeburn  2702:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  2703:                         if ($draft) {
                   2704:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2705:                         }
                   2706:                         $subval =
1.702     kruse    2707: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2708: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2709:                         if ($responsetype eq 'essay') {
                   2710:                             $subval =~ s{\n}{<br />}g;
                   2711:                         }
                   2712:                         $lastsubonly.=$subval."\n";
1.702     kruse    2713:                     }
1.774     raeburn  2714:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.702     kruse    2715: 		    $lastsubonly.='</div>';
1.41      ng       2716: 		}
1.702     kruse    2717:             }
1.151     albertel 2718: 	}
1.702     kruse    2719: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2720:     }
                   2721:     $request->print($lastsubonly);
                   2722:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2723:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2724: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.773     raeburn  2725:     }
1.702     kruse    2726:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2727:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2728:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2729: 								 $env{'request.course.id'},
1.44      ng       2730: 								 $last,'.submission',
1.726     raeburn  2731: 								 'Apache::grades::keywords_highlight',
                   2732:                                                                  $usec,$identifier));
1.41      ng       2733:     }
1.121     ng       2734:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2735: 	.$udom.'" />'."\n");
1.44      ng       2736:     # return if view submission with no grading option
1.618     www      2737:     if (!&canmodify($usec)) {
1.633     www      2738: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2739: 	return;
1.180     albertel 2740:     } else {
1.468     albertel 2741: 	$request->print('</div>'."\n");
1.41      ng       2742:     }
1.33      ng       2743: 
1.773     raeburn  2744:     # grading message center
                   2745: 
                   2746:     if ($env{'form.compmsg'}) {
                   2747:         my $result='<div class="LC_Box">'.
                   2748:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2749:                    '<div class="LC_grade_message_center_body">';
                   2750:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2751:         my $msgfor = $givenn.' '.$lastname;
                   2752:         if (scalar(@$col_fullnames) > 0) {
                   2753:             my $lastone = pop(@$col_fullnames);
                   2754:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2755:         }
                   2756:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2757:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2758:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2759:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2760:                  ',\''.$msgfor.'\');" target="_self">'.
                   2761:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2762:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2763:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2764:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2765:                  '<br />&nbsp;('.
                   2766:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2767:                  '</div></div>';
                   2768:         $request->print($result);
1.118     ng       2769:     }
1.41      ng       2770: 
                   2771:     my %seen = ();
                   2772:     my @partlist;
1.129     ng       2773:     my @gradePartRespid;
1.745     raeburn  2774:     my @part_response_id;
                   2775:     if ($is_tool) {
                   2776:         @part_response_id = ([0,'']);
                   2777:     } else {
                   2778:         @part_response_id = &flatten_responseType($responseType);
                   2779:     }
1.585     bisitz   2780:     $request->print(
1.588     bisitz   2781:         '<div class="LC_Box">'
                   2782:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2783:     );
1.592     bisitz   2784:     $request->print(&gradeBox_start());
1.375     albertel 2785:     foreach my $part_response_id (@part_response_id) {
                   2786:     	my ($partid,$respid) = @{ $part_response_id };
                   2787: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2788: 	next if ($seen{$partid} > 0);
1.41      ng       2789: 	$seen{$partid}++;
1.524     raeburn  2790: 	push(@partlist,$partid);
                   2791: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2792: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2793:     }
1.585     bisitz   2794:     $request->print(&gradeBox_end()); # </div>
                   2795:     $request->print('</div>');
1.468     albertel 2796: 
                   2797:     $request->print('<div class="LC_grade_info_links">');
                   2798:     $request->print('</div>');
                   2799: 
1.45      ng       2800:     $result='<input type="hidden" name="partlist'.$counter.
                   2801: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2802:     $result.='<input type="hidden" name="gradePartRespid'.
                   2803: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2804:     my $ctr = 0;
                   2805:     while ($ctr < scalar(@partlist)) {
                   2806: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2807: 	    $partlist[$ctr].'" />'."\n";
                   2808: 	$ctr++;
                   2809:     }
1.468     albertel 2810:     $request->print($result.''."\n");
1.41      ng       2811: 
1.441     www      2812: # Done with printing info for one student
                   2813: 
1.468     albertel 2814:     $request->print('</div>');#LC_grade_show_user
1.441     www      2815: 
                   2816: 
1.41      ng       2817:     # print end of form
                   2818:     if ($counter == $total) {
1.592     bisitz   2819:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2820: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2821: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2822: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2823: 	my $ntstu ='<select name="NTSTU">'.
                   2824: 	    '<option>1</option><option>2</option>'.
                   2825: 	    '<option>3</option><option>5</option>'.
                   2826: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2827: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2828: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2829:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2830: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2831: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2832: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2833: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2834:         $endform.='<span class="LC_warning">'.
                   2835:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2836:                   '</span>'."\n" ;
1.349     albertel 2837:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2838:             "' name='increment' />";
1.485     albertel 2839: 	$endform.='</td></tr></table></form>';
1.41      ng       2840: 	$request->print($endform);
                   2841:     }
                   2842:     return '';
1.38      ng       2843: }
                   2844: 
1.464     albertel 2845: sub check_collaborators {
                   2846:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2847:     my ($result,@col_fullnames);
                   2848:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2849:     foreach my $part (keys(%$handgrade)) {
                   2850: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2851: 					'.maxcollaborators',
                   2852: 					$symb,$udom,$uname);
                   2853: 	next if ($ncol <= 0);
                   2854: 	$part =~ s/\_/\./g;
                   2855: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2856: 	my (@good_collaborators, @bad_collaborators);
                   2857: 	foreach my $possible_collaborator
1.630     www      2858: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2859: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2860: 	    next if ($possible_collaborator eq '');
1.631     www      2861: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2862: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2863: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2864: 	    # Doing this grep allows 'fuzzy' specification
                   2865: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2866: 			       keys(%$classlist));
                   2867: 	    if (! scalar(@matches)) {
                   2868: 		push(@bad_collaborators, $possible_collaborator);
                   2869: 	    } else {
                   2870: 		push(@good_collaborators, @matches);
                   2871: 	    }
                   2872: 	}
                   2873: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2874: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2875: 	    foreach my $name (@good_collaborators) {
                   2876: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2877: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2878: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2879: 	    }
1.630     www      2880: 	    $result.='</ol><br />'."\n";
1.466     albertel 2881: 	    my ($part)=split(/\./,$part);
1.464     albertel 2882: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2883: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2884: 		"\n";
                   2885: 	}
                   2886: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2887: 	    $result.='<div class="LC_warning">';
1.464     albertel 2888: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2889: 	    $result .= '</div>';
                   2890: 	}         
                   2891: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2892: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2893: 	    $result .= &mt('This student has submitted too many '.
                   2894: 		'collaborators.  Maximum is [_1].',$ncol);
                   2895: 	    $result .= '</div>';
                   2896: 	}
                   2897:     }
                   2898:     return ($result,$fullname,\@col_fullnames);
                   2899: }
                   2900: 
1.44      ng       2901: #--- Retrieve the last submission for all the parts
1.38      ng       2902: sub get_last_submission {
1.745     raeburn  2903:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2904:     my (@string,$timestamp,%lasthidden);
1.119     ng       2905:     if ($$returnhash{'version'}) {
1.46      ng       2906: 	my %lasthash=();
                   2907: 	my ($version);
1.119     ng       2908: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2909: 	    foreach my $key (sort(split(/\:/,
                   2910: 					$$returnhash{$version.':keys'}))) {
                   2911: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2912: 		$timestamp = 
1.545     raeburn  2913: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2914: 	    }
                   2915: 	}
1.640     raeburn  2916:         my (%typeparts,%randombytry);
1.596     raeburn  2917:         my $showsurv = 
                   2918:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2919:         foreach my $key (sort(keys(%lasthash))) {
                   2920:             if ($key =~ /\.type$/) {
                   2921:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2922:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2923:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2924:                     my ($ign,@parts) = split(/\./,$key);
                   2925:                     pop(@parts);
1.641     raeburn  2926:                     my $id = join('.',@parts);
1.640     raeburn  2927:                     if ($lasthash{$key} eq 'randomizetry') {
                   2928:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2929:                     } else {
                   2930:                         unless ($showsurv) {
                   2931:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2932:                         }
1.596     raeburn  2933:                     }
                   2934:                     delete($lasthash{$key});
                   2935:                 }
                   2936:             }
                   2937:         }
                   2938:         my @hidden = keys(%typeparts);
1.640     raeburn  2939:         my @randomize = keys(%randombytry);
1.397     albertel 2940: 	foreach my $key (keys(%lasthash)) {
                   2941: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2942:             my $hide;
                   2943:             if (@hidden) {
                   2944:                 foreach my $id (@hidden) {
                   2945:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2946:                         $hide = 'anon';
1.596     raeburn  2947:                         last;
                   2948:                     }
                   2949:                 }
                   2950:             }
1.640     raeburn  2951:             unless ($hide) {
                   2952:                 if (@randomize) {
1.732     raeburn  2953:                     foreach my $id (@randomize) {
1.640     raeburn  2954:                         if ($key =~ /^\Q$id\E/) {
                   2955:                             $hide = 'rand';
                   2956:                             last;
                   2957:                         }
                   2958:                     }
                   2959:                 }
                   2960:             }
1.397     albertel 2961: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2962: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2963:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2964:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2965:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2966: 	}
                   2967:     }
1.397     albertel 2968:     if (!@string) {
1.745     raeburn  2969:         my $msg;
                   2970:         if ($is_tool) {
1.747     raeburn  2971:             $msg = &mt('No grade passed back.');
1.745     raeburn  2972:         } else {
                   2973:             $msg = &mt('Nothing submitted - no attempts.');
                   2974:         }
1.397     albertel 2975: 	$string[0] =
1.745     raeburn  2976: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2977:     }
                   2978:     return (\@string,\$timestamp);
1.38      ng       2979: }
1.35      ng       2980: 
1.44      ng       2981: #--- High light keywords, with style choosen by user.
1.38      ng       2982: sub keywords_highlight {
1.44      ng       2983:     my $string    = shift;
1.257     albertel 2984:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2985:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2986:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2987:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2988:     foreach my $keyword (@keylist) {
                   2989: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2990:     }
                   2991:     return $string;
1.38      ng       2992: }
1.36      ng       2993: 
1.671     raeburn  2994: # For Tasks provide a mechanism to display previous version for one specific student
                   2995: 
                   2996: sub show_previous_task_version {
                   2997:     my ($request,$symb) = @_;
                   2998:     if ($symb eq '') {
1.717     bisitz   2999:         $request->print(
                   3000:             '<span class="LC_error">'.
                   3001:             &mt('Unable to handle ambiguous references.').
                   3002:             '</span>');
1.671     raeburn  3003:         return '';
                   3004:     }
                   3005:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3006:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3007:     if (!&canview($usec)) {
1.712     bisitz   3008:         $request->print(
                   3009:             '<span class="LC_warning">'.
1.713     bisitz   3010:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   3011:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   3012:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   3013:             '</span>');
1.671     raeburn  3014:         return;
                   3015:     }
                   3016:     my $mode = 'both';
                   3017:     my $isTask = ($symb =~/\.task$/);
                   3018:     if ($isTask) {
                   3019:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   3020:             if ($env{'form.fullname'} eq '') {
                   3021:                 $env{'form.fullname'} =
                   3022:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3023:             }
                   3024:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   3025:             $request->print("\n\n".
                   3026:                             '<div class="LC_grade_show_user">'.
                   3027:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   3028:                             '</h2>'."\n");
                   3029:             &Apache::lonxml::clear_problem_counter();
                   3030:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   3031:                             {'previousversion' => $env{'form.previousversion'} }));
                   3032:             $request->print("\n</div>");
                   3033:         }
                   3034:     }
                   3035:     return;
                   3036: }
                   3037: 
                   3038: sub choose_task_version_form {
                   3039:     my ($symb,$uname,$udom,$nomenu) = @_;
                   3040:     my $isTask = ($symb =~/\.task$/);
                   3041:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   3042:     if ($isTask) {
                   3043:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3044:                                               $udom,$uname);
                   3045:         if (($record{'resource.0.version'} eq '') ||
                   3046:             ($record{'resource.0.version'} < 2)) {
                   3047:             return ($record{'resource.0.version'},
                   3048:                     $record{'resource.0.version'},$result,$js);
                   3049:         } else {
                   3050:             $current = $record{'resource.0.version'};
                   3051:         }
                   3052:         if ($env{'form.previousversion'}) {
                   3053:             $displayed = $env{'form.previousversion'};
                   3054:             $rowtitle = &mt('Choose another version:')
                   3055:         } else {
                   3056:             $displayed = $current;
                   3057:             $rowtitle = &mt('Show earlier version:');
                   3058:         }
                   3059:         $result = '<div class="LC_left_float">';
                   3060:         my $list;
                   3061:         my $numversions = 0;
                   3062:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3063:             if ($i == $current) {
                   3064:                 if (!$env{'form.previousversion'} || $nomenu) {
                   3065:                     next;
                   3066:                 } else {
                   3067:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3068:                     $numversions ++;
                   3069:                 }
                   3070:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3071:                 unless ($i == $env{'form.previousversion'}) {
                   3072:                     $numversions ++;
                   3073:                 }
                   3074:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3075:             }
                   3076:         }
                   3077:         if ($numversions) {
                   3078:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3079:             $result .=
                   3080:                 '<form name="getprev" method="post" action=""'.
                   3081:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3082:                 &Apache::loncommon::start_data_table().
                   3083:                 &Apache::loncommon::start_data_table_row().
                   3084:                 '<th align="left">'.$rowtitle.'</th>'.
                   3085:                 '<td><select name="version">'.
                   3086:                 '<option>'.&mt('Select').'</option>'.
                   3087:                 $list.
                   3088:                 '</select></td>'.
                   3089:                 &Apache::loncommon::end_data_table_row();
                   3090:             unless ($nomenu) {
                   3091:                 $result .= &Apache::loncommon::start_data_table_row().
                   3092:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3093:                 '<td><span class="LC_nobreak">'.
                   3094:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3095:                 &mt('Yes').'</label>'.
                   3096:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3097:                 '</span></td>'.
                   3098:                 &Apache::loncommon::end_data_table_row();
                   3099:             }
                   3100:             $result .=
                   3101:                 &Apache::loncommon::start_data_table_row().
                   3102:                 '<th align="left">&nbsp;</th>'.
                   3103:                 '<td>'.
                   3104:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3105:                 '</td>'.
                   3106:                 &Apache::loncommon::end_data_table_row().
                   3107:                 &Apache::loncommon::end_data_table().
                   3108:                 '</form>';
                   3109:             $js = &previous_display_javascript($nomenu,$current);
                   3110:         } elsif ($displayed && $nomenu) {
                   3111:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3112:         } else {
                   3113:             $result .= &mt('No previous versions to show for this student');
                   3114:         }
                   3115:         $result .= '</div>';
                   3116:     }
                   3117:     return ($current,$displayed,$result,$js);
                   3118: }
                   3119: 
                   3120: sub previous_display_javascript {
                   3121:     my ($nomenu,$current) = @_;
                   3122:     my $js = <<"JSONE";
                   3123: <script type="text/javascript">
                   3124: // <![CDATA[
                   3125: function previousVersion(uname,udom,symb) {
                   3126:     var current = '$current';
                   3127:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3128:     var prevstr = new RegExp("^\\\\d+\$");
                   3129:     if (!prevstr.test(version)) {
                   3130:         return false;
                   3131:     }
                   3132:     var url = '';
                   3133:     if (version == current) {
                   3134:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3135:     } else {
                   3136:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3137:     }
                   3138: JSONE
                   3139:     if ($nomenu) {
                   3140:         $js .= <<"JSTWO";
                   3141:     document.location.href = url;
                   3142: JSTWO
                   3143:     } else {
                   3144:         $js .= <<"JSTHREE";
                   3145:     var newwin = 0;
                   3146:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3147:         if (document.getprev.prevwin[i].checked == true) {
                   3148:             newwin = document.getprev.prevwin[i].value;
                   3149:         }
                   3150:     }
                   3151:     if (newwin == 1) {
                   3152:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3153:         url = url+'&inhibitmenu=yes';
                   3154:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3155:             previousWin = window.open(url,'',options,1);
                   3156:         } else {
                   3157:             previousWin.location.href = url;
                   3158:         }
                   3159:         previousWin.focus();
                   3160:         return false;
                   3161:     } else {
                   3162:         document.location.href = url;
                   3163:         return false;
                   3164:     }
                   3165: JSTHREE
                   3166:     }
                   3167:     $js .= <<"ENDJS";
                   3168:     return false;
                   3169: }
                   3170: // ]]>
                   3171: </script>
                   3172: ENDJS
                   3173: 
                   3174: }
                   3175: 
1.44      ng       3176: #--- Called from submission routine
1.38      ng       3177: sub processHandGrade {
1.608     www      3178:     my ($request,$symb) = @_;
1.324     albertel 3179:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3180:     my $button = $env{'form.gradeOpt'};
                   3181:     my $ngrade = $env{'form.NCT'};
                   3182:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3183:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3184:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3185: 
1.44      ng       3186:     if ($button eq 'Save & Next') {
                   3187: 	my $ctr = 0;
                   3188: 	while ($ctr < $ngrade) {
1.257     albertel 3189: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  3190: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   3191:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3192: 	    if ($errorflag eq 'no_score') {
                   3193: 		$ctr++;
                   3194: 		next;
                   3195: 	    }
1.104     albertel 3196: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3197: 		$request->print(
                   3198:                     '<span class="LC_error">'
                   3199:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3200:                    .'</span>');
1.104     albertel 3201: 		$ctr++;
                   3202: 		next;
                   3203: 	    }
1.726     raeburn  3204:             if ($numhidden) {
                   3205:                 $request->print(
                   3206:                     '<span class="LC_info">'
                   3207:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3208:                    .'</span><br />');
                   3209:             }
1.257     albertel 3210: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3211: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3212: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3213:             my ($feedurl,$showsymb) =
                   3214: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3215: 	    my $messagetail;
1.62      albertel 3216: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3217: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3218: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3219: 		$subject.=' ['.$restitle.']';
1.44      ng       3220: 		my (@msgnum) = split(/,/,$includemsg);
                   3221: 		foreach (@msgnum) {
1.257     albertel 3222: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3223: 		}
1.80      ng       3224: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3225: 		if ($env{'form.withgrades'.$ctr}) {
                   3226: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3227: 		    $messagetail = " for <a href=\"".
1.605     www      3228: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3229: 		}
                   3230: 		$msgstatus = 
                   3231:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3232: 						     $message.$messagetail,
1.418     albertel 3233:                                                      undef,$feedurl,undef,
1.386     raeburn  3234:                                                      undef,undef,$showsymb,
                   3235:                                                      $restitle);
1.574     bisitz   3236: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3237: 				$msgstatus.'<br />');
1.44      ng       3238: 	    }
1.257     albertel 3239: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3240: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3241: 		foreach my $collabstr (@collabstrs) {
                   3242: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3243: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3244: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3245: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3246: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3247: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3248: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3249: 			    next;
1.418     albertel 3250: 			} elsif ($message ne '') {
                   3251: 			    my ($baseurl,$showsymb) = 
                   3252: 				&get_feedurl_and_symb($symb,$collaborator,
                   3253: 						      $udom);
                   3254: 			    if ($env{'form.withgrades'.$ctr}) {
                   3255: 				$messagetail = " for <a href=\"".
1.605     www      3256:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3257: 			    }
1.418     albertel 3258: 			    $msgstatus = 
                   3259: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3260: 			}
1.44      ng       3261: 		    }
                   3262: 		}
                   3263: 	    }
                   3264: 	    $ctr++;
                   3265: 	}
                   3266:     }
                   3267: 
1.773     raeburn  3268:     my $res_error;
                   3269:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3270:     if ($res_error) {
                   3271:         $request->print(&navmap_errormsg());
                   3272:         return;
                   3273:     }
                   3274: 
                   3275:     my %keyhash = ();
                   3276:     if ($numessay) {
1.119     ng       3277: 	# Keywords sorted in alphabatical order
1.257     albertel 3278: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3279: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.775     raeburn  3280: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3281: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3282: 	$env{'form.keywords'} = join(' ',@keywords);
                   3283: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3284: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3285: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3286: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3287: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  3288:     }
1.119     ng       3289: 
1.773     raeburn  3290:     if ($env{'form.compmsg'}) {
1.119     ng       3291: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3292: 	# New messages are saved in env for the next student.
1.119     ng       3293: 	# All messages are saved in nohist_handgrade.db
                   3294: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3295: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3296: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3297: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3298: 		$idx++;
                   3299: 	    }
                   3300: 	    $ctr++;
1.41      ng       3301: 	}
1.119     ng       3302: 	$ctr = 0;
                   3303: 	while ($ctr < $ngrade) {
1.257     albertel 3304: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  3305: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3306: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3307: 	        $idx++;
1.119     ng       3308: 	    }
                   3309: 	    $ctr++;
1.41      ng       3310: 	}
1.257     albertel 3311: 	$env{'form.savemsgN'} = --$idx;
                   3312: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       3313:     }
1.773     raeburn  3314:     if (($numessay) || ($env{'form.compmsg'})) {
                   3315:         my $putresult = &Apache::lonnet::put
                   3316:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   3317:     }
                   3318: 
1.44      ng       3319:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3320:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3321:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3322: 	my ($ctr,$total) = (0,0);
                   3323: 	while ($ctr < $ngrade) {
1.257     albertel 3324: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3325: 	    $ctr++;
                   3326: 	}
1.257     albertel 3327: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3328: 	$ctr = 0;
                   3329: 	while ($ctr < $total) {
1.257     albertel 3330: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3331: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3332: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3333: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3334: 	    $ctr++;
                   3335: 	}
                   3336: 	return '';
                   3337:     }
1.36      ng       3338: 
1.44      ng       3339:     # Get the next/previous one or group of students
1.257     albertel 3340:     my $firststu = $env{'form.unamedom0'};
                   3341:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3342:     my $ctr = 2;
1.41      ng       3343:     while ($laststu eq '') {
1.257     albertel 3344: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3345: 	$ctr++;
                   3346: 	$laststu = $firststu if ($ctr > $ngrade);
                   3347:     }
1.44      ng       3348: 
1.41      ng       3349:     my (@parsedlist,@nextlist);
                   3350:     my ($nextflg) = 0;
1.524     raeburn  3351:     foreach my $item (sort 
1.294     albertel 3352: 	     {
                   3353: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3354: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3355: 		 }
                   3356: 		 return $a cmp $b;
                   3357: 	     } (keys(%$fullname))) {
1.41      ng       3358: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3359: 	    push(@parsedlist,$item);
1.41      ng       3360: 	}
1.524     raeburn  3361: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3362: 	if ($button eq 'Previous') {
1.524     raeburn  3363: 	    last if ($item eq $firststu);
                   3364: 	    push(@parsedlist,$item);
1.41      ng       3365: 	}
                   3366:     }
                   3367:     $ctr = 0;
                   3368:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3369:     foreach my $student (@parsedlist) {
1.257     albertel 3370: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3371: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3372: 	
                   3373: 	if ($submitonly eq 'queued') {
                   3374: 	    my %queue_status = 
                   3375: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3376: 							$udom,$uname);
                   3377: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3378: 	}
                   3379: 
1.156     albertel 3380: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3381: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3382: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3383: 	    my $submitted = 0;
1.248     albertel 3384: 	    my $ungraded = 0;
                   3385: 	    my $incorrect = 0;
1.524     raeburn  3386: 	    foreach my $item (keys(%status)) {
                   3387: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3388: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3389: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3390: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3391: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3392: 		    $submitted = 0;
                   3393: 		}
1.41      ng       3394: 	    }
1.156     albertel 3395: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3396: 				     $submitonly eq 'incorrect' ||
                   3397: 				     $submitonly eq 'graded'));
1.248     albertel 3398: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3399: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3400: 	}
1.524     raeburn  3401: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3402: 	last if ($ctr == $ntstu);
1.41      ng       3403: 	$ctr++;
                   3404:     }
1.36      ng       3405: 
1.41      ng       3406:     $ctr = 0;
                   3407:     my $total = scalar(@nextlist)-1;
1.39      ng       3408: 
1.524     raeburn  3409:     foreach (sort(@nextlist)) {
1.41      ng       3410: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3411: 	$env{'form.student'}  = $uname;
                   3412: 	$env{'form.userdom'}  = $udom;
                   3413: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3414: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3415: 	$ctr++;
                   3416:     }
                   3417:     if ($total < 0) {
1.653     raeburn  3418: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3419: 	$request->print($the_end);
                   3420:     }
                   3421:     return '';
1.38      ng       3422: }
1.36      ng       3423: 
1.44      ng       3424: #---- Save the score and award for each student, if changed
1.38      ng       3425: sub saveHandGrade {
1.324     albertel 3426:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3427:     my @version_parts;
1.104     albertel 3428:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3429: 					   $env{'request.course.id'});
1.104     albertel 3430:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3431:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3432:     my @parts_graded;
1.77      ng       3433:     my %newrecord  = ();
1.726     raeburn  3434:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3435:     my %aggregate = ();
                   3436:     my $aggregateflag = 0;
1.726     raeburn  3437:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3438:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3439:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3440:         $totchg += $numchgs;
                   3441:     }
1.301     albertel 3442:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3443:     foreach my $new_part (@parts) {
1.337     banghart 3444: 	#collaborator ($submi may vary for different parts
1.259     banghart 3445: 	if ($submitter && $new_part ne $part) { next; }
                   3446: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3447: 	if ($dropMenu eq 'excused') {
1.259     banghart 3448: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3449: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3450: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3451: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3452: 		}
1.364     banghart 3453: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3454: 	    }
1.125     ng       3455: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3456: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3457: 	    foreach my $key (keys(%record)) {
1.259     banghart 3458: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3459: 	    }
1.259     banghart 3460: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3461: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3462:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3463: 
                   3464:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3465: 					       [$new_part]);
                   3466:             my $aggtries =$totaltries;
1.269     raeburn  3467:             if ($last_resets{$new_part}) {
1.270     albertel 3468:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3469: 					   $new_part);
1.269     raeburn  3470:             }
1.270     albertel 3471: 
                   3472:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3473:             if ($aggtries > 0) {
1.327     albertel 3474:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3475:                 $aggregateflag = 1;
                   3476:             }
1.125     ng       3477: 	} elsif ($dropMenu eq '') {
1.259     banghart 3478: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3479: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3480: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3481: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3482: 		next;
                   3483: 	    }
1.259     banghart 3484: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3485: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3486: 	    my $partial= $pts/$wgt;
1.259     banghart 3487: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3488: 		#do not update score for part if not changed.
1.346     banghart 3489:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3490: 		next;
1.251     banghart 3491: 	    } else {
1.524     raeburn  3492: 	        push(@parts_graded,$new_part);
1.153     albertel 3493: 	    }
1.259     banghart 3494: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3495: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3496: 	    }
1.259     banghart 3497: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3498: 	    if ($partial == 0) {
1.153     albertel 3499: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3500: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3501: 		}
1.41      ng       3502: 	    } else {
1.153     albertel 3503: 		if ($record{$reckey} ne 'correct_by_override') {
                   3504: 		    $newrecord{$reckey} = 'correct_by_override';
                   3505: 		}
                   3506: 	    }	    
                   3507: 	    if ($submitter && 
1.259     banghart 3508: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3509: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3510: 	    }
1.259     banghart 3511: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3512: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3513: 	}
1.259     banghart 3514: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3515: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3516: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3517: 	        $dropMenu eq 'reset status')
                   3518: 	   {
1.524     raeburn  3519: 	    push(@version_parts,$new_part);
1.259     banghart 3520: 	}
1.41      ng       3521:     }
1.301     albertel 3522:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3523:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3524: 
1.344     albertel 3525:     if (%newrecord) {
                   3526:         if (@version_parts) {
1.364     banghart 3527:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3528:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3529: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3530: 	    foreach my $new_part (@version_parts) {
                   3531: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3532: 				$new_part,\%newrecord);
                   3533: 	    }
1.259     banghart 3534:         }
1.44      ng       3535: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3536: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3537: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3538: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3539:     }
1.269     raeburn  3540:     if ($aggregateflag) {
                   3541:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3542: 			      $cdom,$cnum);
1.269     raeburn  3543:     }
1.726     raeburn  3544:     return ('',$pts,$wgt,$totchg);
                   3545: }
                   3546: 
                   3547: sub makehidden {
1.728     raeburn  3548:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3549:     return unless (ref($record) eq 'HASH');
                   3550:     my %modified;
                   3551:     my $numchanged = 0;
                   3552:     if (exists($record->{$version.':keys'})) {
                   3553:         my $partsregexp = $parts;
                   3554:         $partsregexp =~ s/,/|/g;
                   3555:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3556:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3557:                  my $item = $1;
                   3558:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3559:                      $modified{$key} = $record->{$version.':'.$key};
                   3560:                  }
                   3561:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3562:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3563:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3564:                 $modified{$key} = $record->{$version.':'.$key};
                   3565:             }
                   3566:         }
                   3567:         if (keys(%modified)) {
                   3568:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3569:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3570:                 $numchanged ++;
                   3571:             }
                   3572:         }
                   3573:     }
                   3574:     return $numchanged;
1.36      ng       3575: }
1.322     albertel 3576: 
1.380     albertel 3577: sub check_and_remove_from_queue {
                   3578:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3579:     my @ungraded_parts;
                   3580:     foreach my $part (@{$parts}) {
                   3581: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3582: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3583: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3584: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3585: 		) {
                   3586: 	    push(@ungraded_parts, $part);
                   3587: 	}
                   3588:     }
                   3589:     if ( !@ungraded_parts ) {
                   3590: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3591: 					       $cnum,$domain,$stuname);
                   3592:     }
                   3593: }
                   3594: 
1.337     banghart 3595: sub handback_files {
                   3596:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3597:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3598:     my $res_error;
                   3599:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3600:     if ($res_error) {
                   3601:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3602:         return;
                   3603:     }
1.654     raeburn  3604:     my @handedback;
                   3605:     my $file_msg;
1.375     albertel 3606:     my @part_response_id = &flatten_responseType($responseType);
                   3607:     foreach my $part_response_id (@part_response_id) {
                   3608:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3609: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3610:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3611:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3612:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3613:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3614:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3615:                     my ($directory,$answer_file) = 
1.654     raeburn  3616:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3617:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3618: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3619: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3620:                     my $getpropath = 1;
1.773     raeburn  3621:                     my ($dir_list,$listerror) =
1.662     raeburn  3622:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3623:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3624: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3625:                     # fix filename
1.355     banghart 3626:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3627:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3628:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3629:             	                                $save_file_name);
1.337     banghart 3630:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3631:                         $request->print('<br /><span class="LC_error">'.
                   3632:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3633:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3634:                                         '</span>');
1.356     banghart 3635:                     } else {
1.360     banghart 3636:                         # mark the file as read only
1.654     raeburn  3637:                         push(@handedback,$save_file_name);
1.367     albertel 3638: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3639: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3640: 			}
                   3641:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3642: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3643:                     }
1.686     bisitz   3644:                     $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 3645:                 }
                   3646:             }
                   3647:         }
1.654     raeburn  3648:     }
                   3649:     if (@handedback > 0) {
                   3650:         $request->print('<br />');
                   3651:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3652:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3653:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3654:         my ($subject,$message);
                   3655:         if (scalar(@handedback) == 1) {
                   3656:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3657:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3658:         } else {
                   3659:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3660:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3661:         }
                   3662:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3663:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3664:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3665:         my ($feedurl,$showsymb) =
                   3666:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3667:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3668:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3669:         my $msgstatus =
                   3670:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3671:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3672:                  $restitle);
                   3673:         if ($msgstatus) {
                   3674:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3675:         }
                   3676:     }
1.338     banghart 3677:     return;
1.337     banghart 3678: }
                   3679: 
1.418     albertel 3680: sub get_feedurl_and_symb {
                   3681:     my ($symb,$uname,$udom) = @_;
                   3682:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3683:     $url = &Apache::lonnet::clutter($url);
                   3684:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3685: 					$symb,$udom,$uname);
                   3686:     if ($encrypturl =~ /^yes$/i) {
                   3687: 	&Apache::lonenc::encrypted(\$url,1);
                   3688: 	&Apache::lonenc::encrypted(\$symb,1);
                   3689:     }
                   3690:     return ($url,$symb);
                   3691: }
                   3692: 
1.313     banghart 3693: sub get_submitted_files {
                   3694:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3695:     my @files;
                   3696:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3697:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3698:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3699:     	    push(@files,$file_url.$file);
                   3700:         }
                   3701:     }
                   3702:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3703:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3704:     }
                   3705:     return (\@files);
                   3706: }
1.322     albertel 3707: 
1.269     raeburn  3708: # ----------- Provides number of tries since last reset.
                   3709: sub get_num_tries {
                   3710:     my ($record,$last_reset,$part) = @_;
                   3711:     my $timestamp = '';
                   3712:     my $num_tries = 0;
                   3713:     if ($$record{'version'}) {
                   3714:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3715:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3716:                 $timestamp = $$record{$version.':timestamp'};
                   3717:                 if ($timestamp > $last_reset) {
                   3718:                     $num_tries ++;
                   3719:                 } else {
                   3720:                     last;
                   3721:                 }
                   3722:             }
                   3723:         }
                   3724:     }
                   3725:     return $num_tries;
                   3726: }
                   3727: 
                   3728: # ----------- Determine decrements required in aggregate totals 
                   3729: sub decrement_aggs {
                   3730:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3731:     my %decrement = (
                   3732:                         attempts => 0,
                   3733:                         users => 0,
                   3734:                         correct => 0
                   3735:                     );
                   3736:     $decrement{'attempts'} = $aggtries;
                   3737:     if ($solvedstatus =~ /^correct/) {
                   3738:         $decrement{'correct'} = 1;
                   3739:     }
                   3740:     if ($aggtries == $totaltries) {
                   3741:         $decrement{'users'} = 1;
                   3742:     }
1.524     raeburn  3743:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3744:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3745:     }
                   3746:     return;
                   3747: }
                   3748: 
                   3749: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3750: sub get_last_resets {
1.270     albertel 3751:     my ($symb,$courseid,$partids) =@_;
                   3752:     my %last_resets;
1.269     raeburn  3753:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3754:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3755:     my @keys;
                   3756:     foreach my $part (@{$partids}) {
                   3757: 	push(@keys,"$symb\0$part\0resettime");
                   3758:     }
                   3759:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3760: 				     $cdom,$cname);
                   3761:     foreach my $part (@{$partids}) {
                   3762: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3763:     }
1.270     albertel 3764:     return %last_resets;
1.269     raeburn  3765: }
                   3766: 
1.251     banghart 3767: # ----------- Handles creating versions for portfolio files as answers
                   3768: sub version_portfiles {
1.343     banghart 3769:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3770:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3771:     my @returned_keys;
1.255     banghart 3772:     my $parts = join('|', @$parts_graded);
1.277     albertel 3773:     foreach my $key (keys(%$record)) {
1.259     banghart 3774:         my $new_portfiles;
1.263     banghart 3775:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3776:             my @versioned_portfiles;
1.367     albertel 3777:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3778:             if (@portfiles) {
                   3779:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3780:                                                       \@versioned_portfiles);
1.252     banghart 3781:             }
1.343     banghart 3782:             $$record{$key} = join(',',@versioned_portfiles);
                   3783:             push(@returned_keys,$key);
1.251     banghart 3784:         }
                   3785:     } 
1.343     banghart 3786:     return (@returned_keys);   
1.305     banghart 3787: }
                   3788: 
1.44      ng       3789: #--------------------------------------------------------------------------------------
                   3790: #
                   3791: #-------------------------- Next few routines handles grading by section or whole class
                   3792: #
                   3793: #--- Javascript to handle grading by section or whole class
1.42      ng       3794: sub viewgrades_js {
                   3795:     my ($request) = shift;
                   3796: 
1.539     riegler  3797:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3798:     &js_escape(\$alertmsg);
1.597     wenzelju 3799:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3800:    function writePoint(partid,weight,point) {
1.125     ng       3801: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3802: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3803: 	if (point == "textval") {
1.125     ng       3804: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3805: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3806: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3807: 		var resetbox = false;
                   3808: 		for (var i=0; i<radioButton.length; i++) {
                   3809: 		    if (radioButton[i].checked) {
                   3810: 			textbox.value = i;
                   3811: 			resetbox = true;
                   3812: 		    }
                   3813: 		}
                   3814: 		if (!resetbox) {
                   3815: 		    textbox.value = "";
                   3816: 		}
                   3817: 		return;
                   3818: 	    }
1.109     matthew  3819: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3820: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3821: 				   ") greater than the weight for the part. Accept?");
                   3822: 		if (resp == false) {
                   3823: 		    textbox.value = "";
                   3824: 		    return;
                   3825: 		}
                   3826: 	    }
1.42      ng       3827: 	    for (var i=0; i<radioButton.length; i++) {
                   3828: 		radioButton[i].checked=false;
1.109     matthew  3829: 		if (parseFloat(point) == i) {
1.42      ng       3830: 		    radioButton[i].checked=true;
                   3831: 		}
                   3832: 	    }
1.41      ng       3833: 
1.42      ng       3834: 	} else {
1.125     ng       3835: 	    textbox.value = parseFloat(point);
1.42      ng       3836: 	}
1.41      ng       3837: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3838: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3839: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3840: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3841: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3842: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3843: 	    if (saveval != "correct") {
                   3844: 		scorename.value = point;
1.43      ng       3845: 		if (selname[0].selected != true) {
                   3846: 		    selname[0].selected = true;
                   3847: 		}
1.42      ng       3848: 	    }
                   3849: 	}
1.125     ng       3850: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3851:     }
                   3852: 
                   3853:     function writeRadText(partid,weight) {
1.125     ng       3854: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3855: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3856:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3857: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3858: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3859: 	    for (var i=0; i<radioButton.length; i++) {
                   3860: 		radioButton[i].checked=false;
                   3861: 
                   3862: 	    }
                   3863: 	    textbox.value = "";
                   3864: 
                   3865: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3866: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3867: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3868: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3869: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3870: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3871: 		if ((saveval != "correct") || override) {
1.42      ng       3872: 		    scorename.value = "";
1.125     ng       3873: 		    if (selval[1].selected) {
                   3874: 			selname[1].selected = true;
                   3875: 		    } else {
                   3876: 			selname[2].selected = true;
                   3877: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3878: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3879: 		    }
1.42      ng       3880: 		}
                   3881: 	    }
1.43      ng       3882: 	} else {
                   3883: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3884: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3885: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3886: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3887: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3888: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3889: 		if ((saveval != "correct") || override) {
1.125     ng       3890: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3891: 		    selname[0].selected = true;
                   3892: 		}
                   3893: 	    }
                   3894: 	}	    
1.42      ng       3895:     }
                   3896: 
                   3897:     function changeSelect(partid,user) {
1.125     ng       3898: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3899: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3900: 	var point  = textbox.value;
1.125     ng       3901: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3902: 
1.109     matthew  3903: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3904: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3905: 	    textbox.value = "";
                   3906: 	    return;
                   3907: 	}
1.109     matthew  3908: 	if (parseFloat(point) > parseFloat(weight)) {
                   3909: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3910: 			       ") greater than the weight of the part. Accept?");
                   3911: 	    if (resp == false) {
                   3912: 		textbox.value = "";
                   3913: 		return;
                   3914: 	    }
                   3915: 	}
1.42      ng       3916: 	selval[0].selected = true;
                   3917:     }
                   3918: 
                   3919:     function changeOneScore(partid,user) {
1.125     ng       3920: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3921: 	if (selval[1].selected || selval[2].selected) {
                   3922: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3923: 	    if (selval[2].selected) {
                   3924: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3925: 	    }
1.269     raeburn  3926:         }
1.42      ng       3927:     }
                   3928: 
                   3929:     function resetEntry(numpart) {
                   3930: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3931: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3932: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3933: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3934: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3935: 	    for (var i=0; i<radioButton.length; i++) {
                   3936: 		radioButton[i].checked=false;
                   3937: 
                   3938: 	    }
                   3939: 	    textbox.value = "";
                   3940: 	    selval[0].selected = true;
                   3941: 
                   3942: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3943: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3944: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3945: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3946: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3947: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3948: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3949: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3950: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3951: 		if (saveselval == "excused") {
1.43      ng       3952: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3953: 		} else {
1.43      ng       3954: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3955: 		}
                   3956: 	    }
1.41      ng       3957: 	}
1.42      ng       3958:     }
                   3959: 
1.41      ng       3960: VIEWJAVASCRIPT
1.42      ng       3961: }
                   3962: 
1.44      ng       3963: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3964: sub viewgrades {
1.608     www      3965:     my ($request,$symb) = @_;
1.745     raeburn  3966:     my ($is_tool,$toolsymb);
                   3967:     if ($symb =~ /ext\.tool$/) {
                   3968:         $is_tool = 1;
                   3969:         $toolsymb = $symb;
                   3970:     }
1.42      ng       3971:     &viewgrades_js($request);
1.41      ng       3972: 
1.168     albertel 3973:     #need to make sure we have the correct data for later EXT calls, 
                   3974:     #thus invalidate the cache
                   3975:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3976:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3977:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3978:     &Apache::lonnet::clear_EXT_cache_status();
                   3979: 
1.398     albertel 3980:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3981: 
                   3982:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3983:     $result.=&jscriptNform($symb);
1.41      ng       3984: 
1.44      ng       3985:     #beginning of class grading form
1.442     banghart 3986:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3987:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3988: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3989: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3990: 	&build_section_inputs().
1.442     banghart 3991: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3992: 
1.738     raeburn  3993:     #retrieve selected groups
                   3994:     my (@groups,$group_display);
                   3995:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3996:     if (grep(/^all$/,@groups)) {
                   3997:         @groups = ('all');
                   3998:     } elsif (grep(/^none$/,@groups)) {
                   3999:         @groups = ('none');
                   4000:     } elsif (@groups > 0) {
                   4001:         $group_display = join(', ',@groups);
                   4002:     }
                   4003: 
                   4004:     my ($common_header,$specific_header,@sections,$section_display);
1.780     raeburn  4005:     if ($env{'request.course.sec'} ne '') {
                   4006:         @sections = ($env{'request.course.sec'});
                   4007:     } else {
                   4008:         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   4009:     }
                   4010: 
                   4011: # Check if Save button should be usable
                   4012:     my $disabled = ' disabled="disabled"';
                   4013:     if ($perm{'mgr'}) {
                   4014:         if (grep(/^all$/,@sections)) {
                   4015:             undef($disabled);
                   4016:         } else {
                   4017:             foreach my $sec (@sections) {
                   4018:                 if (&canmodify($sec)) {
                   4019:                     undef($disabled);
                   4020:                     last;
                   4021:                 }
                   4022:             }
                   4023:         }
                   4024:     }
1.738     raeburn  4025:     if (grep(/^all$/,@sections)) {
                   4026:         @sections = ('all');
                   4027:         if ($group_display) {
                   4028:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4029:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4030:         } elsif (grep(/^none$/,@groups)) {
                   4031:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4032:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4033:         } else {
                   4034: 	    $common_header = &mt('Assign Common Grade to Class');
                   4035:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4036:         }
                   4037:     } elsif (grep(/^none$/,@sections)) {
                   4038:         @sections = ('none');
                   4039:         if ($group_display) {
                   4040:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4041:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4042:         } elsif (grep(/^none$/,@groups)) {
                   4043:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4044:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4045:         } else {
                   4046:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4047: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4048:         }
                   4049:     } else {
                   4050:         $section_display = join (", ",@sections);
                   4051:         if ($group_display) {
                   4052:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4053:                                  $section_display,$group_display);
                   4054:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4055:                                    $section_display,$group_display);
                   4056:         } elsif (grep(/^none$/,@groups)) {
                   4057:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4058:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4059:         } else {
                   4060:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4061: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4062:         }
                   4063:     }
                   4064:     my %submit_types = &substatus_options();
                   4065:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4066: 
                   4067:     if ($env{'form.submitonly'} eq 'all') {
                   4068:         $result.= '<h3>'.$common_header.'</h3>';
                   4069:     } else {
1.745     raeburn  4070:         my $text;
                   4071:         if ($is_tool) {
                   4072:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4073:         } else {
                   4074:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4075:         }
                   4076:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 4077:     }
1.738     raeburn  4078:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4079:     #radio buttons/text box for assigning points for a section or class.
                   4080:     #handles different parts of a problem
1.582     raeburn  4081:     my $res_error;
                   4082:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4083:     if ($res_error) {
                   4084:         return &navmap_errormsg();
                   4085:     }
1.42      ng       4086:     my %weight = ();
                   4087:     my $ctsparts = 0;
1.45      ng       4088:     my %seen = ();
1.745     raeburn  4089:     my @part_response_id;
                   4090:     if ($is_tool) {
                   4091:         @part_response_id = ([0,'']);
                   4092:     } else {
                   4093:         @part_response_id = &flatten_responseType($responseType);
                   4094:     }
1.375     albertel 4095:     foreach my $part_response_id (@part_response_id) {
                   4096:     	my ($partid,$respid) = @{ $part_response_id };
                   4097: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4098: 	next if $seen{$partid};
                   4099: 	$seen{$partid}++;
1.42      ng       4100: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4101: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4102: 
1.324     albertel 4103: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4104: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4105: 	my $ctr = 0;
1.42      ng       4106: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4107: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4108: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4109: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4110: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4111: 	    $ctr++;
                   4112: 	}
1.485     albertel 4113: 	$radio.='</tr></table>';
                   4114: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4115: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4116: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4117: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   4118:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4119:             '<select name="SELVAL_'.$partid.'" '.
                   4120:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   4121:                 $weight{$partid}.')"> '.
1.401     albertel 4122: 	    '<option selected="selected"> </option>'.
1.485     albertel 4123: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4124: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4125: 	    '</select></td>'.
                   4126:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4127: 	$line.='<input type="hidden" name="partid_'.
                   4128: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4129: 	$line.='<input type="hidden" name="weight_'.
                   4130: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4131: 
                   4132: 	$result.=
                   4133: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4134: 	    '<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 4135: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4136: 	$ctsparts++;
1.41      ng       4137:     }
1.474     albertel 4138:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4139: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4140:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4141: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4142: 
1.44      ng       4143:     #table listing all the students in a section/class
                   4144:     #header of table
1.738     raeburn  4145:     if ($env{'form.submitonly'} eq 'all') {
                   4146:         $result.= '<h3>'.$specific_header.'</h3>';
                   4147:     } else {
1.745     raeburn  4148:         my $text;
                   4149:         if ($is_tool) {
                   4150:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4151:         } else {
                   4152:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4153:         }
                   4154:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  4155:     }
                   4156:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4157: 	      &Apache::loncommon::start_data_table_header_row().
                   4158: 	      '<th>'.&mt('No.').'</th>'.
                   4159: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4160:     my $partserror;
                   4161:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4162:     if ($partserror) {
                   4163:         return &navmap_errormsg();
                   4164:     }
1.324     albertel 4165:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4166:     my @partids = ();
1.41      ng       4167:     foreach my $part (@parts) {
1.745     raeburn  4168: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  4169:         my $narrowtext = &mt('Tries');
                   4170: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  4171: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 4172: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4173:         push(@partids,$partid);
1.628     www      4174: #
                   4175: # FIXME: Looks like $display looks at English text
                   4176: #
1.324     albertel 4177: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4178: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4179: 	    $result.='<th>'.
1.697     bisitz   4180: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   4181: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4182: 	    next;
1.485     albertel 4183: 	    
1.207     albertel 4184: 	} else {
1.485     albertel 4185: 	    if ($display =~ /Problem Status/) {
                   4186: 		my $grade_status_mt = &mt('Grade Status');
                   4187: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4188: 	    }
                   4189: 	    my $part_mt = &mt('Part:');
                   4190: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4191: 	}
1.485     albertel 4192: 
1.474     albertel 4193: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4194:     }
1.474     albertel 4195:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4196: 
1.270     albertel 4197:     my %last_resets = 
                   4198: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4199: 
1.41      ng       4200:     #get info for each student
1.44      ng       4201:     #list all the students - with points and grade status
1.738     raeburn  4202:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4203:     my $ctr = 0;
1.294     albertel 4204:     foreach (sort 
                   4205: 	     {
                   4206: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4207: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4208: 		 }
                   4209: 		 return $a cmp $b;
                   4210: 	     } (keys(%$fullname))) {
1.324     albertel 4211: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  4212: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4213:     }
1.474     albertel 4214:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4215:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.780     raeburn  4216:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   4217: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4218:     if ($ctr == 0) {
1.442     banghart 4219:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4220:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4221:                 '<span class="LC_warning">';
                   4222:         if ($env{'form.submitonly'} eq 'all') {
                   4223:             if (grep(/^all$/,@sections)) {
                   4224:                 if (grep(/^all$/,@groups)) {
                   4225:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4226:                                    $stu_status);
                   4227:                 } elsif (grep(/^none$/,@groups)) {
                   4228:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4229:                                    $stu_status); 
                   4230:                 } else {
                   4231:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4232:                                    $group_display,$stu_status);
                   4233:                 }
                   4234:             } elsif (grep(/^none$/,@sections)) {
                   4235:                 if (grep(/^all$/,@groups)) {
                   4236:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4237:                                    $stu_status);
                   4238:                 } elsif (grep(/^none$/,@groups)) {
                   4239:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4240:                                    $stu_status);
                   4241:                 } else {
                   4242:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4243:                                    $group_display,$stu_status);
                   4244:                 }
                   4245:             } else {
                   4246:                 if (grep(/^all$/,@groups)) {
                   4247:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4248:                                    $section_display,$stu_status);
                   4249:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4250:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4251:                                    $section_display,$stu_status);
                   4252:                 } else {
                   4253:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4254:                                    $section_display,$group_display,$stu_status);
                   4255:                 }
                   4256:             }
                   4257:         } else {
                   4258:             if (grep(/^all$/,@sections)) {
                   4259:                 if (grep(/^all$/,@groups)) {
                   4260:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4261:                                    $stu_status,$submission_status);
                   4262:                 } elsif (grep(/^none$/,@groups)) {
                   4263:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4264:                                    $stu_status,$submission_status);
                   4265:                 } else {
                   4266:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4267:                                    $group_display,$stu_status,$submission_status);
                   4268:                 }
                   4269:             } elsif (grep(/^none$/,@sections)) {
                   4270:                 if (grep(/^all$/,@groups)) {
                   4271:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4272:                                    $stu_status,$submission_status);
                   4273:                 } elsif (grep(/^none$/,@groups)) {
                   4274:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4275:                                    $stu_status,$submission_status);
                   4276:                 } else {
                   4277:                     $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.',
                   4278:                                    $group_display,$stu_status,$submission_status);
                   4279:                 }
                   4280:             } else {
                   4281:                 if (grep(/^all$/,@groups)) {
                   4282: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4283: 	                           $section_display,$stu_status,$submission_status);
                   4284:                 } elsif (grep(/^none$/,@groups)) {
                   4285:                     $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.',
                   4286:                                    $section_display,$stu_status,$submission_status);
                   4287:                 } else {
                   4288:                     $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.',
                   4289:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4290:                 }
                   4291:             }
                   4292:         }
                   4293: 	$result .= '</span><br />';
1.96      albertel 4294:     }
1.41      ng       4295:     return $result;
                   4296: }
                   4297: 
1.738     raeburn  4298: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4299: sub viewstudentgrade {
1.745     raeburn  4300:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4301:     my ($uname,$udom) = split(/:/,$student);
                   4302:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4303:     my $submitonly = $env{'form.submitonly'};
                   4304:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4305:         my %partstatus = ();
                   4306:         if (ref($parts) eq 'ARRAY') {
                   4307:             foreach my $apart (@{$parts}) {
                   4308:                 my ($part,$type) = &split_part_type($apart);
                   4309:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4310:                 $status = 'nothing' if ($status eq '');
                   4311:                 $partstatus{$part}      = $status;
                   4312:                 my $subkey = "resource.$part.submitted_by";
                   4313:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4314:             }
                   4315:             my $submitted = 0;
                   4316:             my $graded = 0;
                   4317:             my $incorrect = 0;
                   4318:             foreach my $key (keys(%partstatus)) {
                   4319:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4320:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4321:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4322: 
                   4323:                 my $partid = (split(/\./,$key))[1];
                   4324:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4325:                     $submitted = 0;
                   4326:                 }
                   4327:             }
                   4328:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4329:                                        $submitonly eq 'incorrect' ||
                   4330:                                        $submitonly eq 'graded'));
                   4331:             return if (!$graded && ($submitonly eq 'graded'));
                   4332:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4333:         }
                   4334:     }
                   4335:     if ($submitonly eq 'queued') {
                   4336:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4337:         my %queue_status =
                   4338:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4339:                                                     $udom,$uname);
                   4340:         return if (!defined($queue_status{'gradingqueue'}));
                   4341:     }
                   4342:     $$ctr++;
                   4343:     my %aggregates = ();
1.474     albertel 4344:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4345: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4346: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4347: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4348: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4349: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4350:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4351:     foreach my $apart (@$parts) {
                   4352: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4353: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4354:         $result.='<td align="center">';
1.269     raeburn  4355:         my ($aggtries,$totaltries);
                   4356:         unless (exists($aggregates{$part})) {
1.270     albertel 4357: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4358: 	    $aggtries = $totaltries;
1.269     raeburn  4359:             if ($$last_resets{$part}) {  
1.270     albertel 4360:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4361: 					   $part);
                   4362:             }
1.269     raeburn  4363:             $result.='<input type="hidden" name="'.
                   4364:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4365:             $result.='<input type="hidden" name="'.
                   4366:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4367:             $aggregates{$part} = 1;
                   4368:         }
1.41      ng       4369: 	if ($type eq 'awarded') {
1.320     albertel 4370: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4371: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4372: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4373: 	    $result.='<input type="text" name="'.
1.89      albertel 4374: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4375:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4376: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4377: 	} elsif ($type eq 'solved') {
                   4378: 	    my ($status,$foo)=split(/_/,$score,2);
                   4379: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4380: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4381: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4382: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4383: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4384:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4385: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4386: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4387: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4388: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4389: 	} else {
                   4390: 	    $result.='<input type="hidden" name="'.
                   4391: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4392: 		    "\n";
1.233     albertel 4393: 	    $result.='<input type="text" name="'.
1.122     ng       4394: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4395: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4396: 	}
                   4397:     }
1.474     albertel 4398:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4399:     return $result;
1.38      ng       4400: }
                   4401: 
1.44      ng       4402: #--- change scores for all the students in a section/class
                   4403: #    record does not get update if unchanged
1.38      ng       4404: sub editgrades {
1.608     www      4405:     my ($request,$symb) = @_;
1.745     raeburn  4406:     my $toolsymb;
                   4407:     if ($symb =~ /ext\.tool$/) {
                   4408:         $toolsymb = $symb;
                   4409:     }
1.41      ng       4410: 
1.433     banghart 4411:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4412:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  4413:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4414: 
1.477     albertel 4415:     my $result= &Apache::loncommon::start_data_table().
                   4416: 	&Apache::loncommon::start_data_table_header_row().
                   4417: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4418: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4419:     my %scoreptr = (
                   4420: 		    'correct'  =>'correct_by_override',
                   4421: 		    'incorrect'=>'incorrect_by_override',
                   4422: 		    'excused'  =>'excused',
                   4423: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4424:                     'credited' =>'credit_attempted',
1.43      ng       4425: 		    'nothing'  => '',
                   4426: 		    );
1.257     albertel 4427:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4428: 
1.44      ng       4429:     my (@partid);
                   4430:     my %weight = ();
1.54      albertel 4431:     my %columns = ();
1.44      ng       4432:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4433: 
1.582     raeburn  4434:     my $partserror;
                   4435:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4436:     if ($partserror) {
                   4437:         return &navmap_errormsg();
                   4438:     }
1.54      albertel 4439:     my $header;
1.257     albertel 4440:     while ($ctr < $env{'form.totalparts'}) {
                   4441: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4442: 	push(@partid,$partid);
1.257     albertel 4443: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4444: 	$ctr++;
1.54      albertel 4445:     }
1.324     albertel 4446:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4447:     my $totcolspan = 0;
1.54      albertel 4448:     foreach my $partid (@partid) {
1.478     albertel 4449: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4450: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4451: 	$columns{$partid}=2;
                   4452: 	foreach my $stores (@parts) {
                   4453: 	    my ($part,$type) = &split_part_type($stores);
                   4454: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4455: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4456: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4457: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4458:             my $narrowtext = &mt('Tries');
                   4459: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4460: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4461: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4462: 	    $columns{$partid}+=2;
                   4463: 	}
1.748     raeburn  4464:         $totcolspan += $columns{$partid};
1.54      albertel 4465:     }
                   4466:     foreach my $partid (@partid) {
1.324     albertel 4467: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4468: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4469: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4470: 	    '</th>';
1.54      albertel 4471: 
1.44      ng       4472:     }
1.477     albertel 4473:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4474: 	&Apache::loncommon::start_data_table_header_row().
                   4475: 	$header.
                   4476: 	&Apache::loncommon::end_data_table_header_row();
                   4477:     my @noupdate;
1.126     ng       4478:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4479:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4480: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4481: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4482: 	my %newrecord;
                   4483: 	my $updateflag = 0;
1.108     albertel 4484: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4485: 	my $canmodify = &canmodify($usec);
                   4486: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4487: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4488: 	if (!$canmodify) {
1.477     albertel 4489: 	    push(@noupdate,
1.748     raeburn  4490: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4491: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4492: 	    next;
                   4493: 	}
1.269     raeburn  4494:         my %aggregate = ();
                   4495:         my $aggregateflag = 0;
1.281     albertel 4496: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4497: 	foreach (@partid) {
1.257     albertel 4498: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4499: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4500: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4501: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4502: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4503: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4504: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4505: 	    my $score;
                   4506: 	    if ($partial eq '') {
1.257     albertel 4507: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4508: 	    } elsif ($partial > 0) {
                   4509: 		$score = 'correct_by_override';
                   4510: 	    } elsif ($partial == 0) {
                   4511: 		$score = 'incorrect_by_override';
                   4512: 	    }
1.257     albertel 4513: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4514: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4515: 
1.292     albertel 4516: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4517: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4518: 	    if ($dropMenu eq 'reset status' &&
                   4519: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4520: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4521: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4522: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4523: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4524: 		$updateflag = 1;
1.269     raeburn  4525:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4526:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4527:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4528:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4529:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4530:                     $aggregateflag = 1;
                   4531:                 }
1.139     albertel 4532: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4533: 		$updateflag = 1;
                   4534: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4535: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4536: 		$rec_update++;
1.125     ng       4537: 	    }
                   4538: 
1.93      albertel 4539: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4540: 		'<td align="center">'.$awarded.
                   4541: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4542: 
1.54      albertel 4543: 
                   4544: 	    my $partid=$_;
                   4545: 	    foreach my $stores (@parts) {
                   4546: 		my ($part,$type) = &split_part_type($stores);
                   4547: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4548: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4549: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4550: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4551: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4552: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4553: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4554: 		    $updateflag=1;
                   4555: 		}
1.93      albertel 4556: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4557: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4558: 	    }
1.44      ng       4559: 	}
1.477     albertel 4560: 	$line.="\n";
1.301     albertel 4561: 
                   4562: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4563: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4564: 
1.44      ng       4565: 	if ($updateflag) {
                   4566: 	    $count++;
1.257     albertel 4567: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4568: 				    $udom,$uname);
1.301     albertel 4569: 
                   4570: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4571: 					      $cnum,$udom,$uname)) {
                   4572: 		# need to figure out if should be in queue.
                   4573: 		my %record =  
                   4574: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4575: 					     $udom,$uname);
                   4576: 		my $all_graded = 1;
                   4577: 		my $none_graded = 1;
                   4578: 		foreach my $part (@parts) {
                   4579: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4580: 			$all_graded = 0;
                   4581: 		    } else {
                   4582: 			$none_graded = 0;
                   4583: 		    }
                   4584: 		}
                   4585: 
                   4586: 		if ($all_graded || $none_graded) {
                   4587: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4588: 							   $symb,$cdom,$cnum,
                   4589: 							   $udom,$uname);
                   4590: 		}
                   4591: 	    }
                   4592: 
1.477     albertel 4593: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4594: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4595: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4596: 	    $updateCtr++;
1.93      albertel 4597: 	} else {
1.477     albertel 4598: 	    push(@noupdate,
                   4599: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4600: 	    $noupdateCtr++;
1.44      ng       4601: 	}
1.269     raeburn  4602:         if ($aggregateflag) {
                   4603:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4604: 				  $cdom,$cnum);
1.269     raeburn  4605:         }
1.93      albertel 4606:     }
1.477     albertel 4607:     if (@noupdate) {
1.748     raeburn  4608:         my $numcols=$totcolspan+2;
1.477     albertel 4609: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4610: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4611: 	    &mt('No Changes Occurred For the Students Below').
                   4612: 	    '</td>'.
1.477     albertel 4613: 	    &Apache::loncommon::end_data_table_row();
                   4614: 	foreach my $line (@noupdate) {
                   4615: 	    $result.=
                   4616: 		&Apache::loncommon::start_data_table_row().
                   4617: 		$line.
                   4618: 		&Apache::loncommon::end_data_table_row();
                   4619: 	}
1.44      ng       4620:     }
1.614     www      4621:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4622:     my $msg = '<p><b>'.
                   4623: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4624: 	    $rec_update,$count).'</b><br />'.
                   4625: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4626: 	'</b></p>';
1.44      ng       4627:     return $title.$msg.$result;
1.5       albertel 4628: }
1.54      albertel 4629: 
                   4630: sub split_part_type {
                   4631:     my ($partstr) = @_;
                   4632:     my ($temp,@allparts)=split(/_/,$partstr);
                   4633:     my $type=pop(@allparts);
1.439     albertel 4634:     my $part=join('_',@allparts);
1.54      albertel 4635:     return ($part,$type);
                   4636: }
                   4637: 
1.44      ng       4638: #------------- end of section for handling grading by section/class ---------
                   4639: #
                   4640: #----------------------------------------------------------------------------
                   4641: 
1.5       albertel 4642: 
1.44      ng       4643: #----------------------------------------------------------------------------
                   4644: #
                   4645: #-------------------------- Next few routines handles grading by csv upload
                   4646: #
                   4647: #--- Javascript to handle csv upload
1.27      albertel 4648: sub csvupload_javascript_reverse_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 (i==0 && tw!=0) { foundID=1; }
                   4662:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4663:       if (i==2 && tw!=0) { foundclicker=1; }
                   4664:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4665:     }
1.743     raeburn  4666:     if (founduname==0 && foundID==0 && foundclicker==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:     for (i=0;i<=vf.nfields.value;i++) {
                   4680:       //can not pick the same destination field for both name and domain
                   4681:       if (((i ==0)||(i ==1)) && 
                   4682:           ((tf==0)||(tf==1)) && 
                   4683:           (i!=tf) &&
                   4684:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4685:         eval('vf.f'+i+'.selectedIndex=0;')
                   4686:       }
                   4687:     }
                   4688:   }
                   4689: ENDPICK
                   4690: }
                   4691: 
                   4692: sub csvupload_javascript_forward_associate {
1.743     raeburn  4693:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4694:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4695:   &js_escape(\$error1);
                   4696:   &js_escape(\$error2);
1.27      albertel 4697:   return(<<ENDPICK);
                   4698:   function verify(vf) {
                   4699:     var foundsomething=0;
                   4700:     var founduname=0;
1.243     albertel 4701:     var foundID=0;
1.743     raeburn  4702:     var foundclicker=0;
1.27      albertel 4703:     for (i=0;i<=vf.nfields.value;i++) {
                   4704:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4705:       if (tw==1) { foundID=1; }
                   4706:       if (tw==2) { founduname=1; }
1.745     raeburn  4707:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4708:       if (tw>4) { foundsomething=1; }
1.27      albertel 4709:     }
1.743     raeburn  4710:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4711: 	alert('$error1');
                   4712: 	return;
1.27      albertel 4713:     }
                   4714:     if (foundsomething==0) {
1.246     albertel 4715: 	alert('$error2');
                   4716: 	return;
1.27      albertel 4717:     }
                   4718:     vf.submit();
                   4719:   }
                   4720:   function flip(vf,tf) {
                   4721:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4722:     var i;
                   4723:     //can not pick the same destination field twice
                   4724:     for (i=0;i<=vf.nfields.value;i++) {
                   4725:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4726:         eval('vf.f'+i+'.selectedIndex=0;')
                   4727:       }
                   4728:     }
                   4729:   }
                   4730: ENDPICK
                   4731: }
                   4732: 
1.26      albertel 4733: sub csvuploadmap_header {
1.324     albertel 4734:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4735:     my $javascript;
1.257     albertel 4736:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4737: 	$javascript=&csvupload_javascript_reverse_associate();
                   4738:     } else {
                   4739: 	$javascript=&csvupload_javascript_forward_associate();
                   4740:     }
1.45      ng       4741: 
1.418     albertel 4742:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4743:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4744:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4745:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4746:     my $reverse=&mt("Reverse Association");
1.41      ng       4747:     $request->print(<<ENDPICK);
1.632     www      4748: <br />
                   4749: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4750: <input type="hidden" name="associate"  value="" />
                   4751: <input type="hidden" name="phase"      value="three" />
                   4752: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4753: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4754: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4755: <input type="hidden" name="upfile_associate" 
1.257     albertel 4756:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4757: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4758: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4759: <hr />
                   4760: ENDPICK
1.597     wenzelju 4761:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4762:     return '';
1.26      albertel 4763: 
                   4764: }
                   4765: 
                   4766: sub csvupload_fields {
1.582     raeburn  4767:     my ($symb,$errorref) = @_;
1.745     raeburn  4768:     my $toolsymb;
                   4769:     if ($symb =~ /ext\.tool$/) {
                   4770:         $toolsymb = $symb;
                   4771:     }
1.582     raeburn  4772:     my (@parts) = &getpartlist($symb,$errorref);
                   4773:     if (ref($errorref)) {
                   4774:         if ($$errorref) {
                   4775:             return;
                   4776:         }
                   4777:     }
                   4778: 
1.556     weissno  4779:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4780: 		['username','Student Username'],
1.743     raeburn  4781: 		['clicker','Clicker ID'],
1.243     albertel 4782: 		['domain','Student Domain']);
1.324     albertel 4783:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4784:     foreach my $part (sort(@parts)) {
                   4785: 	my @datum;
1.745     raeburn  4786: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4787: 	my $name=$part;
1.745     raeburn  4788: 	if (!$display) { $display = $name; }
1.41      ng       4789: 	@datum=($name,$display);
1.244     albertel 4790: 	if ($name=~/^stores_(.*)_awarded/) {
                   4791: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4792: 	}
1.41      ng       4793: 	push(@fields,\@datum);
                   4794:     }
                   4795:     return (@fields);
1.26      albertel 4796: }
                   4797: 
                   4798: sub csvuploadmap_footer {
1.41      ng       4799:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4800:     my $buttontext = &mt('Assign Grades');
1.41      ng       4801:     $request->print(<<ENDPICK);
1.26      albertel 4802: </table>
                   4803: <input type="hidden" name="nfields" value="$i" />
                   4804: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4805: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4806: </form>
                   4807: ENDPICK
                   4808: }
                   4809: 
1.283     albertel 4810: sub checkforfile_js {
1.638     www      4811:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4812:     &js_escape(\$alertmsg);
1.597     wenzelju 4813:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4814:     function checkUpload(formname) {
                   4815: 	if (formname.upfile.value == "") {
1.539     riegler  4816: 	    alert("$alertmsg");
1.86      ng       4817: 	    return false;
                   4818: 	}
                   4819: 	formname.submit();
                   4820:     }
                   4821: CSVFORMJS
1.283     albertel 4822:     return $result;
                   4823: }
                   4824: 
                   4825: sub upcsvScores_form {
1.608     www      4826:     my ($request,$symb) = @_;
1.283     albertel 4827:     if (!$symb) {return '';}
                   4828:     my $result=&checkforfile_js();
1.632     www      4829:     $result.=&Apache::loncommon::start_data_table().
                   4830:              &Apache::loncommon::start_data_table_header_row().
                   4831:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4832:              &Apache::loncommon::end_data_table_header_row().
                   4833:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4834:     my $upload=&mt("Upload Scores");
1.86      ng       4835:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4836:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4837:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4838:     $result.=<<ENDUPFORM;
1.106     albertel 4839: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4840: <input type="hidden" name="symb" value="$symb" />
                   4841: <input type="hidden" name="command" value="csvuploadmap" />
                   4842: $upfile_select
1.589     bisitz   4843: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4844: </form>
                   4845: ENDUPFORM
1.370     www      4846:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4847:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4848:              '</td>'.
                   4849:             &Apache::loncommon::end_data_table_row().
                   4850:             &Apache::loncommon::end_data_table();
1.86      ng       4851:     return $result;
                   4852: }
                   4853: 
                   4854: 
1.26      albertel 4855: sub csvuploadmap {
1.768     raeburn  4856:     my ($request,$symb) = @_;
1.41      ng       4857:     if (!$symb) {return '';}
1.72      ng       4858: 
1.41      ng       4859:     my $datatoken;
1.257     albertel 4860:     if (!$env{'form.datatoken'}) {
1.41      ng       4861: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4862:     } else {
1.742     raeburn  4863: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4864:         if ($datatoken ne '') {
                   4865: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4866:         }
1.26      albertel 4867:     }
1.41      ng       4868:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4869:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4870:     my ($i,$keyfields);
                   4871:     if (@records) {
1.582     raeburn  4872:         my $fieldserror;
                   4873: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4874:         if ($fieldserror) {
                   4875:             $request->print(&navmap_errormsg());
                   4876:             return;
                   4877:         }
1.257     albertel 4878: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4879: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4880: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4881: 							  \@fields);
                   4882: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4883: 	    chop($keyfields);
                   4884: 	} else {
                   4885: 	    unshift(@fields,['none','']);
                   4886: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4887: 							    \@fields);
1.311     banghart 4888:             foreach my $rec (@records) {
                   4889:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4890:                 if (%temp) {
                   4891:                     $keyfields=join(',',sort(keys(%temp)));
                   4892:                     last;
                   4893:                 }
                   4894:             }
1.41      ng       4895: 	}
                   4896:     }
                   4897:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4898: 
1.41      ng       4899:     return '';
1.27      albertel 4900: }
                   4901: 
1.246     albertel 4902: sub csvuploadoptions {
1.608     www      4903:     my ($request,$symb)= @_;
1.632     www      4904:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4905:     $request->print(<<ENDPICK);
                   4906: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4907: <input type="hidden" name="command"    value="csvuploadassign" />
                   4908: <p>
                   4909: <label>
                   4910:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4911:    $overwrite
1.246     albertel 4912: </label>
                   4913: </p>
                   4914: ENDPICK
                   4915:     my %fields=&get_fields();
                   4916:     if (!defined($fields{'domain'})) {
1.257     albertel 4917: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4918: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4919:     }
1.257     albertel 4920:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4921: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4922: 	my $cleankey=$1;
                   4923: 	if ($cleankey eq 'command') { next; }
                   4924: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4925: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4926:     }
                   4927:     # FIXME do a check for any duplicated user ids...
                   4928:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4929:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4930: <hr /></form>'."\n");
1.246     albertel 4931:     return '';
                   4932: }
                   4933: 
                   4934: sub get_fields {
                   4935:     my %fields;
1.257     albertel 4936:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4937:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4938: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4939: 	    if ($env{'form.f'.$i} ne 'none') {
                   4940: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4941: 	    }
                   4942: 	} else {
1.257     albertel 4943: 	    if ($env{'form.f'.$i} ne 'none') {
                   4944: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4945: 	    }
                   4946: 	}
1.27      albertel 4947:     }
1.246     albertel 4948:     return %fields;
                   4949: }
                   4950: 
                   4951: sub csvuploadassign {
1.766     raeburn  4952:     my ($request,$symb) = @_;
1.246     albertel 4953:     if (!$symb) {return '';}
1.345     bowersj2 4954:     my $error_msg = '';
1.742     raeburn  4955:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4956:     if ($datatoken ne '') { 
                   4957:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4958:     }
1.246     albertel 4959:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4960:     my %fields=&get_fields();
1.257     albertel 4961:     my $courseid=$env{'request.course.id'};
1.97      albertel 4962:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4963:     my @notallowed;
1.41      ng       4964:     my @skipped;
1.657     raeburn  4965:     my @warnings;
1.41      ng       4966:     my $countdone=0;
                   4967:     foreach my $grade (@gradedata) {
                   4968: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4969: 	my $domain;
                   4970: 	if ($entries{$fields{'domain'}}) {
                   4971: 	    $domain=$entries{$fields{'domain'}};
                   4972: 	} else {
1.257     albertel 4973: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4974: 	}
1.243     albertel 4975: 	$domain=~s/\s//g;
1.41      ng       4976: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4977: 	$username=~s/\s//g;
1.243     albertel 4978: 	if (!$username) {
                   4979: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4980: 	    $id=~s/\s//g;
1.737     raeburn  4981:             if ($id ne '') {
                   4982: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4983: 	        $username=$ids{$id};
                   4984:             } else {
                   4985:                 if ($entries{$fields{'clicker'}}) {
                   4986:                     my $clicker = $entries{$fields{'clicker'}};
                   4987:                     $clicker=~s/\s//g;
                   4988:                     if ($clicker ne '') {
                   4989:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4990:                         if ($clickers{$clicker} ne '') {  
                   4991:                             my $match = 0;
                   4992:                             my @inclass;
                   4993:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4994:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4995:                                     $username = $poss;
                   4996:                                     push(@inclass,$poss);
                   4997:                                     $match ++;
                   4998:                                     
                   4999:                                 }
                   5000:                             }
                   5001:                             if ($match > 1) {
                   5002:                                 undef($username); 
                   5003:                                 $request->print('<p class="LC_warning">'.
                   5004:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   5005:                                                 $clicker,join(', ',@inclass)).'</p>');
                   5006:                             }
                   5007:                         }
                   5008:                     }
                   5009:                 }
                   5010:             }
1.243     albertel 5011: 	}
1.41      ng       5012: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 5013: 	    my $id=$entries{$fields{'ID'}};
                   5014: 	    $id=~s/\s//g;
1.737     raeburn  5015:             my $clicker = $entries{$fields{'clicker'}};
                   5016:             $clicker=~s/\s//g;
                   5017:             if ($clicker) {
                   5018:                 push(@skipped,"$clicker:$domain");
                   5019: 	    } elsif ($id) {
1.247     albertel 5020: 		push(@skipped,"$id:$domain");
                   5021: 	    } else {
                   5022: 		push(@skipped,"$username:$domain");
                   5023: 	    }
1.41      ng       5024: 	    next;
                   5025: 	}
1.108     albertel 5026: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 5027: 	if (!&canmodify($usec)) {
                   5028: 	    push(@notallowed,"$username:$domain");
                   5029: 	    next;
                   5030: 	}
1.244     albertel 5031: 	my %points;
1.41      ng       5032: 	my %grades;
                   5033: 	foreach my $dest (keys(%fields)) {
1.244     albertel 5034: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   5035: 		$dest eq 'domain') { next; }
                   5036: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   5037: 	    if ($dest=~/stores_(.*)_points/) {
                   5038: 		my $part=$1;
                   5039: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   5040: 					      $symb,$domain,$username);
1.345     bowersj2 5041:                 if ($wgt) {
                   5042:                     $entries{$fields{$dest}}=~s/\s//g;
                   5043:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5044:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5045:                                           : 'correct_by_override';
1.638     www      5046:                     if ($pcr>1) {
1.657     raeburn  5047:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      5048:                     }
1.345     bowersj2 5049:                     $grades{"resource.$part.awarded"}=$pcr;
                   5050:                     $grades{"resource.$part.solved"}=$award;
                   5051:                     $points{$part}=1;
                   5052:                 } else {
                   5053:                     $error_msg = "<br />" .
                   5054:                         &mt("Some point values were assigned"
                   5055:                             ." for problems with a weight "
                   5056:                             ."of zero. These values were "
                   5057:                             ."ignored.");
                   5058:                 }
1.244     albertel 5059: 	    } else {
                   5060: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5061: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5062: 		my $store_key=$dest;
                   5063: 		$store_key=~s/^stores/resource/;
                   5064: 		$store_key=~s/_/\./g;
                   5065: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5066: 	    }
1.41      ng       5067: 	}
1.766     raeburn  5068: 	if (! %grades) {
1.508     www      5069:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5070:         } else {
                   5071: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5072: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5073: 					   $env{'request.course.id'},
                   5074: 					   $domain,$username);
1.508     www      5075: 	   if ($result eq 'ok') {
1.627     www      5076: # Successfully stored
1.508     www      5077: 	      $request->print('.');
1.627     www      5078: # Remove from grading queue
                   5079:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5080:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5081:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5082:                                              $domain,$username);
                   5083:               $countdone++;
                   5084:            } else {
1.508     www      5085: 	      $request->print("<p><span class=\"LC_error\">".
                   5086:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5087:                                   "$username:$domain",$result)."</span></p>");
                   5088: 	   }
                   5089: 	   $request->rflush();
                   5090:         }
1.41      ng       5091:     }
1.570     www      5092:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  5093:     if (@warnings) {
                   5094:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5095:         $request->print(join(', ',@warnings));
                   5096:     }
1.41      ng       5097:     if (@skipped) {
1.571     www      5098: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5099:         $request->print(join(', ',@skipped));
1.106     albertel 5100:     }
                   5101:     if (@notallowed) {
1.571     www      5102: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5103: 	$request->print(join(', ',@notallowed));
1.41      ng       5104:     }
1.106     albertel 5105:     $request->print("<br />\n");
1.345     bowersj2 5106:     return $error_msg;
1.26      albertel 5107: }
1.44      ng       5108: #------------- end of section for handling csv file upload ---------
                   5109: #
                   5110: #-------------------------------------------------------------------
                   5111: #
1.122     ng       5112: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5113: #
                   5114: #--- Select a page/sequence and a student to grade
1.68      ng       5115: sub pickStudentPage {
1.608     www      5116:     my ($request,$symb) = @_;
1.68      ng       5117: 
1.539     riegler  5118:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  5119:     &js_escape(\$alertmsg);
1.597     wenzelju 5120:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5121: 
                   5122: function checkPickOne(formname) {
1.76      ng       5123:     if (radioSelection(formname.student) == null) {
1.539     riegler  5124: 	alert("$alertmsg");
1.68      ng       5125: 	return;
                   5126:     }
1.125     ng       5127:     ptr = pullDownSelection(formname.selectpage);
                   5128:     formname.page.value = formname["page"+ptr].value;
                   5129:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5130:     formname.submit();
                   5131: }
                   5132: 
                   5133: LISTJAVASCRIPT
1.118     ng       5134:     &commonJSfunctions($request);
1.608     www      5135: 
1.257     albertel 5136:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5137:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5138:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  5139:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5140: 
1.398     albertel 5141:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5142: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5143: 
1.80      ng       5144:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5145:     my $map_error;
                   5146:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5147:     if ($map_error) {
                   5148:         $request->print(&navmap_errormsg());
                   5149:         return; 
                   5150:     }
1.137     albertel 5151:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5152: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5153: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   5154: 
                   5155:     # Collection of hidden fields
1.70      ng       5156:     my $ctr=0;
1.68      ng       5157:     foreach (@$titles) {
1.700     bisitz   5158:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5159:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5160:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5161:         $ctr++;
1.68      ng       5162:     }
1.700     bisitz   5163:     $result.='<input type="hidden" name="page" />'."\n".
                   5164:         '<input type="hidden" name="title" />'."\n";
                   5165: 
                   5166:     $result.=&build_section_inputs();
                   5167:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5168:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   5169: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   5170: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 5171: 
1.700     bisitz   5172:     # Show grading options
                   5173:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5174:     my $select = '<select name="selectpage">'."\n";
1.70      ng       5175:     $ctr=0;
                   5176:     foreach (@$titles) {
                   5177: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   5178: 	$select.='<option value="'.$ctr.'"'.
                   5179: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5180: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       5181: 	$ctr++;
                   5182:     }
1.700     bisitz   5183:     $select.= '</select>';
1.68      ng       5184: 
1.700     bisitz   5185:     $result.=
                   5186:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5187:        .$select
                   5188:        .&Apache::lonhtmlcommon::row_closure();
                   5189: 
                   5190:     $result.=
                   5191:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5192:        .'<label><input type="radio" name="vProb" value="no"'
                   5193:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5194:        .'<label><input type="radio" name="vProb" value="yes" />'
                   5195:            .&mt('yes').'</label>'."\n"
                   5196:        .&Apache::lonhtmlcommon::row_closure();
                   5197: 
                   5198:     $result.=
                   5199:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5200:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5201:            .&mt('none').' </label>'."\n"
                   5202:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5203:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5204:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5205:            .&mt('all submissions with details').' </label>'
                   5206:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 5207:     
1.700     bisitz   5208:     $result.=
                   5209:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5210:        .'<input type="text" name="CODE" value="" />'
                   5211:        .&Apache::lonhtmlcommon::row_closure(1)
                   5212:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5213: 
1.700     bisitz   5214:     # Show list of students to select for grading
                   5215:     $result.='<br /><input type="button" '.
1.589     bisitz   5216:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5217: 
1.68      ng       5218:     $request->print($result);
                   5219: 
1.485     albertel 5220:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5221: 	&Apache::loncommon::start_data_table().
                   5222: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5223: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5224: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5225: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5226: 	'<th>'.&nameUserString('header').'</th>'.
                   5227: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5228:  
1.761     raeburn  5229:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5230:     my $ptr = 1;
1.294     albertel 5231:     foreach my $student (sort 
                   5232: 			 {
                   5233: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5234: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5235: 			     }
                   5236: 			     return $a cmp $b;
                   5237: 			 } (keys(%$fullname))) {
1.68      ng       5238: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5239: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5240:                                   : '</td>');
1.126     ng       5241: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5242: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5243: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5244: 	$studentTable.=
                   5245: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5246:                          : '');
1.68      ng       5247: 	$ptr++;
                   5248:     }
1.484     albertel 5249:     if ($ptr%2 == 0) {
                   5250: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5251: 	    &Apache::loncommon::end_data_table_row();
                   5252:     }
                   5253:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5254:     $studentTable.='<input type="button" '.
1.589     bisitz   5255:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5256: 
                   5257:     $request->print($studentTable);
                   5258: 
                   5259:     return '';
                   5260: }
                   5261: 
                   5262: sub getSymbMap {
1.582     raeburn  5263:     my ($map_error) = @_;
1.132     bowersj2 5264:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5265:     unless (ref($navmap)) {
                   5266:         if (ref($map_error)) {
                   5267:             $$map_error = 'navmap';
                   5268:         }
                   5269:         return;
                   5270:     }
1.68      ng       5271:     my %symbx = ();
                   5272:     my @titles = ();
1.117     bowersj2 5273:     my $minder = 0;
                   5274: 
                   5275:     # Gather every sequence that has problems.
1.240     albertel 5276:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5277: 					       1,0,1);
1.117     bowersj2 5278:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5279: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5280: 	    my $title = $minder.'.'.
                   5281: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5282: 	    push(@titles, $title); # minder in case two titles are identical
                   5283: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5284: 	    $minder++;
1.241     albertel 5285: 	}
1.68      ng       5286:     }
                   5287:     return \@titles,\%symbx;
                   5288: }
                   5289: 
1.72      ng       5290: #
                   5291: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5292: sub displayPage {
1.608     www      5293:     my ($request,$symb) = @_;
1.257     albertel 5294:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5295:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5296:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5297:     my $pageTitle = $env{'form.page'};
1.103     albertel 5298:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5299:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5300:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5301: 
                   5302:     #need to make sure we have the correct data for later EXT calls, 
                   5303:     #thus invalidate the cache
                   5304:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5305:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5306:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5307:     &Apache::lonnet::clear_EXT_cache_status();
                   5308: 
1.103     albertel 5309:     if (!&canview($usec)) {
1.712     bisitz   5310:         $request->print(
                   5311:             '<span class="LC_warning">'.
                   5312:             &mt('Unable to view requested student. ([_1])',
                   5313:                     $env{'form.student'}).
                   5314:             '</span>');
                   5315:         return;
1.103     albertel 5316:     }
1.398     albertel 5317:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5318:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5319: 	'</h3>'."\n";
1.500     albertel 5320:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5321:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5322: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5323:     } else {
                   5324: 	delete($env{'form.CODE'});
                   5325:     }
1.71      ng       5326:     &sub_page_js($request);
                   5327:     $request->print($result);
                   5328: 
1.132     bowersj2 5329:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5330:     unless (ref($navmap)) {
                   5331:         $request->print(&navmap_errormsg());
                   5332:         return;
                   5333:     }
1.257     albertel 5334:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5335:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5336:     if (!$map) {
1.485     albertel 5337: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5338: 	return; 
                   5339:     }
1.68      ng       5340:     my $iterator = $navmap->getIterator($map->map_start(),
                   5341: 					$map->map_finish());
                   5342: 
1.71      ng       5343:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5344: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5345: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5346: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5347: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5348: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5349: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5350: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5351: 
1.382     albertel 5352:     if (defined($env{'form.CODE'})) {
                   5353: 	$studentTable.=
                   5354: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5355:     }
1.381     albertel 5356:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5357: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5358: 
1.594     bisitz   5359:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5360:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5361:         '</span>'."\n".
1.484     albertel 5362: 	&Apache::loncommon::start_data_table().
                   5363: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5364: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5365: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5366: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5367: 
1.329     albertel 5368:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5369:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5370:     $iterator->next(); # skip the first BEGIN_MAP
                   5371:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5372:     while ($depth > 0) {
1.68      ng       5373:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5374:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5375: 
1.745     raeburn  5376:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5377: 	    my $parts = $curRes->parts();
1.68      ng       5378:             my $title = $curRes->compTitle();
1.71      ng       5379: 	    my $symbx = $curRes->symb();
1.746     raeburn  5380:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5381: 	    $studentTable.=
                   5382: 		&Apache::loncommon::start_data_table_row().
                   5383: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5384: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5385: 		                        : '<br />('.&mt('[_1]parts',
                   5386: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5387: 		 ).
                   5388: 		 '</td>';
1.71      ng       5389: 	    $studentTable.='<td valign="top">';
1.382     albertel 5390: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5391:             if ($is_tool) {
                   5392:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5393:             } else {
1.745     raeburn  5394: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5395: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5396: 					         undef,'both',\%form);
                   5397: 	        } else {
                   5398: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5399: 		    $companswer =~ s|<form(.*?)>||g;
                   5400: 		    $companswer =~ s|</form>||g;
                   5401: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5402: #		        $companswer =~ s/$1/ /ms;
                   5403: #		        $request->print('match='.$1."<br />\n");
                   5404: #		    }
                   5405: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5406: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5407: 		}
1.71      ng       5408: 	    }
                   5409: 
1.257     albertel 5410: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5411: 
1.257     albertel 5412: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5413: 		if ($record{'version'} eq '') {
1.745     raeburn  5414:                     my $msg = &mt('No recorded submission for this problem.');
                   5415:                     if ($is_tool) {
                   5416:                         $msg = &mt('No recorded transactions for this external tool');
                   5417:                     }
                   5418: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5419: 		} else {
1.116     ng       5420: 		    my %responseType = ();
                   5421: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5422: 			my @responseIds =$curRes->responseIds($partid);
                   5423: 			my @responseType =$curRes->responseType($partid);
                   5424: 			my %responseIds;
                   5425: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5426: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5427: 			}
                   5428: 			$responseType{$partid} = \%responseIds;
1.116     ng       5429: 		    }
1.148     albertel 5430: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5431: 		}
1.257     albertel 5432: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5433: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5434:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5435: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5436: 									$env{'request.course.id'},
1.726     raeburn  5437: 									'','.submission',undef,
                   5438:                                                                         $usec,$identifier);
1.71      ng       5439:  
                   5440: 	    }
1.103     albertel 5441: 	    if (&canmodify($usec)) {
1.585     bisitz   5442:             $studentTable.=&gradeBox_start();
1.103     albertel 5443: 		foreach my $partid (@{$parts}) {
                   5444: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5445: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5446: 		    $question++;
                   5447: 		}
1.585     bisitz   5448:             $studentTable.=&gradeBox_end();
1.196     albertel 5449: 		$prob++;
1.71      ng       5450: 	    }
                   5451: 	    $studentTable.='</td></tr>';
1.68      ng       5452: 
1.103     albertel 5453: 	}
1.68      ng       5454:         $curRes = $iterator->next();
                   5455:     }
1.780     raeburn  5456:     my $disabled;
                   5457:     unless (&canmodify($usec)) {
                   5458:         $disabled = ' disabled="disabled"';
                   5459:     }
1.68      ng       5460: 
1.589     bisitz   5461:     $studentTable.=
                   5462:         '</table>'."\n".
1.780     raeburn  5463:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5464:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5465:         '</form>'."\n";
1.71      ng       5466:     $request->print($studentTable);
                   5467: 
                   5468:     return '';
1.119     ng       5469: }
                   5470: 
                   5471: sub displaySubByDates {
1.148     albertel 5472:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5473:     my $isCODE=0;
1.335     albertel 5474:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5475:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5476:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5477:     my $studentTable=&Apache::loncommon::start_data_table().
                   5478: 	&Apache::loncommon::start_data_table_header_row().
                   5479: 	'<th>'.&mt('Date/Time').'</th>'.
                   5480: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5481:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5482: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5483: 	'<th>'.&mt('Status').'</th>'.
                   5484: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5485:     my ($version);
                   5486:     my %mark;
1.148     albertel 5487:     my %orders;
1.119     ng       5488:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5489:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5490:         if ($is_tool) {
                   5491:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5492:         } else {
                   5493:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5494:         }
1.147     albertel 5495:     }
1.335     albertel 5496: 
                   5497:     my $interaction;
1.525     raeburn  5498:     my $no_increment = 1;
1.735     raeburn  5499:     my (%lastrndseed,%lasttype);
1.119     ng       5500:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5501: 	my $timestamp = 
                   5502: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5503: 	if (exists($$record{$version.':resource.0.version'})) {
                   5504: 	    $interaction = $$record{$version.':resource.0.version'};
                   5505: 	}
1.671     raeburn  5506:         if ($isTask && $env{'form.previousversion'}) {
                   5507:             next unless ($interaction == $env{'form.previousversion'});
                   5508:         }
1.335     albertel 5509: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5510: 		             : "$version:resource");
1.467     albertel 5511: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5512: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5513: 	if ($isCODE) {
                   5514: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5515: 	}
1.671     raeburn  5516:         if ($isTask) {
                   5517:             $studentTable.='<td>'.$interaction.'</td>';
                   5518:         }
1.119     ng       5519: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5520: 	my @displaySub = ();
                   5521: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5522:             my ($hidden,$type);
                   5523:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5524:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5525:                 $hidden = 1;
                   5526:             }
1.749     raeburn  5527:             my @matchKey;
                   5528:             if ($isTask) {
1.769     raeburn  5529:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  5530:             } elsif ($is_tool) {
1.769     raeburn  5531:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  5532:             } else {
1.769     raeburn  5533:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  5534:             }
1.122     ng       5535: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5536: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5537: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5538: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5539: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5540:                     if ($is_tool) {
                   5541:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5542:                     } else {
1.749     raeburn  5543: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5544: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5545:                         $displaySub[0].='<span class="LC_nobreak">';
                   5546:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5547:                                        .' <span class="LC_internal_info">'
                   5548:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5549:                                        .'</span>'
                   5550:                                        .' <b>';
                   5551:                         if ($hidden) {
                   5552:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5553:                         } else {
                   5554:                             my ($trial,$rndseed,$newvariation);
                   5555:                             if ($type eq 'randomizetry') {
                   5556:                                 $trial = $$record{"$where.$partid.tries"};
                   5557:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5558:                             }
                   5559: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5560: 			        $displaySub[0].=&mt('Trial not counted');
                   5561: 		            } else {
                   5562: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5563: 					        $$record{"$where.$partid.tries"});
                   5564:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5565:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5566:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5567:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5568:                                     }
1.640     raeburn  5569:                                 }
1.749     raeburn  5570:                                 $lastrndseed{$partid} = $rndseed;
                   5571:                                 $lasttype{$partid} = $type;
                   5572: 		            }
                   5573: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5574:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5575: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5576: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5577: 			        $orders{$partid}->{$responseId}=
                   5578: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5579:                                                $no_increment,$type,$trial,$rndseed);
                   5580: 		            }
                   5581: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5582: 		            $displaySub[0].='&nbsp; '.
                   5583: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5584:                         }
1.596     raeburn  5585:                     }
1.147     albertel 5586: 		}
                   5587: 	    }
1.335     albertel 5588: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5589: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5590: 				    $$record{"$where.$partid.checkedin"},
                   5591: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5592: 					'<br />';
1.335     albertel 5593: 	    }
                   5594: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5595: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5596: 		    lc($$record{"$where.$partid.award"}).' '.
                   5597: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5598: 		    '<br />';
1.749     raeburn  5599: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5600: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5601: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5602: 		}
1.147     albertel 5603: 	    }
1.335     albertel 5604: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5605: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5606: 		unless ($is_tool) {
                   5607: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5608: 		}
1.335     albertel 5609: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5610: 		$displaySub[2].=
1.749     raeburn  5611: 		    $$record{"$version:resource.$partid.regrader"};
                   5612:                 unless ($is_tool) {
                   5613: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5614:                 }
1.147     albertel 5615: 	    }
                   5616: 	}
                   5617: 	# needed because old essay regrader has not parts info
                   5618: 	if (exists $$record{"$version:resource.regrader"}) {
                   5619: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5620: 	}
                   5621: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5622: 	if ($displaySub[2]) {
1.467     albertel 5623: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5624: 	}
1.467     albertel 5625: 	$studentTable.='&nbsp;</td>'.
                   5626: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5627:     }
1.467     albertel 5628:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5629:     return $studentTable;
1.71      ng       5630: }
                   5631: 
                   5632: sub updateGradeByPage {
1.608     www      5633:     my ($request,$symb) = @_;
1.71      ng       5634: 
1.257     albertel 5635:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5636:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5637:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5638:     my $pageTitle = $env{'form.page'};
1.103     albertel 5639:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5640:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5641:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5642:     if (!&canmodify($usec)) {
1.526     raeburn  5643: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5644: 	return;
                   5645:     }
1.398     albertel 5646:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5647:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5648: 	'</h3>'."\n";
1.70      ng       5649: 
1.68      ng       5650:     $request->print($result);
                   5651: 
1.582     raeburn  5652: 
1.132     bowersj2 5653:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5654:     unless (ref($navmap)) {
                   5655:         $request->print(&navmap_errormsg());
                   5656:         return;
                   5657:     }
1.257     albertel 5658:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5659:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5660:     if (!$map) {
1.527     raeburn  5661: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5662: 	return; 
                   5663:     }
1.71      ng       5664:     my $iterator = $navmap->getIterator($map->map_start(),
                   5665: 					$map->map_finish());
1.70      ng       5666: 
1.484     albertel 5667:     my $studentTable=
                   5668: 	&Apache::loncommon::start_data_table().
                   5669: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5670: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5671: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5672: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5673: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5674: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5675: 
                   5676:     $iterator->next(); # skip the first BEGIN_MAP
                   5677:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5678:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5679:     while ($depth > 0) {
1.71      ng       5680:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5681:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5682: 
1.385     albertel 5683:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5684: 	    my $parts = $curRes->parts();
1.71      ng       5685:             my $title = $curRes->compTitle();
                   5686: 	    my $symbx = $curRes->symb();
1.484     albertel 5687: 	    $studentTable.=
                   5688: 		&Apache::loncommon::start_data_table_row().
                   5689: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5690: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5691:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5692: 		.')').'</td>';
1.71      ng       5693: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5694: 
                   5695: 	    my %newrecord=();
                   5696: 	    my @displayPts=();
1.269     raeburn  5697:             my %aggregate = ();
                   5698:             my $aggregateflag = 0;
1.726     raeburn  5699:             if ($env{'form.HIDE'.$prob}) {
                   5700:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5701:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5702:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5703:                 $hideflag += $numchgs;
                   5704:             }
1.71      ng       5705: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5706: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5707: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5708: 
1.257     albertel 5709: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5710: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5711: 		my $partial = $newpts/$wgt;
                   5712: 		my $score;
                   5713: 		if ($partial > 0) {
                   5714: 		    $score = 'correct_by_override';
1.125     ng       5715: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5716: 		    $score = 'incorrect_by_override';
                   5717: 		}
1.257     albertel 5718: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5719: 		if ($dropMenu eq 'excused') {
1.71      ng       5720: 		    $partial = '';
                   5721: 		    $score = 'excused';
1.125     ng       5722: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5723: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5724: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5725: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5726: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5727: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5728: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5729: 		    $changeflag++;
                   5730: 		    $newpts = '';
1.269     raeburn  5731:                     
                   5732:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5733:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5734:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5735:                     if ($aggtries > 0) {
                   5736:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5737:                         $aggregateflag = 1;
                   5738:                     }
1.71      ng       5739: 		}
1.324     albertel 5740: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5741: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5742: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5743: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5744: 		    '&nbsp;<br />';
1.526     raeburn  5745: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5746: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5747: 		    '&nbsp;<br />';
1.71      ng       5748: 		$question++;
1.380     albertel 5749: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5750: 
1.71      ng       5751: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5752: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5753: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5754: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5755: 
                   5756: 		$changeflag++;
                   5757: 	    }
                   5758: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5759: 		my %record = 
                   5760: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5761: 					     $udom,$uname);
                   5762: 
                   5763: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5764: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5765: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5766: 		    $newrecord{'resource.CODE'} = '';
                   5767: 		}
1.257     albertel 5768: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5769: 					$udom,$uname);
1.382     albertel 5770: 		%record = &Apache::lonnet::restore($symbx,
                   5771: 						   $env{'request.course.id'},
                   5772: 						   $udom,$uname);
1.380     albertel 5773: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5774: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5775: 	    }
1.380     albertel 5776: 	    
1.269     raeburn  5777:             if ($aggregateflag) {
                   5778:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5779:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5780:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5781:             }
1.125     ng       5782: 
1.71      ng       5783: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5784: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5785: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5786: 
1.196     albertel 5787: 	    $prob++;
1.68      ng       5788: 	}
1.71      ng       5789:         $curRes = $iterator->next();
1.68      ng       5790:     }
1.98      albertel 5791: 
1.484     albertel 5792:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5793:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5794: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5795: 		  $changeflag).'<br />');
                   5796:     my $hidemsg=($hideflag == 0 ? '' :
                   5797:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5798:                      $hideflag).'<br />');
                   5799:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5800: 
1.70      ng       5801:     return '';
                   5802: }
                   5803: 
1.72      ng       5804: #-------- end of section for handling grading by page/sequence ---------
                   5805: #
                   5806: #-------------------------------------------------------------------
                   5807: 
1.581     www      5808: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5809: #
                   5810: #------ start of section for handling grading by page/sequence ---------
                   5811: 
1.423     albertel 5812: =pod
                   5813: 
                   5814: =head1 Bubble sheet grading routines
                   5815: 
1.424     albertel 5816:   For this documentation:
                   5817: 
                   5818:    'scanline' refers to the full line of characters
                   5819:    from the file that we are parsing that represents one entire sheet
                   5820: 
                   5821:    'bubble line' refers to the data
1.659     raeburn  5822:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5823: 
                   5824: 
1.659     raeburn  5825: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5826: into a course. When a user wants to grade, they select a
1.659     raeburn  5827: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5828: one of the predefined configurations for what each scanline looks
                   5829: like.
                   5830: 
                   5831: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5832: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5833: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5834: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5835: invalid student/employee ID
1.424     albertel 5836: 
                   5837: If the CODE option is used that determines the randomization of the
1.556     weissno  5838: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5839: username:domain.
                   5840: 
                   5841: During the validation phase the instructor can choose to skip scanlines. 
                   5842: 
1.659     raeburn  5843: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5844: 
                   5845:   scantron_original_filename (unmodified original file)
                   5846:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5847:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5848: 
                   5849: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5850: correction information that isn't representable in the bubblesheet
1.424     albertel 5851: file (see &scantron_getfile() for more information)
                   5852: 
                   5853: After all scanlines are either valid, marked as valid or skipped, then
                   5854: foreach line foreach problem in the picked sequence, an ssi request is
                   5855: made that simulates a user submitting their selected letter(s) against
                   5856: the homework problem.
1.423     albertel 5857: 
                   5858: =over 4
                   5859: 
                   5860: 
                   5861: 
                   5862: =item defaultFormData
                   5863: 
                   5864:   Returns html hidden inputs used to hold context/default values.
                   5865: 
                   5866:  Arguments:
                   5867:   $symb - $symb of the current resource 
                   5868: 
                   5869: =cut
1.422     foxr     5870: 
1.81      albertel 5871: sub defaultFormData {
1.324     albertel 5872:     my ($symb)=@_;
1.766     raeburn  5873:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5874: }
                   5875: 
1.447     foxr     5876: 
1.423     albertel 5877: =pod 
                   5878: 
                   5879: =item getSequenceDropDown
                   5880: 
                   5881:    Return html dropdown of possible sequences to grade
                   5882:  
                   5883:  Arguments:
1.582     raeburn  5884:    $symb - $symb of the current resource
                   5885:    $map_error - ref to scalar which will container error if
                   5886:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5887: 
                   5888: =cut
1.422     foxr     5889: 
1.75      albertel 5890: sub getSequenceDropDown {
1.582     raeburn  5891:     my ($symb,$map_error)=@_;
1.75      albertel 5892:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5893:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5894:     if (ref($map_error)) {
                   5895:         return if ($$map_error);
                   5896:     }
1.137     albertel 5897:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5898:     my $ctr=0;
                   5899:     foreach (@$titles) {
                   5900: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5901: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5902: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5903: 	    '>'.$showtitle.'</option>'."\n";
                   5904: 	$ctr++;
                   5905:     }
                   5906:     $result.= '</select>';
                   5907:     return $result;
                   5908: }
                   5909: 
1.495     albertel 5910: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5911:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5912: 
                   5913: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5914: 
1.509     raeburn  5915: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5916:                                    # matchresponse or rankresponse, where 
                   5917:                                    # an individual response can have multiple 
                   5918:                                    # lines
1.503     raeburn  5919: 
                   5920: my %responsetype_per_response;     # responsetype for each response
                   5921: 
1.691     raeburn  5922: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5923:                                    # numbered response. Needed when randomorder
                   5924:                                    # or randompick are in use. Key is ID, value 
                   5925:                                    # is response number.
                   5926: 
1.495     albertel 5927: # Save and restore the bubble lines array to the form env.
                   5928: 
                   5929: 
                   5930: sub save_bubble_lines {
                   5931:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5932: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5933: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5934: 	    $first_bubble_line{$line};
1.503     raeburn  5935:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5936:             $subdivided_bubble_lines{$line};
                   5937:         $env{"form.scantron.responsetype.$line"} =
                   5938:             $responsetype_per_response{$line};
1.495     albertel 5939:     }
1.691     raeburn  5940:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5941:         my $line = $masterseq_id_responsenum{$resid};
                   5942:         $env{"form.scantron.residpart.$line"} = $resid;
                   5943:     }
1.495     albertel 5944: }
                   5945: 
                   5946: 
                   5947: sub restore_bubble_lines {
                   5948:     my $line = 0;
                   5949:     %bubble_lines_per_response = ();
1.691     raeburn  5950:     %masterseq_id_responsenum = ();
1.495     albertel 5951:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5952: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5953: 	$bubble_lines_per_response{$line} = $value;
                   5954: 	$first_bubble_line{$line}  =
                   5955: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5956:         $subdivided_bubble_lines{$line} =
                   5957:             $env{"form.scantron.sub_bubblelines.$line"};
                   5958:         $responsetype_per_response{$line} =
                   5959:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5960:         my $id = $env{"form.scantron.residpart.$line"};
                   5961:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5962: 	$line++;
                   5963:     }
                   5964: }
                   5965: 
1.423     albertel 5966: =pod 
                   5967: 
                   5968: =item scantron_filenames
                   5969: 
                   5970:    Returns a list of the scantron files in the current course 
                   5971: 
                   5972: =cut
1.422     foxr     5973: 
1.202     albertel 5974: sub scantron_filenames {
1.257     albertel 5975:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5976:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5977:     my $getpropath = 1;
1.662     raeburn  5978:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5979:                                                         $cname,$getpropath);
1.202     albertel 5980:     my @possiblenames;
1.662     raeburn  5981:     if (ref($dirlist) eq 'ARRAY') {
                   5982:         foreach my $filename (sort(@{$dirlist})) {
                   5983: 	    ($filename)=split(/&/,$filename);
                   5984: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5985: 	    $filename=~s/^scantron_orig_//;
                   5986: 	    push(@possiblenames,$filename);
                   5987:         }
1.202     albertel 5988:     }
                   5989:     return @possiblenames;
                   5990: }
                   5991: 
1.423     albertel 5992: =pod 
                   5993: 
                   5994: =item scantron_uploads
                   5995: 
                   5996:    Returns  html drop-down list of scantron files in current course.
                   5997: 
                   5998:  Arguments:
                   5999:    $file2grade - filename to set as selected in the dropdown
                   6000: 
                   6001: =cut
1.422     foxr     6002: 
1.202     albertel 6003: sub scantron_uploads {
1.209     ng       6004:     my ($file2grade) = @_;
1.202     albertel 6005:     my $result=	'<select name="scantron_selectfile">';
                   6006:     $result.="<option></option>";
                   6007:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 6008: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 6009:     }
                   6010:     $result.="</select>";
                   6011:     return $result;
                   6012: }
                   6013: 
1.423     albertel 6014: =pod 
                   6015: 
                   6016: =item scantron_scantab
                   6017: 
                   6018:   Returns html drop down of the scantron formats in the scantronformat.tab
                   6019:   file.
                   6020: 
                   6021: =cut
1.422     foxr     6022: 
1.82      albertel 6023: sub scantron_scantab {
                   6024:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 6025:     $result.='<option></option>'."\n";
1.754     raeburn  6026:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  6027:     if (@lines > 0) {
                   6028:         foreach my $line (@lines) {
                   6029:             next if (($line =~ /^\#/) || ($line eq ''));
                   6030: 	    my ($name,$descrip)=split(/:/,$line);
                   6031: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   6032:         }
1.82      albertel 6033:     }
                   6034:     $result.='</select>'."\n";
1.518     raeburn  6035:     return $result;
                   6036: }
                   6037: 
1.423     albertel 6038: =pod 
                   6039: 
                   6040: =item scantron_CODElist
                   6041: 
                   6042:   Returns html drop down of the saved CODE lists from current course,
                   6043:   generated from earlier printings.
                   6044: 
                   6045: =cut
1.422     foxr     6046: 
1.186     albertel 6047: sub scantron_CODElist {
1.257     albertel 6048:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6049:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 6050:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   6051:     my $namechoice='<option></option>';
1.225     albertel 6052:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 6053: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 6054: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 6055: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   6056:     }
                   6057:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6058:     return $namechoice;
                   6059: }
                   6060: 
1.423     albertel 6061: =pod 
                   6062: 
                   6063: =item scantron_CODEunique
                   6064: 
                   6065:   Returns the html for "Each CODE to be used once" radio.
                   6066: 
                   6067: =cut
1.422     foxr     6068: 
1.186     albertel 6069: sub scantron_CODEunique {
1.532     bisitz   6070:     my $result='<span class="LC_nobreak">
1.272     albertel 6071:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6072:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6073:                 </span>
1.532     bisitz   6074:                 <span class="LC_nobreak">
1.272     albertel 6075:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6076:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6077:                 </span>';
1.186     albertel 6078:     return $result;
                   6079: }
1.423     albertel 6080: 
                   6081: =pod 
                   6082: 
                   6083: =item scantron_selectphase
                   6084: 
1.659     raeburn  6085:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6086:   Allows for - starting a grading run.
1.424     albertel 6087:              - downloading existing scan data (original, corrected
1.423     albertel 6088:                                                 or skipped info)
                   6089: 
                   6090:              - uploading new scan data
                   6091: 
                   6092:  Arguments:
                   6093:   $r          - The Apache request object
                   6094:   $file2grade - name of the file that contain the scanned data to score
                   6095: 
                   6096: =cut
1.186     albertel 6097: 
1.75      albertel 6098: sub scantron_selectphase {
1.608     www      6099:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6100:     if (!$symb) {return '';}
1.582     raeburn  6101:     my $map_error;
                   6102:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6103:     if ($map_error) {
                   6104:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6105:         return;
                   6106:     }
1.324     albertel 6107:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6108:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6109:     my $format_selector=&scantron_scantab();
1.186     albertel 6110:     my $CODE_selector=&scantron_CODElist();
                   6111:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6112:     my $result;
1.422     foxr     6113: 
1.513     foxr     6114:     $ssi_error = 0;
                   6115: 
1.770     raeburn  6116:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 6117: 
                   6118: 	# Chunk of form to prompt for a scantron file upload.
                   6119: 
                   6120:         $r->print('
1.754     raeburn  6121:     <br />');
1.606     wenzelju 6122:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6123:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  6124:     my $csec= $env{'request.course.sec'};
1.736     damieng  6125:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6126:     &js_escape(\$alertmsg);
1.754     raeburn  6127:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 6128:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   6129:     function checkUpload(formname) {
                   6130: 	if (formname.upfile.value == "") {
1.736     damieng  6131: 	    alert("'.$alertmsg.'");
1.606     wenzelju 6132: 	    return false;
                   6133: 	}
                   6134: 	formname.submit();
1.756     raeburn  6135:     }'."\n".$formatjs));
1.606     wenzelju 6136:     $r->print('
                   6137:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6138:                 '.$default_form_data.'
                   6139:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  6140:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 6141:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6142:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  6143:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6144:               '.&Apache::loncommon::start_data_table_header_row().'
                   6145:                 <th>
                   6146:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6147:                 </th>
                   6148:               '.&Apache::loncommon::end_data_table_header_row().'
                   6149:               '.&Apache::loncommon::start_data_table_row().'
                   6150:             <td>
                   6151:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6152:     if ($formatoptions) {
                   6153:         $r->print('</td>
                   6154:                  '.&Apache::loncommon::end_data_table_row().'
                   6155:                  '.&Apache::loncommon::start_data_table_row().'
                   6156:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6157:                  </td>
                   6158:                  '.&Apache::loncommon::end_data_table_row().'
                   6159:                  '.&Apache::loncommon::start_data_table_row().'
                   6160:                  <td>'
                   6161:         );
                   6162:     } else {
                   6163:         $r->print(' <br />');
                   6164:     }
                   6165:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6166:               </td>
                   6167:              '.&Apache::loncommon::end_data_table_row().'
                   6168:              '.&Apache::loncommon::end_data_table().'
                   6169:              </form>'
                   6170:     );
1.606     wenzelju 6171: 
                   6172:     }
                   6173: 
1.422     foxr     6174:     # Chunk of form to prompt for a file to grade and how:
                   6175: 
1.489     albertel 6176:     $result.= '
                   6177:     <br />
                   6178:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6179:     <input type="hidden" name="command" value="scantron_warning" />
                   6180:     '.$default_form_data.'
                   6181:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6182:        '.&Apache::loncommon::start_data_table_header_row().'
                   6183:             <th colspan="2">
1.492     albertel 6184:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
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('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6189:        '.&Apache::loncommon::end_data_table_row().'
                   6190:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6191:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6192:        '.&Apache::loncommon::end_data_table_row().'
                   6193:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6194:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6195:        '.&Apache::loncommon::end_data_table_row().'
                   6196:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6197:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6198:        '.&Apache::loncommon::end_data_table_row().'
                   6199:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6200:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6201:        '.&Apache::loncommon::end_data_table_row().'
                   6202:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6203: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6204:             <td>
1.492     albertel 6205: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6206:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6207:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6208: 	    </td>
1.489     albertel 6209:        '.&Apache::loncommon::end_data_table_row().'
                   6210:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6211:             <td colspan="2">
1.572     www      6212:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6213:             </td>
1.489     albertel 6214:        '.&Apache::loncommon::end_data_table_row().'
                   6215:     '.&Apache::loncommon::end_data_table().'
                   6216:     </form>
                   6217: ';
1.162     albertel 6218:    
                   6219:     $r->print($result);
                   6220: 
1.422     foxr     6221:     # Chunk of the form that prompts to view a scoring office file,
                   6222:     # corrected file, skipped records in a file.
                   6223: 
1.489     albertel 6224:     $r->print('
                   6225:    <br />
                   6226:    <form action="/adm/grades" name="scantron_download">
                   6227:      '.$default_form_data.'
                   6228:      <input type="hidden" name="command" value="scantron_download" />
                   6229:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6230:        '.&Apache::loncommon::start_data_table_header_row().'
                   6231:               <th>
1.492     albertel 6232:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6233:               </th>
                   6234:        '.&Apache::loncommon::end_data_table_header_row().'
                   6235:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6236:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6237:                 <br />
1.492     albertel 6238:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6239:        '.&Apache::loncommon::end_data_table_row().'
                   6240:      '.&Apache::loncommon::end_data_table().'
                   6241:    </form>
                   6242:    <br />
                   6243: ');
1.162     albertel 6244: 
1.457     banghart 6245:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6246: 
1.694     bisitz   6247:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6248:              $default_form_data."\n".
                   6249:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6250:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6251:              '<th colspan="2">
1.572     www      6252:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6253:              '</th>'."\n".
                   6254:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6255:               &Apache::loncommon::start_data_table_row()."\n".
                   6256:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6257:               '<td> '.$sequence_selector.' </td>'.
                   6258:               &Apache::loncommon::end_data_table_row()."\n".
                   6259:               &Apache::loncommon::start_data_table_row()."\n".
                   6260:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6261:               '<td> '.$file_selector.' </td>'."\n".
                   6262:               &Apache::loncommon::end_data_table_row()."\n".
                   6263:               &Apache::loncommon::start_data_table_row()."\n".
                   6264:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6265:               '<td> '.$format_selector.' </td>'."\n".
                   6266:               &Apache::loncommon::end_data_table_row()."\n".
                   6267:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6268:               '<td> '.&mt('Options').' </td>'."\n".
                   6269:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6270:               &Apache::loncommon::end_data_table_row()."\n".
                   6271:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6272:               '<td colspan="2">'."\n".
                   6273:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6274:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6275:               '</td>'."\n".
                   6276:               &Apache::loncommon::end_data_table_row()."\n".
                   6277:               &Apache::loncommon::end_data_table()."\n".
                   6278:               '</form><br />');
                   6279:     return;
1.75      albertel 6280: }
                   6281: 
1.423     albertel 6282: =pod 
                   6283: 
                   6284: =item username_to_idmap
                   6285: 
1.556     weissno  6286:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6287:     student username:domain. If a single ID occurs for more than one student,
                   6288:     the status of the student is checked, and if Active, the value in the hash
                   6289:     will be set to the Active student.
1.423     albertel 6290: 
                   6291:   Arguments:
                   6292: 
                   6293:     $classlist - reference to the class list hash. This is a hash
                   6294:                  keyed by student name:domain  whose elements are references
1.424     albertel 6295:                  to arrays containing various chunks of information
1.423     albertel 6296:                  about the student. (See loncoursedata for more info).
                   6297: 
                   6298:   Returns
                   6299:     %idmap - the constructed hash
                   6300: 
                   6301: =cut
                   6302: 
1.82      albertel 6303: sub username_to_idmap {
                   6304:     my ($classlist)= @_;
                   6305:     my %idmap;
                   6306:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6307:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6308:         unless ($id eq '') {
                   6309:             if (!exists($idmap{$id})) {
                   6310:                 $idmap{$id} = $student;
                   6311:             } else {
                   6312:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6313:                 if ($status eq 'Active') {
                   6314:                     $idmap{$id} = $student;
                   6315:                 }
                   6316:             }
                   6317:         }
1.82      albertel 6318:     }
                   6319:     return %idmap;
                   6320: }
1.423     albertel 6321: 
                   6322: =pod
                   6323: 
1.424     albertel 6324: =item scantron_fixup_scanline
1.423     albertel 6325: 
                   6326:    Process a requested correction to a scanline.
                   6327: 
                   6328:   Arguments:
1.754     raeburn  6329:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6330:     $scan_data         - hash of correction information 
                   6331:                           (see &scantron_getfile())
                   6332:     $line              - existing scanline
                   6333:     $whichline         - line number of the passed in scanline
                   6334:     $field             - type of change to process 
                   6335:                          (either 
1.573     bisitz   6336:                           'ID'     -> correct the student/employee ID
1.423     albertel 6337:                           'CODE'   -> correct the CODE
                   6338:                           'answer' -> fixup the submitted answers)
                   6339:     
                   6340:    $args               - hash of additional info,
                   6341:                           - 'ID' 
                   6342:                                'newid' -> studentID to use in replacement
1.424     albertel 6343:                                           of existing one
1.423     albertel 6344:                           - 'CODE' 
                   6345:                                'CODE_ignore_dup' - set to true if duplicates
                   6346:                                                    should be ignored.
                   6347: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6348:                                         if the existing unfound code should
1.423     albertel 6349:                                         be used as is
                   6350:                           - 'answer'
                   6351:                                'response' - new answer or 'none' if blank
                   6352:                                'question' - the bubble line to change
1.503     raeburn  6353:                                'questionnum' - the question identifier,
                   6354:                                                may include subquestion. 
1.423     albertel 6355: 
                   6356:   Returns:
                   6357:     $line - the modified scanline
                   6358: 
                   6359:   Side effects: 
                   6360:     $scan_data - may be updated
                   6361: 
                   6362: =cut
                   6363: 
1.82      albertel 6364: 
1.157     albertel 6365: sub scantron_fixup_scanline {
                   6366:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6367:     if ($field eq 'ID') {
                   6368: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6369: 	    return ($line,1,'New value too large');
1.157     albertel 6370: 	}
                   6371: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6372: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6373: 				     $args->{'newid'});
                   6374: 	}
                   6375: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6376: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6377: 	if ($args->{'newid'}=~/^\s*$/) {
                   6378: 	    &scan_data($scan_data,"$whichline.user",
                   6379: 		       $args->{'username'}.':'.$args->{'domain'});
                   6380: 	}
1.186     albertel 6381:     } elsif ($field eq 'CODE') {
1.192     albertel 6382: 	if ($args->{'CODE_ignore_dup'}) {
                   6383: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6384: 	}
                   6385: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6386: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6387: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6388: 		return ($line,1,'New CODE value too large');
                   6389: 	    }
                   6390: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6391: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6392: 	    }
                   6393: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6394: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6395: 	}
1.157     albertel 6396:     } elsif ($field eq 'answer') {
1.497     foxr     6397: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6398: 	my $off=$scantron_config->{'Qoff'};
                   6399: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6400: 	my $answer=${off}x$length;
                   6401: 	if ($args->{'response'} eq 'none') {
                   6402: 	    &scan_data($scan_data,
1.503     raeburn  6403: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6404: 	} else {
                   6405: 	    if ($on eq 'letter') {
                   6406: 		my @alphabet=('A'..'Z');
                   6407: 		$answer=$alphabet[$args->{'response'}];
                   6408: 	    } elsif ($on eq 'number') {
                   6409: 		$answer=$args->{'response'}+1;
                   6410: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6411: 	    } else {
1.497     foxr     6412: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6413: 	    }
1.497     foxr     6414: 	    &scan_data($scan_data,
1.503     raeburn  6415: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6416: 	}
1.497     foxr     6417: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6418: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6419:     }
                   6420:     return $line;
                   6421: }
1.423     albertel 6422: 
                   6423: =pod
                   6424: 
                   6425: =item scan_data
                   6426: 
                   6427:     Edit or look up  an item in the scan_data hash.
                   6428: 
                   6429:   Arguments:
                   6430:     $scan_data  - The hash (see scantron_getfile)
                   6431:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6432:                   scantronfilename_key).
1.423     albertel 6433:     $data        - New value of the hash entry.
                   6434:     $delete      - If true, the entry is removed from the hash.
                   6435: 
                   6436:   Returns:
                   6437:     The new value of the hash table field (undefined if deleted).
                   6438: 
                   6439: =cut
                   6440: 
                   6441: 
1.157     albertel 6442: sub scan_data {
                   6443:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6444:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6445:     if (defined($value)) {
                   6446: 	$scan_data->{$filename.'_'.$key} = $value;
                   6447:     }
                   6448:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6449:     return $scan_data->{$filename.'_'.$key};
                   6450: }
1.423     albertel 6451: 
1.495     albertel 6452: # ----- These first few routines are general use routines.----
                   6453: 
                   6454: # Return the number of occurences of a pattern in a string.
                   6455: 
                   6456: sub occurence_count {
                   6457:     my ($string, $pattern) = @_;
                   6458: 
                   6459:     my @matches = ($string =~ /$pattern/g);
                   6460: 
                   6461:     return scalar(@matches);
                   6462: }
                   6463: 
                   6464: 
                   6465: # Take a string known to have digits and convert all the
                   6466: # digits into letters in the range J,A..I.
                   6467: 
                   6468: sub digits_to_letters {
                   6469:     my ($input) = @_;
                   6470: 
                   6471:     my @alphabet = ('J', 'A'..'I');
                   6472: 
                   6473:     my @input    = split(//, $input);
                   6474:     my $output ='';
                   6475:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6476: 	if ($input[$i] =~ /\d/) {
                   6477: 	    $output .= $alphabet[$input[$i]];
                   6478: 	} else {
                   6479: 	    $output .= $input[$i];
                   6480: 	}
                   6481:     }
                   6482:     return $output;
                   6483: }
                   6484: 
1.423     albertel 6485: =pod 
                   6486: 
                   6487: =item scantron_parse_scanline
                   6488: 
1.711     bisitz   6489:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6490: 
                   6491:  Arguments:
1.711     bisitz   6492:     line             - The text of the bubblesheet file line to process
1.423     albertel 6493:     whichline        - Line number
1.711     bisitz   6494:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6495:     scan_data        - Hash of extra information about the scanline
                   6496:                        (see scantron_getfile for more information)
                   6497:     just_header      - True if should not process question answers but only
                   6498:                        the stuff to the left of the answers.
1.691     raeburn  6499:     randomorder      - True if randomorder in use
                   6500:     randompick       - True if randompick in use
                   6501:     sequence         - Exam folder URL
                   6502:     master_seq       - Ref to array containing symbs in exam folder
                   6503:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6504:                        (corresponding values are resource objects)
                   6505:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6506:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6507:                        are refs to an array of resource objects, ordered
                   6508:                        according to order used for CODE, when randomorder
                   6509:                        and or randompick are in use.
                   6510:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6511:                        for current line to question number used for same question
                   6512:                         in "Master Sequence" (as seen by Course Coordinator).
                   6513:     startline        - Ref to hash where key is question number (0 is first)
                   6514:                        and value is number of first bubble line for current 
                   6515:                        student or code-based randompick and/or randomorder.
                   6516:     totalref         - Ref of scalar used to score total number of bubble
                   6517:                        lines needed for responses in a scan line (used when
                   6518:                        randompick in use. 
                   6519:     
1.423     albertel 6520:  Returns:
                   6521:    Hash containing the result of parsing the scanline
                   6522: 
                   6523:    Keys are all proceeded by the string 'scantron.'
                   6524: 
                   6525:        CODE    - the CODE in use for this scanline
                   6526:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6527:                  by the operator
                   6528:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6529:                             CODEs were selected, but the usage has been
                   6530:                             forced by the operator
1.556     weissno  6531:        ID  - student/employee ID
1.423     albertel 6532:        PaperID - if used, the ID number printed on the sheet when the 
                   6533:                  paper was scanned
                   6534:        FirstName - first name from the sheet
                   6535:        LastName  - last name from the sheet
                   6536: 
                   6537:      if just_header was not true these key may also exist
                   6538: 
1.447     foxr     6539:        missingerror - a list of bubble ranges that are considered to be answers
                   6540:                       to a single question that don't have any bubbles filled in.
                   6541:                       Of the form questionnumber:firstbubblenumber:count.
                   6542:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6543:                       to a single question that have more than one bubble filled in.
                   6544:                       Of the form questionnumber::firstbubblenumber:count
                   6545:    
                   6546:                 In the above, count is the number of bubble responses in the
                   6547:                 input line needed to represent the possible answers to the question.
                   6548:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6549:                 per line would have count = 2.
                   6550: 
1.423     albertel 6551:        maxquest     - the number of the last bubble line that was parsed
                   6552: 
                   6553:        (<number> starts at 1)
                   6554:        <number>.answer - zero or more letters representing the selected
                   6555:                          letters from the scanline for the bubble line 
                   6556:                          <number>.
                   6557:                          if blank there was either no bubble or there where
                   6558:                          multiple bubbles, (consult the keys missingerror and
                   6559:                          doubleerror if this is an error condition)
                   6560: 
                   6561: =cut
                   6562: 
1.82      albertel 6563: sub scantron_parse_scanline {
1.691     raeburn  6564:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6565:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6566:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6567: 
1.82      albertel 6568:     my %record;
1.691     raeburn  6569:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6570:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6571: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6572: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6573: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6574: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6575: 	    $record{'scantron.CODE'}=substr($data,
                   6576: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6577: 					    $$scantron_config{'CODElength'});
1.191     albertel 6578: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6579: 		$record{'scantron.useCODE'}=1;
                   6580: 	    }
1.192     albertel 6581: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6582: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6583: 	    }
1.82      albertel 6584: 	} else {
                   6585: 	    #FIXME interpret first N questions
                   6586: 	}
                   6587:     }
1.83      albertel 6588:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6589: 				  $$scantron_config{'IDlength'});
1.157     albertel 6590:     $record{'scantron.PaperID'}=
                   6591: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6592: 	       $$scantron_config{'PaperIDlength'});
                   6593:     $record{'scantron.FirstName'}=
                   6594: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6595: 	       $$scantron_config{'FirstNamelength'});
                   6596:     $record{'scantron.LastName'}=
                   6597: 	substr($data,$$scantron_config{'LastName'}-1,
                   6598: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6599:     if ($just_header) { return \%record; }
1.194     albertel 6600: 
1.82      albertel 6601:     my @alphabet=('A'..'Z');
                   6602:     my $questnum=0;
1.447     foxr     6603:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6604: 
1.691     raeburn  6605:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6606:     if ($randompick || $randomorder) {
                   6607:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6608:                                          $master_seq,$symb_to_resource,
                   6609:                                          $partids_by_symb,$orderedforcode,
                   6610:                                          $respnumlookup,$startline);
                   6611:         if ($total) {
                   6612:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6613:         }
                   6614:         if (ref($totalref)) {
                   6615:             $$totalref = $total;
                   6616:         }
                   6617:     }
                   6618:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6619:     chomp($questions);		# Get rid of any trailing \n.
                   6620:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6621:     while (length($questions)) {
1.691     raeburn  6622:         my $answers_needed;
                   6623:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6624:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6625:         } else {
                   6626: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6627:         }
1.503     raeburn  6628:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6629:                              || 1;
                   6630:         $questnum++;
                   6631:         my $quest_id = $questnum;
                   6632:         my $currentquest = substr($questions,0,$answer_length);
                   6633:         $questions       = substr($questions,$answer_length);
                   6634:         if (length($currentquest) < $answer_length) { next; }
                   6635: 
1.691     raeburn  6636:         my $subdivided;
                   6637:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6638:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6639:         } else {
                   6640:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6641:         }
                   6642:         if ($subdivided =~ /,/) {
1.503     raeburn  6643:             my $subquestnum = 1;
                   6644:             my $subquestions = $currentquest;
1.691     raeburn  6645:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6646:             foreach my $subans (@subanswers_needed) {
                   6647:                 my $subans_length =
                   6648:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6649:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6650:                 $subquestions   = substr($subquestions,$subans_length);
                   6651:                 $quest_id = "$questnum.$subquestnum";
                   6652:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6653:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6654:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6655:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6656:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6657:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6658:                 } else {
                   6659:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6660:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6661:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6662:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6663:                 }
                   6664:                 $subquestnum ++;
                   6665:             }
                   6666:         } else {
                   6667:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6668:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6669:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6670:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6671:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6672:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6673:             } else {
                   6674:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6675:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6676:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6677:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6678:             }
                   6679:         }
                   6680:     }
                   6681:     $record{'scantron.maxquest'}=$questnum;
                   6682:     return \%record;
                   6683: }
1.447     foxr     6684: 
1.691     raeburn  6685: sub get_master_seq {
                   6686:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6687:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6688:                    (ref($symb_to_resource) eq 'HASH'));
                   6689:     my $resource_error;
                   6690:     foreach my $resource (@{$resources}) {
                   6691:         my $ressymb;
                   6692:         if (ref($resource)) {
                   6693:             $ressymb = $resource->symb();
                   6694:             push(@{$master_seq},$ressymb);
                   6695:             $symb_to_resource->{$ressymb} = $resource;
                   6696:         } else {
                   6697:             $resource_error = 1;
                   6698:             last;
                   6699:         }
                   6700:     }
                   6701:     return $resource_error;
                   6702: }
                   6703: 
                   6704: sub get_respnum_lookups {
                   6705:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6706:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6707:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6708:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6709:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6710:                    (ref($startline) eq 'HASH'));
                   6711:     my ($user,$scancode);
                   6712:     if ((exists($record->{'scantron.CODE'})) &&
                   6713:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6714:         $scancode = $record->{'scantron.CODE'};
                   6715:     } else {
                   6716:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6717:     }
                   6718:     my @mapresources =
                   6719:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6720:                      $orderedforcode);
                   6721:     my $total = 0;
                   6722:     my $count = 0;
                   6723:     foreach my $resource (@mapresources) {
                   6724:         my $id = $resource->id();
                   6725:         my $symb = $resource->symb();
                   6726:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6727:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6728:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6729:                 if ($respnum ne '') {
                   6730:                     $respnumlookup->{$count} = $respnum;
                   6731:                     $startline->{$count} = $total;
                   6732:                     $total += $bubble_lines_per_response{$respnum};
                   6733:                     $count ++;
                   6734:                 }
                   6735:             }
                   6736:         }
                   6737:     }
                   6738:     return $total;
                   6739: }
                   6740: 
1.503     raeburn  6741: sub scantron_validator_lettnum {
                   6742:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6743:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6744:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6745: 
                   6746:     # Qon 'letter' implies for each slot in currquest we have:
                   6747:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6748:     #    about anything else (esp. a value of Qoff) for missing
                   6749:     #    bubbles.
                   6750:     #
                   6751:     # Qon 'number' implies each slot gives a digit that indexes the
                   6752:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6753:     #    and * or ? for double bubbles on a single line.
                   6754:     #
1.447     foxr     6755: 
1.503     raeburn  6756:     my $matchon;
                   6757:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6758:         $matchon = '[A-Z]';
                   6759:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6760:         $matchon = '\d';
                   6761:     }
                   6762:     my $occurrences = 0;
1.691     raeburn  6763:     my $responsenum = $questnum-1;
                   6764:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6765:        $responsenum = $respnumlookup->{$questnum-1} 
                   6766:     }
                   6767:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6768:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6769:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6770:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6771:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6772:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6773:         my @singlelines = split('',$currquest);
                   6774:         foreach my $entry (@singlelines) {
                   6775:             $occurrences = &occurence_count($entry,$matchon);
                   6776:             if ($occurrences > 1) {
                   6777:                 last;
                   6778:             }
1.691     raeburn  6779:         }
1.503     raeburn  6780:     } else {
                   6781:         $occurrences = &occurence_count($currquest,$matchon); 
                   6782:     }
                   6783:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6784:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6785:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6786:             my $bubble = substr($currquest,$ans,1);
                   6787:             if ($bubble =~ /$matchon/ ) {
                   6788:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6789:                     if ($bubble == 0) {
                   6790:                         $bubble = 10; 
                   6791:                     }
                   6792:                     $record->{"scantron.$ansnum.answer"} = 
                   6793:                         $alphabet->[$bubble-1];
                   6794:                 } else {
                   6795:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6796:                 }
                   6797:             } else {
                   6798:                 $record->{"scantron.$ansnum.answer"}='';
                   6799:             }
                   6800:             $ansnum++;
                   6801:         }
                   6802:     } elsif (!defined($currquest)
                   6803:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6804:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6805:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6806:             $record->{"scantron.$ansnum.answer"}='';
                   6807:             $ansnum++;
                   6808:         }
                   6809:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6810:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6811:         }
                   6812:     } else {
                   6813:         if ($$scantron_config{'Qon'} eq 'number') {
                   6814:             $currquest = &digits_to_letters($currquest);            
                   6815:         }
                   6816:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6817:             my $bubble = substr($currquest,$ans,1);
                   6818:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6819:             $ansnum++;
                   6820:         }
                   6821:     }
                   6822:     return $ansnum;
                   6823: }
1.447     foxr     6824: 
1.503     raeburn  6825: sub scantron_validator_positional {
                   6826:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6827:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6828:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6829: 
1.503     raeburn  6830:     # Otherwise there's a positional notation;
                   6831:     # each bubble line requires Qlength items, and there are filled in
                   6832:     # bubbles for each case where there 'Qon' characters.
                   6833:     #
1.447     foxr     6834: 
1.503     raeburn  6835:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6836: 
1.503     raeburn  6837:     # If the split only gives us one element.. the full length of the
                   6838:     # answer string, no bubbles are filled in:
1.447     foxr     6839: 
1.507     raeburn  6840:     if ($answers_needed eq '') {
                   6841:         return;
                   6842:     }
                   6843: 
1.503     raeburn  6844:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6845:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6846:             $record->{"scantron.$ansnum.answer"}='';
                   6847:             $ansnum++;
                   6848:         }
                   6849:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6850:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6851:         }
                   6852:     } elsif (scalar(@array) == 2) {
                   6853:         my $location = length($array[0]);
                   6854:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6855:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6856:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6857:             if ($ans eq $line_num) {
                   6858:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6859:             } else {
                   6860:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6861:             }
                   6862:             $ansnum++;
                   6863:          }
                   6864:     } else {
                   6865:         #  If there's more than one instance of a bubble character
                   6866:         #  That's a double bubble; with positional notation we can
                   6867:         #  record all the bubbles filled in as well as the
                   6868:         #  fact this response consists of multiple bubbles.
                   6869:         #
1.691     raeburn  6870:         my $responsenum = $questnum-1;
                   6871:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6872:             $responsenum = $respnumlookup->{$questnum-1}
                   6873:         }
                   6874:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6875:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6876:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6877:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6878:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6879:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6880:             my $doubleerror = 0;
                   6881:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6882:                    (!$doubleerror)) {
                   6883:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6884:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6885:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6886:                if (length(@currarray) > 2) {
                   6887:                    $doubleerror = 1;
                   6888:                } 
                   6889:             }
                   6890:             if ($doubleerror) {
                   6891:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6892:             }
                   6893:         } else {
                   6894:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6895:         }
                   6896:         my $item = $ansnum;
                   6897:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6898:             $record->{"scantron.$item.answer"} = '';
                   6899:             $item ++;
                   6900:         }
1.447     foxr     6901: 
1.503     raeburn  6902:         my @ans=@array;
                   6903:         my $i=0;
                   6904:         my $increment = 0;
                   6905:         while ($#ans) {
                   6906:             $i+=length($ans[0]) + $increment;
                   6907:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6908:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6909:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6910:             shift(@ans);
                   6911:             $increment = 1;
                   6912:         }
                   6913:         $ansnum += $answers_needed;
1.82      albertel 6914:     }
1.503     raeburn  6915:     return $ansnum;
1.82      albertel 6916: }
                   6917: 
1.423     albertel 6918: =pod
                   6919: 
                   6920: =item scantron_add_delay
                   6921: 
                   6922:    Adds an error message that occurred during the grading phase to a
                   6923:    queue of messages to be shown after grading pass is complete
                   6924: 
                   6925:  Arguments:
1.424     albertel 6926:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6927:    $scanline    - the scanline that caused the error
                   6928:    $errormesage - the error message
                   6929:    $errorcode   - a numeric code for the error
                   6930: 
                   6931:  Side Effects:
1.424     albertel 6932:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6933: 
                   6934: =cut
                   6935: 
1.82      albertel 6936: sub scantron_add_delay {
1.140     albertel 6937:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6938:     push(@$delayqueue,
                   6939: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6940: 	  'ecode' => $errorcode }
                   6941: 	 );
1.82      albertel 6942: }
                   6943: 
1.423     albertel 6944: =pod
                   6945: 
                   6946: =item scantron_find_student
                   6947: 
1.424     albertel 6948:    Finds the username for the current scanline
                   6949: 
                   6950:   Arguments:
                   6951:    $scantron_record - hash result from scantron_parse_scanline
                   6952:    $scan_data       - hash of correction information 
                   6953:                       (see &scantron_getfile() form more information)
                   6954:    $idmap           - hash from &username_to_idmap()
                   6955:    $line            - number of current scanline
                   6956:  
                   6957:   Returns:
                   6958:    Either 'username:domain' or undef if unknown
                   6959: 
1.423     albertel 6960: =cut
                   6961: 
1.82      albertel 6962: sub scantron_find_student {
1.157     albertel 6963:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6964:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6965:     if ($scanID =~ /^\s*$/) {
                   6966:  	return &scan_data($scan_data,"$line.user");
                   6967:     }
1.83      albertel 6968:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6969:  	if (lc($id) eq lc($scanID)) {
                   6970:  	    return $$idmap{$id};
                   6971:  	}
1.83      albertel 6972:     }
                   6973:     return undef;
                   6974: }
                   6975: 
1.423     albertel 6976: =pod
                   6977: 
                   6978: =item scantron_filter
                   6979: 
1.424     albertel 6980:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6981:    hidden resources was selected
                   6982: 
1.423     albertel 6983: =cut
                   6984: 
1.83      albertel 6985: sub scantron_filter {
                   6986:     my ($curres)=@_;
1.331     albertel 6987: 
                   6988:     if (ref($curres) && $curres->is_problem()) {
                   6989: 	# if the user has asked to not have either hidden
                   6990: 	# or 'randomout' controlled resources to be graded
                   6991: 	# don't include them
                   6992: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6993: 	    && $curres->randomout) {
                   6994: 	    return 0;
                   6995: 	}
1.83      albertel 6996: 	return 1;
                   6997:     }
                   6998:     return 0;
1.82      albertel 6999: }
                   7000: 
1.423     albertel 7001: =pod
                   7002: 
                   7003: =item scantron_process_corrections
                   7004: 
1.424     albertel 7005:    Gets correction information out of submitted form data and corrects
                   7006:    the scanline
                   7007: 
1.423     albertel 7008: =cut
                   7009: 
1.157     albertel 7010: sub scantron_process_corrections {
                   7011:     my ($r) = @_;
1.754     raeburn  7012:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7013:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7014:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 7015:     my $which=$env{'form.scantron_line'};
1.200     albertel 7016:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 7017:     my ($skip,$err,$errmsg);
1.257     albertel 7018:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 7019: 	$skip=1;
1.257     albertel 7020:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   7021: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   7022: 	    $env{'form.scantron_domain'};
1.157     albertel 7023: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   7024: 	($line,$err,$errmsg)=
                   7025: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   7026: 				     'ID',{'newid'=>$newid,
1.257     albertel 7027: 				    'username'=>$env{'form.scantron_username'},
                   7028: 				    'domain'=>$env{'form.scantron_domain'}});
                   7029:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   7030: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 7031: 	my $newCODE;
1.192     albertel 7032: 	my %args;
1.190     albertel 7033: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 7034: 	    $newCODE='use_unfound';
1.190     albertel 7035: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 7036: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 7037: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 7038: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 7039: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 7040: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 7041: 	}
1.257     albertel 7042: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 7043: 	    $args{'CODE_ignore_dup'}=1;
                   7044: 	}
                   7045: 	$args{'CODE'}=$newCODE;
1.186     albertel 7046: 	($line,$err,$errmsg)=
                   7047: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7048: 				     'CODE',\%args);
1.257     albertel 7049:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7050: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7051: 	    ($line,$err,$errmsg)=
                   7052: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7053: 					 $which,'answer',
                   7054: 					 { 'question'=>$question,
1.503     raeburn  7055: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7056:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7057: 	    if ($err) { last; }
                   7058: 	}
                   7059:     }
                   7060:     if ($err) {
1.703     bisitz   7061:         $r->print(
                   7062:             '<p class="LC_error">'
                   7063:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7064:                 $errmsg)
1.704     raeburn  7065:            .'</p>');
1.157     albertel 7066:     } else {
1.200     albertel 7067: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7068: 	&scantron_putfile($scanlines,$scan_data);
                   7069:     }
                   7070: }
                   7071: 
1.423     albertel 7072: =pod
                   7073: 
                   7074: =item reset_skipping_status
                   7075: 
1.424     albertel 7076:    Forgets the current set of remember skipped scanlines (and thus
                   7077:    reverts back to considering all lines in the
                   7078:    scantron_skipped_<filename> file)
                   7079: 
1.423     albertel 7080: =cut
                   7081: 
1.200     albertel 7082: sub reset_skipping_status {
                   7083:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7084:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7085:     &scantron_putfile(undef,$scan_data);
                   7086: }
                   7087: 
1.423     albertel 7088: =pod
                   7089: 
                   7090: =item start_skipping
                   7091: 
1.424     albertel 7092:    Marks a scanline to be skipped. 
                   7093: 
1.423     albertel 7094: =cut
                   7095: 
1.376     albertel 7096: sub start_skipping {
1.200     albertel 7097:     my ($scan_data,$i)=@_;
                   7098:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7099:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7100: 	$remembered{$i}=2;
                   7101:     } else {
                   7102: 	$remembered{$i}=1;
                   7103:     }
1.200     albertel 7104:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7105: }
                   7106: 
1.423     albertel 7107: =pod
                   7108: 
                   7109: =item should_be_skipped
                   7110: 
1.424     albertel 7111:    Checks whether a scanline should be skipped.
                   7112: 
1.423     albertel 7113: =cut
                   7114: 
1.200     albertel 7115: sub should_be_skipped {
1.376     albertel 7116:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7117:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7118: 	# not redoing old skips
1.376     albertel 7119: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7120: 	return 0;
                   7121:     }
                   7122:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7123: 
                   7124:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7125: 	return 0;
                   7126:     }
1.200     albertel 7127:     return 1;
                   7128: }
                   7129: 
1.423     albertel 7130: =pod
                   7131: 
                   7132: =item remember_current_skipped
                   7133: 
1.424     albertel 7134:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7135:    file and remembers them into scan_data for later use.
                   7136: 
1.423     albertel 7137: =cut
                   7138: 
1.200     albertel 7139: sub remember_current_skipped {
                   7140:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7141:     my %to_remember;
                   7142:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7143: 	if ($scanlines->{'skipped'}[$i]) {
                   7144: 	    $to_remember{$i}=1;
                   7145: 	}
                   7146:     }
1.376     albertel 7147: 
1.200     albertel 7148:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7149:     &scantron_putfile(undef,$scan_data);
                   7150: }
                   7151: 
1.423     albertel 7152: =pod
                   7153: 
                   7154: =item check_for_error
                   7155: 
1.424     albertel 7156:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  7157:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7158:     something went wrong.
                   7159: 
1.423     albertel 7160: =cut
                   7161: 
1.200     albertel 7162: sub check_for_error {
                   7163:     my ($r,$result)=@_;
                   7164:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7165: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7166:     }
                   7167: }
1.157     albertel 7168: 
1.423     albertel 7169: =pod
                   7170: 
                   7171: =item scantron_warning_screen
                   7172: 
1.424     albertel 7173:    Interstitial screen to make sure the operator has selected the
                   7174:    correct options before we start the validation phase.
                   7175: 
1.423     albertel 7176: =cut
                   7177: 
1.203     albertel 7178: sub scantron_warning_screen {
1.650     raeburn  7179:     my ($button_text,$symb)=@_;
1.257     albertel 7180:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  7181:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7182:     my $CODElist;
1.284     albertel 7183:     if ($scantron_config{'CODElocation'} &&
                   7184: 	$scantron_config{'CODEstart'} &&
                   7185: 	$scantron_config{'CODElength'}) {
                   7186: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   7187: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7188: 	$CODElist=
1.492     albertel 7189: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7190: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7191:     }
1.663     raeburn  7192:     my $lastbubblepoints;
                   7193:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7194:         $lastbubblepoints =
                   7195:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7196:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7197:     }
1.770     raeburn  7198:     return '
1.203     albertel 7199: <p>
1.492     albertel 7200: <span class="LC_warning">
1.705     raeburn  7201: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7202: </p>
                   7203: <table>
1.492     albertel 7204: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7205: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  7206: '.$CODElist.$lastbubblepoints.'
1.203     albertel 7207: </table>
1.680     raeburn  7208: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  7209: '.&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  7210: ';
1.203     albertel 7211: }
                   7212: 
1.423     albertel 7213: =pod
                   7214: 
                   7215: =item scantron_do_warning
                   7216: 
1.424     albertel 7217:    Check if the operator has picked something for all required
                   7218:    fields. Error out if something is missing.
                   7219: 
1.423     albertel 7220: =cut
                   7221: 
1.203     albertel 7222: sub scantron_do_warning {
1.608     www      7223:     my ($r,$symb)=@_;
1.203     albertel 7224:     if (!$symb) {return '';}
1.324     albertel 7225:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7226:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7227:     if ( $env{'form.selectpage'} eq '' ||
                   7228: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7229: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7230: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7231: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7232: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7233: 	} 
1.257     albertel 7234: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7235: 	    $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  7236: 	}
1.257     albertel 7237: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7238: 	    $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  7239: 	}
1.237     albertel 7240:     } else {
1.650     raeburn  7241: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  7242:         my ($checksec,@possibles) = &gradable_sections();
                   7243:         my $gradesections;
                   7244:         if ($checksec) {
                   7245:             my $file=$env{'form.scantron_selectfile'};
                   7246:             if (&valid_file($file)) {
                   7247:                 my %bysec = &scantron_get_sections();
                   7248:                 my $table;
                   7249:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   7250:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   7251:                     $table = &Apache::loncommon::start_data_table()."\n".
                   7252:                              &Apache::loncommon::start_data_table_header_row().
                   7253:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   7254:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   7255:                     if ($bysec{'none'}) {
                   7256:                         $table .= &Apache::loncommon::start_data_table_row().
                   7257:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   7258:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7259:                     }
                   7260:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   7261:                         next if ($sec eq 'none');
                   7262:                         $table .= &Apache::loncommon::start_data_table_row().
                   7263:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   7264:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7265:                     }
                   7266:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   7267:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   7268:                                       '<p>'.$table.'</p>';
                   7269:                     if (@possibles) {
                   7270:                         $gradesections .= '<p>'.
                   7271:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   7272:                                               scalar(@possibles)).'<br />'.
                   7273:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   7274:                                               '<i>'.$checksec.'</i>').' ';
                   7275:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   7276:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   7277:                         }
                   7278:                         $gradesections .= '</p>';
                   7279:                     }
                   7280:                 }
                   7281:             } else {
                   7282:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   7283:             }
                   7284:         }
1.663     raeburn  7285:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7286: 	$r->print('
1.770     raeburn  7287: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 7288: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7289: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7290: ');
1.237     albertel 7291:     }
1.614     www      7292:     $r->print("</form><br />");
1.203     albertel 7293:     return '';
                   7294: }
                   7295: 
1.423     albertel 7296: =pod
                   7297: 
                   7298: =item scantron_form_start
                   7299: 
1.424     albertel 7300:     html hidden input for remembering all selected grading options
                   7301: 
1.423     albertel 7302: =cut
                   7303: 
1.203     albertel 7304: sub scantron_form_start {
                   7305:     my ($max_bubble)=@_;
                   7306:     my $result= <<SCANTRONFORM;
                   7307: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7308:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7309:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7310:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7311:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7312:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7313:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7314:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7315:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7316:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7317: SCANTRONFORM
1.447     foxr     7318: 
                   7319:   my $line = 0;
                   7320:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7321:        my $chunk =
                   7322: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7323:        $chunk .=
                   7324: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7325:        $chunk .= 
                   7326:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7327:        $chunk .=
                   7328:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7329:        $chunk .=
                   7330:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7331:        $result .= $chunk;
                   7332:        $line++;
1.691     raeburn  7333:     }
1.203     albertel 7334:     return $result;
                   7335: }
                   7336: 
1.423     albertel 7337: =pod
                   7338: 
                   7339: =item scantron_validate_file
                   7340: 
1.659     raeburn  7341:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7342: 
                   7343:     Also processes any necessary information resets that need to
                   7344:     occur before validation begins (ignore previous corrections,
                   7345:     restarting the skipped records processing)
                   7346: 
1.423     albertel 7347: =cut
                   7348: 
1.157     albertel 7349: sub scantron_validate_file {
1.608     www      7350:     my ($r,$symb) = @_;
1.157     albertel 7351:     if (!$symb) {return '';}
1.324     albertel 7352:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7353:     
1.703     bisitz   7354:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7355:     # them when doing the corrections reset
1.257     albertel 7356:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7357: 	&reset_skipping_status();
                   7358:     }
1.257     albertel 7359:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7360: 	&remember_current_skipped();
1.257     albertel 7361: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7362:     }
                   7363: 
1.257     albertel 7364:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7365: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7366: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7367: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7368: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7369:     }
1.200     albertel 7370: 
1.257     albertel 7371:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7372: 	&scantron_process_corrections($r);
                   7373:     }
1.770     raeburn  7374: 
                   7375:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   7376:     my ($checksec,@gradable);
                   7377:     if ($env{'request.course.sec'}) {
                   7378:         ($checksec,my @possibles) = &gradable_sections();
                   7379:         if ($checksec) {
                   7380:             if (@possibles) {
                   7381:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   7382:                 if (@chosensecs) {
                   7383:                     foreach my $sec (@chosensecs) {
                   7384:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   7385:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   7386:                                 push(@gradable,$sec);
                   7387:                             }
                   7388:                         }
                   7389:                     }
                   7390:                 }
                   7391:             }
                   7392:             $r->print('<p><table>');
                   7393:             if (@gradable) {
                   7394:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   7395:                 $r->print(
                   7396:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   7397:             } else {
                   7398:                 $r->print(
                   7399:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   7400:             }
                   7401:             $r->print('</table></p>');
                   7402:         }
                   7403:     }
                   7404:     $r->rflush();
                   7405: 
1.157     albertel 7406:     #get the student pick code ready
                   7407:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7408:     my $nav_error;
1.754     raeburn  7409:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7410:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7411:     if ($nav_error) {
                   7412:         $r->print(&navmap_errormsg());
                   7413:         return '';
                   7414:     }
1.203     albertel 7415:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7416:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7417:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7418:     }
1.157     albertel 7419:     $r->print($result);
                   7420:     
1.334     albertel 7421:     my @validate_phases=( 'sequence',
                   7422: 			  'ID',
1.157     albertel 7423: 			  'CODE',
                   7424: 			  'doublebubble',
                   7425: 			  'missingbubbles');
1.257     albertel 7426:     if (!$env{'form.validatepass'}) {
                   7427: 	$env{'form.validatepass'} = 0;
1.157     albertel 7428:     }
1.257     albertel 7429:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  7430:     my %skipbysec=();
1.448     foxr     7431: 
1.157     albertel 7432:     my $stop=0;
                   7433:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7434: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7435: 	$r->rflush();
1.691     raeburn  7436:      
1.157     albertel 7437: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7438: 	{
                   7439: 	    no strict 'refs';
1.770     raeburn  7440:             my @extras=();
                   7441:             if ($validate_phases[$currentphase] eq 'ID') {
                   7442:                 @extras = (\%skipbysec,$checksec,@gradable);
                   7443:             }
                   7444: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 7445: 	}
                   7446:     }
                   7447:     if (!$stop) {
1.650     raeburn  7448: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  7449:         my $secinfo;
                   7450:         if (keys(%skipbysec) > 0) {
                   7451:             my $seclist = '<ul>';
                   7452:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   7453:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   7454:             }
                   7455:             $seclist .= '</ul>';
                   7456:             $secinfo = '<p class="LC_info">'.
                   7457:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   7458:                            $seclist).
                   7459:                        '</p>';
                   7460:         }
1.542     raeburn  7461: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  7462:                   $secinfo.$warning.
1.542     raeburn  7463:                   &mt('Perform verification for each student after storage of submissions?').
                   7464:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7465:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7466:                   ('&nbsp;'x3).'<label>'.
                   7467:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7468:                   '</label></span><br />'.
                   7469:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7470:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7471:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7472:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7473:     } else {
                   7474: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7475: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7476:     }
                   7477:     if ($stop) {
1.334     albertel 7478: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7479: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7480: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7481: 
1.650     raeburn  7482: 	    $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 7483: 	} else {
1.503     raeburn  7484:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7485: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7486:             } else {
1.539     riegler  7487:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7488:             }
1.492     albertel 7489: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7490: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7491: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7492: 	}
1.157     albertel 7493:     }
1.614     www      7494:     $r->print(" </form><br />");
1.157     albertel 7495:     return '';
                   7496: }
                   7497: 
1.423     albertel 7498: 
                   7499: =pod
                   7500: 
                   7501: =item scantron_remove_file
                   7502: 
1.659     raeburn  7503:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7504:    scantron_original_<filename> is never removed
                   7505: 
                   7506: 
1.423     albertel 7507: =cut
                   7508: 
1.200     albertel 7509: sub scantron_remove_file {
1.192     albertel 7510:     my ($which)=@_;
1.257     albertel 7511:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7512:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7513:     my $file='scantron_';
1.200     albertel 7514:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7515: 	$file.=$which.'_';
1.192     albertel 7516:     } else {
                   7517: 	return 'refused';
                   7518:     }
1.257     albertel 7519:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7520:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7521: }
                   7522: 
1.423     albertel 7523: 
                   7524: =pod
                   7525: 
                   7526: =item scantron_remove_scan_data
                   7527: 
1.659     raeburn  7528:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7529:    data file.  (In the case that both the are doing skipped records we need
                   7530:    to remember the old skipped lines for the time being so that element
                   7531:    persists for a while.)
                   7532: 
1.423     albertel 7533: =cut
                   7534: 
1.200     albertel 7535: sub scantron_remove_scan_data {
1.257     albertel 7536:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7537:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7538:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7539:     my @todelete;
1.257     albertel 7540:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7541:     foreach my $key (@keys) {
                   7542: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7543: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7544: 		$key=~/remember_skipping/) {
                   7545: 		next;
                   7546: 	    }
1.192     albertel 7547: 	    push(@todelete,$key);
                   7548: 	}
                   7549:     }
1.200     albertel 7550:     my $result;
1.192     albertel 7551:     if (@todelete) {
1.491     albertel 7552: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7553: 				       \@todelete,$cdom,$cname);
                   7554:     } else {
                   7555: 	$result = 'ok';
1.192     albertel 7556:     }
                   7557:     return $result;
                   7558: }
                   7559: 
1.423     albertel 7560: 
                   7561: =pod
                   7562: 
                   7563: =item scantron_getfile
                   7564: 
1.659     raeburn  7565:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7566:     the scan_data hash
                   7567:   
                   7568:   Arguments:
                   7569:     None
                   7570: 
                   7571:   Returns:
                   7572:     2 hash references
                   7573: 
                   7574:      - first one has 
                   7575:          orig      -
                   7576:          corrected -
                   7577:          skipped   -  each of which points to an array ref of the specified
                   7578:                       file broken up into individual lines
                   7579:          count     - number of scanlines
                   7580:  
                   7581:      - second is the scan_data hash possible keys are
1.425     albertel 7582:        ($number refers to scanline numbered $number and thus the key affects
                   7583:         only that scanline
                   7584:         $bubline refers to the specific bubble line element and the aspects
                   7585:         refers to that specific bubble line element)
                   7586: 
                   7587:        $number.user - username:domain to use
                   7588:        $number.CODE_ignore_dup 
                   7589:                     - ignore the duplicate CODE error 
                   7590:        $number.useCODE
                   7591:                     - use the CODE in the scanline as is
                   7592:        $number.no_bubble.$bubline
                   7593:                     - it is valid that there is no bubbled in bubble
                   7594:                       at $number $bubline
                   7595:        remember_skipping
                   7596:                     - a frozen hash containing keys of $number and values
                   7597:                       of either 
                   7598:                         1 - we are on a 'do skipped records pass' and plan
                   7599:                             on processing this line
                   7600:                         2 - we are on a 'do skipped records pass' and this
                   7601:                             scanline has been marked to skip yet again
1.424     albertel 7602: 
1.423     albertel 7603: =cut
                   7604: 
1.157     albertel 7605: sub scantron_getfile {
1.200     albertel 7606:     #FIXME really would prefer a scantron directory
1.257     albertel 7607:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7608:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7609:     my $lines;
                   7610:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7611: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7612:     my %scanlines;
                   7613:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7614:     my $temp=$scanlines{'orig'};
                   7615:     $scanlines{'count'}=$#$temp;
                   7616: 
                   7617:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7618: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7619:     if ($lines eq '-1') {
                   7620: 	$scanlines{'corrected'}=[];
                   7621:     } else {
                   7622: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7623:     }
                   7624:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7625: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7626:     if ($lines eq '-1') {
                   7627: 	$scanlines{'skipped'}=[];
                   7628:     } else {
                   7629: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7630:     }
1.175     albertel 7631:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7632:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7633:     my %scan_data = @tmp;
                   7634:     return (\%scanlines,\%scan_data);
                   7635: }
                   7636: 
1.423     albertel 7637: =pod
                   7638: 
                   7639: =item lonnet_putfile
                   7640: 
1.424     albertel 7641:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7642: 
                   7643:  Arguments:
                   7644:    $contents - data to store
                   7645:    $filename - filename to store $contents into
                   7646: 
                   7647:  Returns:
                   7648:    result value from &Apache::lonnet::finishuserfileupload
                   7649: 
1.423     albertel 7650: =cut
                   7651: 
1.157     albertel 7652: sub lonnet_putfile {
                   7653:     my ($contents,$filename)=@_;
1.257     albertel 7654:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7655:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7656:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7657:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7658: 
                   7659: }
                   7660: 
1.423     albertel 7661: =pod
                   7662: 
                   7663: =item scantron_putfile
                   7664: 
1.659     raeburn  7665:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7666:     scan_data hash. (Does not modify the original version only the
                   7667:     corrected and skipped versions.
                   7668: 
                   7669:  Arguments:
                   7670:     $scanlines - hash ref that looks like the first return value from
                   7671:                  &scantron_getfile()
                   7672:     $scan_data - hash ref that looks like the second return value from
                   7673:                  &scantron_getfile()
                   7674: 
1.423     albertel 7675: =cut
                   7676: 
1.157     albertel 7677: sub scantron_putfile {
                   7678:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7679:     #FIXME really would prefer a scantron directory
1.257     albertel 7680:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7681:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7682:     if ($scanlines) {
                   7683: 	my $prefix='scantron_';
1.157     albertel 7684: # no need to update orig, shouldn't change
                   7685: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7686: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7687: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7688: 			$prefix.'corrected_'.
1.257     albertel 7689: 			$env{'form.scantron_selectfile'});
1.200     albertel 7690: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7691: 			$prefix.'skipped_'.
1.257     albertel 7692: 			$env{'form.scantron_selectfile'});
1.200     albertel 7693:     }
1.175     albertel 7694:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7695: }
                   7696: 
1.423     albertel 7697: =pod
                   7698: 
                   7699: =item scantron_get_line
                   7700: 
1.424     albertel 7701:    Returns the correct version of the scanline
                   7702: 
                   7703:  Arguments:
                   7704:     $scanlines - hash ref that looks like the first return value from
                   7705:                  &scantron_getfile()
                   7706:     $scan_data - hash ref that looks like the second return value from
                   7707:                  &scantron_getfile()
                   7708:     $i         - number of the requested line (starts at 0)
                   7709: 
                   7710:  Returns:
                   7711:    A scanline, (either the original or the corrected one if it
                   7712:    exists), or undef if the requested scanline should be
                   7713:    skipped. (Either because it's an skipped scanline, or it's an
                   7714:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7715:    pass.
                   7716: 
1.423     albertel 7717: =cut
                   7718: 
1.157     albertel 7719: sub scantron_get_line {
1.200     albertel 7720:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7721:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7722:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7723:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7724:     return $scanlines->{'orig'}[$i]; 
                   7725: }
                   7726: 
1.423     albertel 7727: =pod
                   7728: 
                   7729: =item scantron_todo_count
                   7730: 
1.424     albertel 7731:     Counts the number of scanlines that need processing.
                   7732: 
                   7733:  Arguments:
                   7734:     $scanlines - hash ref that looks like the first return value from
                   7735:                  &scantron_getfile()
                   7736:     $scan_data - hash ref that looks like the second return value from
                   7737:                  &scantron_getfile()
                   7738: 
                   7739:  Returns:
                   7740:     $count - number of scanlines to process
                   7741: 
1.423     albertel 7742: =cut
                   7743: 
1.200     albertel 7744: sub get_todo_count {
                   7745:     my ($scanlines,$scan_data)=@_;
                   7746:     my $count=0;
                   7747:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7748: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7749: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7750: 	$count++;
                   7751:     }
                   7752:     return $count;
                   7753: }
                   7754: 
1.423     albertel 7755: =pod
                   7756: 
                   7757: =item scantron_put_line
                   7758: 
1.659     raeburn  7759:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7760:     data file.
                   7761: 
                   7762:  Arguments:
                   7763:     $scanlines - hash ref that looks like the first return value from
                   7764:                  &scantron_getfile()
                   7765:     $scan_data - hash ref that looks like the second return value from
                   7766:                  &scantron_getfile()
                   7767:     $i         - line number to update
                   7768:     $newline   - contents of the updated scanline
                   7769:     $skip      - if true make the line for skipping and update the
                   7770:                  'skipped' file
                   7771: 
1.423     albertel 7772: =cut
                   7773: 
1.157     albertel 7774: sub scantron_put_line {
1.200     albertel 7775:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7776:     if ($skip) {
                   7777: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7778: 	&start_skipping($scan_data,$i);
1.157     albertel 7779: 	return;
                   7780:     }
                   7781:     $scanlines->{'corrected'}[$i]=$newline;
                   7782: }
                   7783: 
1.423     albertel 7784: =pod
                   7785: 
                   7786: =item scantron_clear_skip
                   7787: 
1.424     albertel 7788:    Remove a line from the 'skipped' file
                   7789: 
                   7790:  Arguments:
                   7791:     $scanlines - hash ref that looks like the first return value from
                   7792:                  &scantron_getfile()
                   7793:     $scan_data - hash ref that looks like the second return value from
                   7794:                  &scantron_getfile()
                   7795:     $i         - line number to update
                   7796: 
1.423     albertel 7797: =cut
                   7798: 
1.376     albertel 7799: sub scantron_clear_skip {
                   7800:     my ($scanlines,$scan_data,$i)=@_;
                   7801:     if (exists($scanlines->{'skipped'}[$i])) {
                   7802: 	undef($scanlines->{'skipped'}[$i]);
                   7803: 	return 1;
                   7804:     }
                   7805:     return 0;
                   7806: }
                   7807: 
1.423     albertel 7808: =pod
                   7809: 
                   7810: =item scantron_filter_not_exam
                   7811: 
1.424     albertel 7812:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7813:    filter out resources that are not marked as 'exam' mode
                   7814: 
1.423     albertel 7815: =cut
                   7816: 
1.334     albertel 7817: sub scantron_filter_not_exam {
                   7818:     my ($curres)=@_;
                   7819:     
                   7820:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7821: 	# if the user has asked to not have either hidden
                   7822: 	# or 'randomout' controlled resources to be graded
                   7823: 	# don't include them
                   7824: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7825: 	    && $curres->randomout) {
                   7826: 	    return 0;
                   7827: 	}
                   7828: 	return 1;
                   7829:     }
                   7830:     return 0;
                   7831: }
                   7832: 
1.423     albertel 7833: =pod
                   7834: 
                   7835: =item scantron_validate_sequence
                   7836: 
1.424     albertel 7837:     Validates the selected sequence, checking for resource that are
                   7838:     not set to exam mode.
                   7839: 
1.423     albertel 7840: =cut
                   7841: 
1.334     albertel 7842: sub scantron_validate_sequence {
                   7843:     my ($r,$currentphase) = @_;
                   7844: 
                   7845:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7846:     unless (ref($navmap)) {
                   7847:         $r->print(&navmap_errormsg());
                   7848:         return (1,$currentphase);
                   7849:     }
1.334     albertel 7850:     my (undef,undef,$sequence)=
                   7851: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7852: 
                   7853:     my $map=$navmap->getResourceByUrl($sequence);
                   7854: 
                   7855:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7856:                                     value="ignore" />');
                   7857:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7858: 	my @resources=
                   7859: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7860: 	if (@resources) {
1.675     bisitz   7861: 	    $r->print(
                   7862:                 '<p class="LC_warning">'
                   7863:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7864:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7865:                    .' work correctly.')
                   7866:                .'</p>'
                   7867:             );
1.334     albertel 7868: 	    return (1,$currentphase);
                   7869: 	}
                   7870:     }
                   7871: 
                   7872:     return (0,$currentphase+1);
                   7873: }
                   7874: 
1.423     albertel 7875: 
                   7876: 
1.157     albertel 7877: sub scantron_validate_ID {
1.770     raeburn  7878:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 7879:     
                   7880:     #get student info
                   7881:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7882:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  7883:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 7884: 
                   7885:     #get scantron line setup
1.754     raeburn  7886:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7887:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7888: 
                   7889:     my $nav_error;
1.649     raeburn  7890:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7891:     if ($nav_error) {
                   7892:         $r->print(&navmap_errormsg());
                   7893:         return(1,$currentphase);
                   7894:     }
1.157     albertel 7895: 
                   7896:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  7897:     my $unsavedskips = 0;
1.157     albertel 7898:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7899: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7900: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7901: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7902: 						 $scan_data);
                   7903: 	my $id=$$scan_record{'scantron.ID'};
                   7904: 	my $found;
                   7905: 	foreach my $checkid (keys(%idmap)) {
                   7906: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7907: 	}
                   7908: 	if ($found) {
                   7909: 	    my $username=$idmap{$found};
1.770     raeburn  7910:             if ($checksec) {
                   7911:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   7912:                     my $stusec = $classlist->{$username}->[$secidx];
                   7913:                     if ($stusec ne $checksec) {
                   7914:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7915:                             my $skip=1;
                   7916:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7917:                             if (ref($skipbysec) eq 'HASH') {
                   7918:                                 if ($stusec eq '') {
                   7919:                                     $skipbysec->{'none'} ++;
                   7920:                                 } else {
                   7921:                                     $skipbysec->{$stusec} ++;
                   7922:                                 }
                   7923:                             }
                   7924:                             $unsavedskips ++;
                   7925:                             next;
                   7926:                         }
                   7927:                     }
                   7928:                 }
                   7929:             }
1.157     albertel 7930: 	    if ($found{'ids'}{$found}) {
                   7931: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7932: 					 $line,'duplicateID',$found);
1.770     raeburn  7933:                 if ($unsavedskips) {
                   7934:                     &scantron_putfile($scanlines,$scan_data);
                   7935:                     $unsavedskips = 0;
                   7936:                 }
1.194     albertel 7937: 		return(1,$currentphase);
1.157     albertel 7938: 	    } elsif ($found{'usernames'}{$username}) {
                   7939: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7940: 					 $line,'duplicateID',$username);
1.770     raeburn  7941:                 if ($unsavedskips) {
                   7942:                     &scantron_putfile($scanlines,$scan_data);
                   7943:                     $unsavedskips = 0;
                   7944:                 }
1.194     albertel 7945: 		return(1,$currentphase);
1.157     albertel 7946: 	    }
1.186     albertel 7947: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7948: 	    $found{'ids'}{$found}++;
                   7949: 	    $found{'usernames'}{$username}++;
                   7950: 	} else {
                   7951: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7952: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  7953:                 if (($checksec && $username ne '')) {
                   7954:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   7955:                         my $stusec = $classlist->{$username}->[$secidx];
                   7956:                         if ($stusec ne $checksec) {
                   7957:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7958:                                 my $skip=1;
                   7959:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7960:                                 if (ref($skipbysec) eq 'HASH') {
                   7961:                                     if ($stusec eq '') {
                   7962:                                         $skipbysec->{'none'} ++;
                   7963:                                     } else {
                   7964:                                         $skipbysec->{$stusec} ++;
                   7965:                                     }
                   7966:                                 }
                   7967:                                 $unsavedskips ++;
                   7968:                                 next;
                   7969:                             }
                   7970:                         }
                   7971:                     }
                   7972: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 7973: 		    &scantron_get_correction($r,$i,$scan_record,
                   7974: 					     \%scantron_config,
                   7975: 					     $line,'duplicateID',$username);
1.770     raeburn  7976:                     if ($unsavedskips) {
                   7977:                         &scantron_putfile($scanlines,$scan_data);
                   7978:                         $unsavedskips = 0;
                   7979:                     }
1.194     albertel 7980: 		    return(1,$currentphase);
1.157     albertel 7981: 		} elsif (!defined($username)) {
                   7982: 		    &scantron_get_correction($r,$i,$scan_record,
                   7983: 					     \%scantron_config,
                   7984: 					     $line,'incorrectID');
1.770     raeburn  7985:                     if ($unsavedskips) {
                   7986:                         &scantron_putfile($scanlines,$scan_data);
                   7987:                         $unsavedskips = 0;
                   7988:                     }
1.194     albertel 7989: 		    return(1,$currentphase);
1.157     albertel 7990: 		}
                   7991: 		$found{'usernames'}{$username}++;
                   7992: 	    } else {
                   7993: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7994: 					 $line,'incorrectID');
1.770     raeburn  7995:                 if ($unsavedskips) {
                   7996:                     &scantron_putfile($scanlines,$scan_data);
                   7997:                     $unsavedskips = 0;
                   7998:                 }
1.194     albertel 7999: 		return(1,$currentphase);
1.157     albertel 8000: 	    }
                   8001: 	}
                   8002:     }
1.770     raeburn  8003:     if ($unsavedskips) {
                   8004:         &scantron_putfile($scanlines,$scan_data);
                   8005:         $unsavedskips = 0;
                   8006:     }
1.157     albertel 8007:     return (0,$currentphase+1);
                   8008: }
                   8009: 
1.770     raeburn  8010: sub scantron_get_sections {
                   8011:     my %bysec;
                   8012:     if ($env{'form.scantron_format'} ne '') {
                   8013:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   8014:         my ($scanlines,$scan_data)=&scantron_getfile();
                   8015:         my $classlist=&Apache::loncoursedata::get_classlist();
                   8016:         my %idmap=&username_to_idmap($classlist);
                   8017:         foreach my $key (keys(%idmap)) {
                   8018:             my $lckey = lc($key);
                   8019:             $idmap{$lckey} = $idmap{$key};
                   8020:         }
                   8021:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   8022:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   8023:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   8024:             if ($line=~/^[\s\cz]*$/) { next; }
                   8025:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8026:                                                      $scan_data);
                   8027:             my $id=lc($$scan_record{'scantron.ID'});
                   8028:             if (exists($idmap{$id})) {
                   8029:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   8030:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   8031:                     if ($stusec eq '') {
                   8032:                         $bysec{'none'} ++;
                   8033:                     } else {
                   8034:                         $bysec{$stusec} ++;
                   8035:                     }
                   8036:                 }
                   8037:             }
                   8038:         }
                   8039:     }
                   8040:     return %bysec;
                   8041: }
1.423     albertel 8042: 
1.157     albertel 8043: sub scantron_get_correction {
1.691     raeburn  8044:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   8045:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 8046: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 8047: #to show both the current line and the previous one and allow skipping
                   8048: #the previous one or the current one
                   8049: 
1.333     albertel 8050:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   8051:         $r->print(
                   8052:             '<p class="LC_warning">'
                   8053:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   8054:                 "<b>$error</b>",
                   8055:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   8056:            ."</p> \n");
1.157     albertel 8057:     } else {
1.658     bisitz   8058:         $r->print(
                   8059:             '<p class="LC_warning">'
                   8060:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8061:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8062:            ."</p> \n");
                   8063:     }
                   8064:     my $message =
                   8065:         '<p>'
                   8066:        .&mt('The ID on the form is [_1]',
                   8067:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8068:        .'<br />'
1.665     raeburn  8069:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   8070:             $$scan_record{'scantron.LastName'},
                   8071:             $$scan_record{'scantron.FirstName'})
                   8072:        .'</p>';
1.242     albertel 8073: 
1.157     albertel 8074:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8075:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8076:                            # Array populated for doublebubble or
                   8077:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8078:                            # to validate radio button checking   
                   8079: 
1.157     albertel 8080:     if ($error =~ /ID$/) {
1.186     albertel 8081: 	if ($error eq 'incorrectID') {
1.658     bisitz   8082:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8083: 		      "</p>\n");
1.157     albertel 8084: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   8085:             $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 8086: 	}
1.242     albertel 8087: 	$r->print($message);
1.492     albertel 8088: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8089: 	$r->print("\n<ul><li> ");
                   8090: 	#FIXME it would be nice if this sent back the user ID and
                   8091: 	#could do partial userID matches
                   8092: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8093: 				       'scantron_username','scantron_domain'));
                   8094: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   8095: 	$r->print("\n:\n".
1.257     albertel 8096: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8097: 
                   8098: 	$r->print('</li>');
1.186     albertel 8099:     } elsif ($error =~ /CODE$/) {
                   8100: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   8101: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8102: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   8103: 	    $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 8104: 	}
1.658     bisitz   8105: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   8106: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8107:                  ."</p>\n");
1.242     albertel 8108: 	$r->print($message);
1.658     bisitz   8109: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8110: 	$r->print("\n<br /> ");
1.194     albertel 8111: 	my $i=0;
1.273     albertel 8112: 	if ($error eq 'incorrectCODE' 
                   8113: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8114: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8115: 	    if ($closest > 0) {
                   8116: 		foreach my $testcode (@{$closest}) {
                   8117: 		    my $checked='';
1.569     bisitz   8118: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8119: 		    $r->print("
                   8120:    <label>
1.569     bisitz   8121:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8122:        ".&mt("Use the similar CODE [_1] instead.",
                   8123: 	    "<b><tt>".$testcode."</tt></b>")."
                   8124:     </label>
                   8125:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8126: 		    $r->print("\n<br />");
                   8127: 		    $i++;
                   8128: 		}
1.194     albertel 8129: 	    }
                   8130: 	}
1.273     albertel 8131: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8132: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8133: 	    $r->print("
                   8134:     <label>
1.569     bisitz   8135:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  8136:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8137: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8138:     </label>");
1.273     albertel 8139: 	    $r->print("\n<br />");
                   8140: 	}
1.194     albertel 8141: 
1.597     wenzelju 8142: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8143: function change_radio(field) {
1.190     albertel 8144:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8145:     var i;
                   8146:     for (i=0;i<slct.length;i++) {
                   8147:         if (slct[i].value==field) { slct[i].checked=true; }
                   8148:     }
                   8149: }
                   8150: ENDSCRIPT
1.187     albertel 8151: 	my $href="/adm/pickcode?".
1.359     www      8152: 	   "form=".&escape("scantronupload").
                   8153: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8154: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8155: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8156: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8157: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8158: 	    $r->print("
                   8159:     <label>
                   8160:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8161:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8162: 	     "<a target='_blank' href='$href'>","</a>")."
                   8163:     </label> 
1.558     bisitz   8164:     ".&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 8165: 	    $r->print("\n<br />");
                   8166: 	}
1.492     albertel 8167: 	$r->print("
                   8168:     <label>
                   8169:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8170:        ".&mt("Use [_1] as the CODE.",
                   8171: 	     "</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 8172: 	$r->print("\n<br /><br />");
1.157     albertel 8173:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   8174: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8175: 
                   8176: 	# The form field scantron_questions is acutally a list of line numbers.
                   8177: 	# represented by this form so:
                   8178: 
1.691     raeburn  8179: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8180:                                                 $respnumlookup,$startline);
1.497     foxr     8181: 
1.157     albertel 8182: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8183: 		  $line_list.'" />');
1.242     albertel 8184: 	$r->print($message);
1.492     albertel 8185: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8186: 	foreach my $question (@{$arg}) {
1.503     raeburn  8187: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8188:                                                    $scan_record, $error,
                   8189:                                                    $randomorder,$randompick,
                   8190:                                                    $respnumlookup,$startline);
1.524     raeburn  8191:             push(@lines_to_correct,@linenums);
1.157     albertel 8192: 	}
1.503     raeburn  8193:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8194:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   8195: 	$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 8196: 	$r->print($message);
1.492     albertel 8197: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8198: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8199: 
1.503     raeburn  8200: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8201: 	# a list of question numbers. Therefore:
                   8202: 	#
1.691     raeburn  8203: 
                   8204: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8205:                                                 $respnumlookup,$startline);
1.497     foxr     8206: 
1.157     albertel 8207: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8208: 		  $line_list.'" />');
1.157     albertel 8209: 	foreach my $question (@{$arg}) {
1.503     raeburn  8210: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8211:                                                    $scan_record, $error,
                   8212:                                                    $randomorder,$randompick,
                   8213:                                                    $respnumlookup,$startline);
1.524     raeburn  8214:             push(@lines_to_correct,@linenums);
1.157     albertel 8215: 	}
1.503     raeburn  8216:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8217:     } else {
                   8218: 	$r->print("\n<ul>");
                   8219:     }
                   8220:     $r->print("\n</li></ul>");
1.497     foxr     8221: }
                   8222: 
1.503     raeburn  8223: sub verify_bubbles_checked {
                   8224:     my (@ansnums) = @_;
                   8225:     my $ansnumstr = join('","',@ansnums);
                   8226:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  8227:     &js_escape(\$warning);
1.767     raeburn  8228:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8229: function verify_bubble_radio(form) {
                   8230:     var ansnumArray = new Array ("$ansnumstr");
                   8231:     var need_bubble_count = 0;
                   8232:     for (var i=0; i<ansnumArray.length; i++) {
                   8233:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8234:             var bubble_picked = 0; 
                   8235:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8236:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8237:                     bubble_picked = 1;
                   8238:                 }
                   8239:             }
                   8240:             if (bubble_picked == 0) {
                   8241:                 need_bubble_count ++;
                   8242:             }
                   8243:         }
                   8244:     }
                   8245:     if (need_bubble_count) {
                   8246:         alert("$warning");
                   8247:         return;
                   8248:     }
                   8249:     form.submit(); 
                   8250: }
                   8251: ENDSCRIPT
                   8252:     return $output;
                   8253: }
                   8254: 
1.497     foxr     8255: =pod
                   8256: 
                   8257: =item  questions_to_line_list
1.157     albertel 8258: 
1.497     foxr     8259: Converts a list of questions into a string of comma separated
                   8260: line numbers in the answer sheet used by the questions.  This is
                   8261: used to fill in the scantron_questions form field.
                   8262: 
                   8263:   Arguments:
                   8264:      questions    - Reference to an array of questions.
1.691     raeburn  8265:      randomorder  - True if randomorder in use.
                   8266:      randompick   - True if randompick in use.
                   8267:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8268:                      for current line to question number used for same question
                   8269:                      in "Master Seqence" (as seen by Course Coordinator).
                   8270:      startline    - Reference to hash where key is question number (0 is first)
                   8271:                     and key is number of first bubble line for current student
                   8272:                     or code-based randompick and/or randomorder.
1.693     raeburn  8273: 
1.497     foxr     8274: =cut
                   8275: 
                   8276: 
                   8277: sub questions_to_line_list {
1.691     raeburn  8278:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8279:     my @lines;
                   8280: 
1.503     raeburn  8281:     foreach my $item (@{$questions}) {
                   8282:         my $question = $item;
                   8283:         my ($first,$count,$last);
                   8284:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8285:             $question = $1;
                   8286:             my $subquestion = $2;
1.691     raeburn  8287:             my $responsenum = $question-1;
                   8288:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8289:                 $responsenum = $respnumlookup->{$question-1};
                   8290:                 if (ref($startline) eq 'HASH') {
                   8291:                     $first = $startline->{$question-1} + 1;
                   8292:                 }
                   8293:             } else {
                   8294:                 $first = $first_bubble_line{$responsenum} + 1;
                   8295:             }
                   8296:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8297:             my $subcount = 1;
                   8298:             while ($subcount<$subquestion) {
                   8299:                 $first += $subans[$subcount-1];
                   8300:                 $subcount ++;
                   8301:             }
                   8302:             $count = $subans[$subquestion-1];
                   8303:         } else {
1.691     raeburn  8304:             my $responsenum = $question-1;
                   8305:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8306:                 $responsenum = $respnumlookup->{$question-1};
                   8307:                 if (ref($startline) eq 'HASH') {
                   8308:                     $first = $startline->{$question-1} + 1;
                   8309:                 }
                   8310:             } else {
                   8311:                 $first = $first_bubble_line{$responsenum} + 1;
                   8312:             }
                   8313: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8314:         }
1.506     raeburn  8315:         $last = $first+$count-1;
1.503     raeburn  8316:         push(@lines, ($first..$last));
1.497     foxr     8317:     }
                   8318:     return join(',', @lines);
                   8319: }
                   8320: 
                   8321: =pod 
                   8322: 
                   8323: =item prompt_for_corrections
                   8324: 
                   8325: Prompts for a potentially multiline correction to the
                   8326: user's bubbling (factors out common code from scantron_get_correction
                   8327: for multi and missing bubble cases).
                   8328: 
                   8329:  Arguments:
                   8330:    $r           - Apache request object.
                   8331:    $question    - The question number to prompt for.
                   8332:    $scan_config - The scantron file configuration hash.
                   8333:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8334:    $error       - Type of error
1.691     raeburn  8335:    $randomorder - True if randomorder in use.
                   8336:    $randompick  - True if randompick in use.
                   8337:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8338:                     for current line to question number used for same question
                   8339:                     in "Master Seqence" (as seen by Course Coordinator).
                   8340:    $startline   - Reference to hash where key is question number (0 is first)
                   8341:                   and value is number of first bubble line for current student
                   8342:                   or code-based randompick and/or randomorder.
                   8343: 
1.497     foxr     8344: 
                   8345:  Implicit inputs:
                   8346:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8347:                                   Numbered from 0 (but question numbers are from
                   8348:                                   1.
                   8349:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8350:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8351:                                   type problems render as separate sub-questions, 
1.503     raeburn  8352:                                   in exam mode. This hash contains a 
                   8353:                                   comma-separated list of the lines per 
                   8354:                                   sub-question.
1.510     raeburn  8355:    %responsetype_per_response   - essayresponse, formularesponse,
                   8356:                                   stringresponse, imageresponse, reactionresponse,
                   8357:                                   and organicresponse type problem parts can have
1.503     raeburn  8358:                                   multiple lines per response if the weight
                   8359:                                   assigned exceeds 10.  In this case, only
                   8360:                                   one bubble per line is permitted, but more 
                   8361:                                   than one line might contain bubbles, e.g.
                   8362:                                   bubbling of: line 1 - J, line 2 - J, 
                   8363:                                   line 3 - B would assign 22 points.  
1.497     foxr     8364: 
                   8365: =cut
                   8366: 
                   8367: sub prompt_for_corrections {
1.691     raeburn  8368:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8369:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8370:     my ($current_line,$lines);
                   8371:     my @linenums;
                   8372:     my $questionnum = $question;
1.691     raeburn  8373:     my ($first,$responsenum);
1.503     raeburn  8374:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8375:         $question = $1;
                   8376:         my $subquestion = $2;
1.691     raeburn  8377:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8378:             $responsenum = $respnumlookup->{$question-1};
                   8379:             if (ref($startline) eq 'HASH') {
                   8380:                 $first = $startline->{$question-1};
                   8381:             }
                   8382:         } else {
                   8383:             $responsenum = $question-1;
1.714     raeburn  8384:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8385:         }
                   8386:         $current_line = $first + 1 ;
                   8387:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8388:         my $subcount = 1;
                   8389:         while ($subcount<$subquestion) {
                   8390:             $current_line += $subans[$subcount-1];
                   8391:             $subcount ++;
                   8392:         }
                   8393:         $lines = $subans[$subquestion-1];
                   8394:     } else {
1.691     raeburn  8395:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8396:             $responsenum = $respnumlookup->{$question-1};
                   8397:             if (ref($startline) eq 'HASH') { 
                   8398:                 $first = $startline->{$question-1};
                   8399:             }
                   8400:         } else {
                   8401:             $responsenum = $question-1;
                   8402:             $first = $first_bubble_line{$responsenum};
                   8403:         }
                   8404:         $current_line = $first + 1;
                   8405:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8406:     }
1.497     foxr     8407:     if ($lines > 1) {
1.503     raeburn  8408:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8409:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8410:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8411:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8412:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8413:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8414:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8415:             $r->print(
                   8416:                 &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)
                   8417:                .'<br /><br />'
                   8418:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8419:                .'<br />'
                   8420:                .&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.')
                   8421:                .'<br />'
                   8422:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8423:                .'<br /><br />'
                   8424:             );
1.503     raeburn  8425:         } else {
                   8426:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8427:         }
1.497     foxr     8428:     }
                   8429:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8430:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8431: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8432: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8433:         push(@linenums,$current_line);
1.497     foxr     8434: 	$current_line++;
                   8435:     }
                   8436:     if ($lines > 1) {
                   8437: 	$r->print("<hr /><br />");
                   8438:     }
1.503     raeburn  8439:     return @linenums;
1.157     albertel 8440: }
1.423     albertel 8441: 
                   8442: =pod
                   8443: 
                   8444: =item scantron_bubble_selector
                   8445:   
                   8446:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8447:    possibly showing the existing the selected bubbles if known
1.423     albertel 8448: 
                   8449:  Arguments:
                   8450:     $r           - Apache request object
1.754     raeburn  8451:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8452:     $line        - Number of the line being displayed.
1.503     raeburn  8453:     $questionnum - Question number (may include subquestion)
                   8454:     $error       - Type of error.
1.497     foxr     8455:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8456: 
                   8457: =cut
                   8458: 
1.157     albertel 8459: sub scantron_bubble_selector {
1.503     raeburn  8460:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8461:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8462: 
                   8463:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8464:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8465:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8466:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8467:             $max=$$scan_config{'BubblesPerRow'};
                   8468:             if (($scmode eq 'number') && ($max > 10)) {
                   8469:                 $max = 10;
                   8470:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8471:                 $max = 26;
                   8472:             }
                   8473:         } else {
                   8474:             $max = 10;
                   8475:         }
                   8476:     }
1.274     albertel 8477: 
1.157     albertel 8478:     my @alphabet=('A'..'Z');
1.503     raeburn  8479:     $r->print(&Apache::loncommon::start_data_table().
                   8480:               &Apache::loncommon::start_data_table_row());
                   8481:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8482:     for (my $i=0;$i<$max+1;$i++) {
                   8483: 	$r->print("\n".'<td align="center">');
                   8484: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8485: 	else { $r->print('&nbsp;'); }
                   8486: 	$r->print('</td>');
                   8487:     }
1.503     raeburn  8488:     $r->print(&Apache::loncommon::end_data_table_row().
                   8489:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8490:     for (my $i=0;$i<$max;$i++) {
                   8491: 	$r->print("\n".
                   8492: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8493: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8494:     }
1.503     raeburn  8495:     my $nobub_checked = ' ';
                   8496:     if ($error eq 'missingbubble') {
                   8497:         $nobub_checked = ' checked = "checked" ';
                   8498:     }
                   8499:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8500: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8501:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8502:               $line.'" value="'.$questionnum.'" /></td>');
                   8503:     $r->print(&Apache::loncommon::end_data_table_row().
                   8504:               &Apache::loncommon::end_data_table());
1.157     albertel 8505: }
                   8506: 
1.423     albertel 8507: =pod
                   8508: 
                   8509: =item num_matches
                   8510: 
1.424     albertel 8511:    Counts the number of characters that are the same between the two arguments.
                   8512: 
                   8513:  Arguments:
                   8514:    $orig - CODE from the scanline
                   8515:    $code - CODE to match against
                   8516: 
                   8517:  Returns:
                   8518:    $count - integer count of the number of same characters between the
                   8519:             two arguments
                   8520: 
1.423     albertel 8521: =cut
                   8522: 
1.194     albertel 8523: sub num_matches {
                   8524:     my ($orig,$code) = @_;
                   8525:     my @code=split(//,$code);
                   8526:     my @orig=split(//,$orig);
                   8527:     my $same=0;
                   8528:     for (my $i=0;$i<scalar(@code);$i++) {
                   8529: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8530:     }
                   8531:     return $same;
                   8532: }
                   8533: 
1.423     albertel 8534: =pod
                   8535: 
                   8536: =item scantron_get_closely_matching_CODEs
                   8537: 
1.424     albertel 8538:    Cycles through all CODEs and finds the set that has the greatest
                   8539:    number of same characters as the provided CODE
                   8540: 
                   8541:  Arguments:
                   8542:    $allcodes - hash ref returned by &get_codes()
                   8543:    $CODE     - CODE from the current scanline
                   8544: 
                   8545:  Returns:
                   8546:    2 element list
                   8547:     - first elements is number of how closely matching the best fit is 
                   8548:       (5 means best set has 5 matching characters)
                   8549:     - second element is an arrary ref containing the set of valid CODEs
                   8550:       that best fit the passed in CODE
                   8551: 
1.423     albertel 8552: =cut
                   8553: 
1.194     albertel 8554: sub scantron_get_closely_matching_CODEs {
                   8555:     my ($allcodes,$CODE)=@_;
                   8556:     my @CODEs;
                   8557:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8558: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8559:     }
                   8560: 
                   8561:     return ($#CODEs,$CODEs[-1]);
                   8562: }
                   8563: 
1.423     albertel 8564: =pod
                   8565: 
                   8566: =item get_codes
                   8567: 
1.424     albertel 8568:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8569:    set of remembered CODEs.
                   8570: 
                   8571:  Arguments:
                   8572:   $old_name - name of the set of remembered CODEs
                   8573:   $cdom     - domain of the course
                   8574:   $cnum     - internal course name
                   8575: 
                   8576:  Returns:
                   8577:   %allcodes - keys are the valid CODEs, values are all 1
                   8578: 
1.423     albertel 8579: =cut
                   8580: 
1.194     albertel 8581: sub get_codes {
1.280     foxr     8582:     my ($old_name, $cdom, $cnum) = @_;
                   8583:     if (!$old_name) {
                   8584: 	$old_name=$env{'form.scantron_CODElist'};
                   8585:     }
                   8586:     if (!$cdom) {
                   8587: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8588:     }
                   8589:     if (!$cnum) {
                   8590: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8591:     }
1.278     albertel 8592:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8593: 				    $cdom,$cnum);
                   8594:     my %allcodes;
                   8595:     if ($result{"type\0$old_name"} eq 'number') {
                   8596: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8597:     } else {
                   8598: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8599:     }
1.194     albertel 8600:     return %allcodes;
                   8601: }
                   8602: 
1.423     albertel 8603: =pod
                   8604: 
                   8605: =item scantron_validate_CODE
                   8606: 
1.424     albertel 8607:    Validates all scanlines in the selected file to not have any
                   8608:    invalid or underspecified CODEs and that none of the codes are
                   8609:    duplicated if this was requested.
                   8610: 
1.423     albertel 8611: =cut
                   8612: 
1.157     albertel 8613: sub scantron_validate_CODE {
                   8614:     my ($r,$currentphase) = @_;
1.754     raeburn  8615:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8616:     if ($scantron_config{'CODElocation'} &&
                   8617: 	$scantron_config{'CODEstart'} &&
                   8618: 	$scantron_config{'CODElength'}) {
1.257     albertel 8619: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8620: 	    &FIXME_blow_up()
                   8621: 	}
                   8622:     } else {
                   8623: 	return (0,$currentphase+1);
                   8624:     }
                   8625:     
                   8626:     my %usedCODEs;
                   8627: 
1.194     albertel 8628:     my %allcodes=&get_codes();
1.186     albertel 8629: 
1.582     raeburn  8630:     my $nav_error;
1.649     raeburn  8631:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8632:     if ($nav_error) {
                   8633:         $r->print(&navmap_errormsg());
                   8634:         return(1,$currentphase);
                   8635:     }
1.447     foxr     8636: 
1.186     albertel 8637:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8638:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8639: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8640: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8641: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8642: 						 $scan_data);
                   8643: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8644: 	my $error=0;
1.224     albertel 8645: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8646: 	    &scantron_get_correction($r,$i,$scan_record,
                   8647: 				     \%scantron_config,
                   8648: 				     $line,'incorrectCODE',\%allcodes);
                   8649: 	    return(1,$currentphase);
                   8650: 	}
1.221     albertel 8651: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8652: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8653: 	    &scantron_get_correction($r,$i,$scan_record,
                   8654: 				     \%scantron_config,
1.194     albertel 8655: 				     $line,'incorrectCODE',\%allcodes);
                   8656: 	    return(1,$currentphase);
1.186     albertel 8657: 	}
1.214     albertel 8658: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8659: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8660: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8661: 	    &scantron_get_correction($r,$i,$scan_record,
                   8662: 				     \%scantron_config,
1.194     albertel 8663: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8664: 	    return(1,$currentphase);
1.186     albertel 8665: 	}
1.524     raeburn  8666: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8667:     }
1.157     albertel 8668:     return (0,$currentphase+1);
                   8669: }
                   8670: 
1.423     albertel 8671: =pod
                   8672: 
                   8673: =item scantron_validate_doublebubble
                   8674: 
1.424     albertel 8675:    Validates all scanlines in the selected file to not have any
                   8676:    bubble lines with multiple bubbles marked.
                   8677: 
1.423     albertel 8678: =cut
                   8679: 
1.157     albertel 8680: sub scantron_validate_doublebubble {
                   8681:     my ($r,$currentphase) = @_;
                   8682:     #get student info
                   8683:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8684:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8685:     my (undef,undef,$sequence)=
                   8686:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8687: 
                   8688:     #get scantron line setup
1.754     raeburn  8689:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8690:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8691: 
                   8692:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8693:     unless (ref($navmap)) {
                   8694:         $r->print(&navmap_errormsg());
                   8695:         return(1,$currentphase);
                   8696:     }
                   8697:     my $map=$navmap->getResourceByUrl($sequence);
                   8698:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8699:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8700:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8701:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8702: 
1.583     raeburn  8703:     my $nav_error;
1.691     raeburn  8704:     if (ref($map)) {
                   8705:         $randomorder = $map->randomorder();
                   8706:         $randompick = $map->randompick();
                   8707:         if ($randomorder || $randompick) {
                   8708:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8709:             if ($nav_error) {
                   8710:                 $r->print(&navmap_errormsg());
                   8711:                 return(1,$currentphase);
                   8712:             }
                   8713:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8714:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8715:         }
                   8716:     } else {
                   8717:         $r->print(&navmap_errormsg());
                   8718:         return(1,$currentphase);
                   8719:     }
                   8720: 
1.649     raeburn  8721:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8722:     if ($nav_error) {
                   8723:         $r->print(&navmap_errormsg());
                   8724:         return(1,$currentphase);
                   8725:     }
1.447     foxr     8726: 
1.157     albertel 8727:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8728: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8729: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8730: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8731: 						 $scan_data,undef,\%idmap,$randomorder,
                   8732:                                                  $randompick,$sequence,\@master_seq,
                   8733:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8734:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8735: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8736: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8737: 				 'doublebubble',
1.691     raeburn  8738: 				 $$scan_record{'scantron.doubleerror'},
                   8739:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8740:     	return (1,$currentphase);
                   8741:     }
                   8742:     return (0,$currentphase+1);
                   8743: }
                   8744: 
1.423     albertel 8745: 
1.503     raeburn  8746: sub scantron_get_maxbubble {
1.649     raeburn  8747:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8748:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8749: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8750: 	&restore_bubble_lines();
1.257     albertel 8751: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8752:     }
1.330     albertel 8753: 
1.447     foxr     8754:     my (undef, undef, $sequence) =
1.257     albertel 8755: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8756: 
1.447     foxr     8757:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8758:     unless (ref($navmap)) {
                   8759:         if (ref($nav_error)) {
                   8760:             $$nav_error = 1;
                   8761:         }
1.591     raeburn  8762:         return;
1.582     raeburn  8763:     }
1.191     albertel 8764:     my $map=$navmap->getResourceByUrl($sequence);
                   8765:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8766:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8767: 
                   8768:     &Apache::lonxml::clear_problem_counter();
                   8769: 
1.557     raeburn  8770:     my $uname       = $env{'user.name'};
                   8771:     my $udom        = $env{'user.domain'};
1.435     foxr     8772:     my $cid         = $env{'request.course.id'};
                   8773:     my $total_lines = 0;
                   8774:     %bubble_lines_per_response = ();
1.447     foxr     8775:     %first_bubble_line         = ();
1.503     raeburn  8776:     %subdivided_bubble_lines   = ();
                   8777:     %responsetype_per_response = ();
1.691     raeburn  8778:     %masterseq_id_responsenum  = ();
1.554     raeburn  8779: 
1.447     foxr     8780:     my $response_number = 0;
                   8781:     my $bubble_line     = 0;
1.191     albertel 8782:     foreach my $resource (@resources) {
1.691     raeburn  8783:         my $resid = $resource->id(); 
1.672     raeburn  8784:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8785:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8786:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8787: 	    foreach my $part_id (@{$parts}) {
                   8788:                 my $lines;
                   8789: 
                   8790: 	        # TODO - make this a persistent hash not an array.
                   8791: 
                   8792:                 # optionresponse, matchresponse and rankresponse type items 
                   8793:                 # render as separate sub-questions in exam mode.
                   8794:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8795:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8796:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8797:                     my ($numbub,$numshown);
                   8798:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8799:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8800:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8801:                         }
                   8802:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8803:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8804:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8805:                         }
                   8806:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8807:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8808:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8809:                         }
                   8810:                     }
                   8811:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8812:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8813:                     }
1.649     raeburn  8814:                     my $bubbles_per_row =
                   8815:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8816:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8817:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8818:                         $inner_bubble_lines++;
                   8819:                     }
                   8820:                     for (my $i=0; $i<$numshown; $i++) {
                   8821:                         $subdivided_bubble_lines{$response_number} .= 
                   8822:                             $inner_bubble_lines.',';
                   8823:                     }
                   8824:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8825:                     $lines = $numshown * $inner_bubble_lines;
                   8826:                 } else {
                   8827:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8828:                 }
1.542     raeburn  8829: 
                   8830:                 $first_bubble_line{$response_number} = $bubble_line;
                   8831: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8832:                 $responsetype_per_response{$response_number} = 
                   8833:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8834:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8835: 	        $response_number++;
                   8836: 
                   8837: 	        $bubble_line +=  $lines;
                   8838: 	        $total_lines +=  $lines;
                   8839: 	    }
                   8840:         }
                   8841:     }
1.552     raeburn  8842:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8843: 
                   8844:     &save_bubble_lines();
                   8845:     $env{'form.scantron_maxbubble'} =
                   8846: 	$total_lines;
                   8847:     return $env{'form.scantron_maxbubble'};
                   8848: }
1.523     raeburn  8849: 
1.649     raeburn  8850: sub bubblesheet_bubbles_per_row {
                   8851:     my ($scantron_config) = @_;
                   8852:     my $bubbles_per_row;
                   8853:     if (ref($scantron_config) eq 'HASH') {
                   8854:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8855:     }
                   8856:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8857:         $bubbles_per_row = 10;
                   8858:     }
                   8859:     return $bubbles_per_row;
                   8860: }
                   8861: 
1.157     albertel 8862: sub scantron_validate_missingbubbles {
                   8863:     my ($r,$currentphase) = @_;
                   8864:     #get student info
                   8865:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8866:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8867:     my (undef,undef,$sequence)=
                   8868:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8869: 
                   8870:     #get scantron line setup
1.754     raeburn  8871:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8872:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8873: 
                   8874:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8875:     unless (ref($navmap)) {
                   8876:         $r->print(&navmap_errormsg());
                   8877:         return(1,$currentphase);
                   8878:     }
                   8879: 
                   8880:     my $map=$navmap->getResourceByUrl($sequence);
                   8881:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8882:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8883:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8884:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8885: 
1.582     raeburn  8886:     my $nav_error;
1.691     raeburn  8887:     if (ref($map)) {
                   8888:         $randomorder = $map->randomorder();
                   8889:         $randompick = $map->randompick();
                   8890:         if ($randomorder || $randompick) {
                   8891:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8892:             if ($nav_error) {
                   8893:                 $r->print(&navmap_errormsg());
                   8894:                 return(1,$currentphase);
                   8895:             }
                   8896:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8897:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8898:         }
                   8899:     } else {
                   8900:         $r->print(&navmap_errormsg());
                   8901:         return(1,$currentphase);
                   8902:     }
                   8903: 
                   8904: 
1.649     raeburn  8905:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8906:     if ($nav_error) {
1.691     raeburn  8907:         $r->print(&navmap_errormsg());
1.693     raeburn  8908:         return(1,$currentphase);
1.582     raeburn  8909:     }
1.691     raeburn  8910: 
1.157     albertel 8911:     if (!$max_bubble) { $max_bubble=2**31; }
                   8912:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8913: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8914: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8915: 	my $scan_record =
                   8916:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8917: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8918:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8919:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8920: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8921: 	my @to_correct;
1.470     foxr     8922: 	
                   8923: 	# Probably here's where the error is...
                   8924: 
1.157     albertel 8925: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8926:             my $lastbubble;
                   8927:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8928:                my $question = $1;
                   8929:                my $subquestion = $2;
1.691     raeburn  8930:                my ($first,$responsenum);
                   8931:                if ($randomorder || $randompick) {
                   8932:                    $responsenum = $respnumlookup{$question-1};
                   8933:                    $first = $startline{$question-1};
                   8934:                } else {
                   8935:                    $responsenum = $question-1; 
                   8936:                    $first = $first_bubble_line{$responsenum};
                   8937:                }
                   8938:                if (!defined($first)) { next; }
                   8939:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8940:                my $subcount = 1;
                   8941:                while ($subcount<$subquestion) {
                   8942:                    $first += $subans[$subcount-1];
                   8943:                    $subcount ++;
                   8944:                }
                   8945:                my $count = $subans[$subquestion-1];
                   8946:                $lastbubble = $first + $count;
                   8947:             } else {
1.691     raeburn  8948:                my ($first,$responsenum);
                   8949:                if ($randomorder || $randompick) {
                   8950:                    $responsenum = $respnumlookup{$missing-1};
                   8951:                    $first = $startline{$missing-1};
                   8952:                } else {
                   8953:                    $responsenum = $missing-1;
                   8954:                    $first = $first_bubble_line{$responsenum};
                   8955:                }
                   8956:                if (!defined($first)) { next; }
                   8957:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8958:             }
                   8959:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8960: 	    push(@to_correct,$missing);
                   8961: 	}
                   8962: 	if (@to_correct) {
                   8963: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8964: 				     $line,'missingbubble',\@to_correct,
                   8965:                                      $randomorder,$randompick,\%respnumlookup,
                   8966:                                      \%startline);
1.157     albertel 8967: 	    return (1,$currentphase);
                   8968: 	}
                   8969: 
                   8970:     }
                   8971:     return (0,$currentphase+1);
                   8972: }
                   8973: 
1.663     raeburn  8974: sub hand_bubble_option {
                   8975:     my (undef, undef, $sequence) =
                   8976:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8977:     return if ($sequence eq '');
                   8978:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8979:     unless (ref($navmap)) {
                   8980:         return;
                   8981:     }
                   8982:     my $needs_hand_bubbles;
                   8983:     my $map=$navmap->getResourceByUrl($sequence);
                   8984:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8985:     foreach my $res (@resources) {
                   8986:         if (ref($res)) {
                   8987:             if ($res->is_problem()) {
                   8988:                 my $partlist = $res->parts();
                   8989:                 foreach my $part (@{ $partlist }) {
                   8990:                     my @types = $res->responseType($part);
                   8991:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8992:                         $needs_hand_bubbles = 1;
                   8993:                         last;
                   8994:                     }
                   8995:                 }
                   8996:             }
                   8997:         }
                   8998:     }
                   8999:     if ($needs_hand_bubbles) {
1.754     raeburn  9000:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  9001:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   9002:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   9003:                &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 />').
                   9004:                '<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  9005:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  9006:     }
                   9007:     return;
                   9008: }
1.423     albertel 9009: 
1.82      albertel 9010: sub scantron_process_students {
1.608     www      9011:     my ($r,$symb) = @_;
1.513     foxr     9012: 
1.257     albertel 9013:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     9014:     if (!$symb) {
                   9015: 	return '';
                   9016:     }
1.324     albertel 9017:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 9018: 
1.754     raeburn  9019:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  9020:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 9021:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 9022:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9023:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 9024:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9025:     unless (ref($navmap)) {
                   9026:         $r->print(&navmap_errormsg());
                   9027:         return '';
1.691     raeburn  9028:     }
1.83      albertel 9029:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9030:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  9031:         %grader_randomlists_by_symb);
1.677     raeburn  9032:     if (ref($map)) {
                   9033:         $randomorder = $map->randomorder();
1.689     raeburn  9034:         $randompick = $map->randompick();
1.691     raeburn  9035:     } else {
                   9036:         $r->print(&navmap_errormsg());
                   9037:         return '';
1.677     raeburn  9038:     }
1.691     raeburn  9039:     my $nav_error;
1.83      albertel 9040:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9041:     if ($randomorder || $randompick) {
                   9042:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9043:         if ($nav_error) {
                   9044:             $r->print(&navmap_errormsg());
                   9045:             return '';
                   9046:         }
                   9047:     }
1.557     raeburn  9048:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  9049:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  9050: 
1.554     raeburn  9051:     my ($uname,$udom);
1.82      albertel 9052:     my $result= <<SCANTRONFORM;
1.81      albertel 9053: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   9054:   <input type="hidden" name="command" value="scantron_configphase" />
                   9055:   $default_form_data
                   9056: SCANTRONFORM
1.82      albertel 9057:     $r->print($result);
                   9058: 
1.770     raeburn  9059:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 9060:     my @delayqueue;
1.542     raeburn  9061:     my (%completedstudents,%scandata);
1.770     raeburn  9062: 
1.520     www      9063:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9064:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9065:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   9066:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9067:     $r->print('<br />');
1.140     albertel 9068:     my $start=&Time::HiRes::time();
1.158     albertel 9069:     my $i=-1;
1.542     raeburn  9070:     my $started;
1.447     foxr     9071: 
1.649     raeburn  9072:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9073:     if ($nav_error) {
                   9074:         $r->print(&navmap_errormsg());
                   9075:         return '';
                   9076:     }
                   9077: 
1.513     foxr     9078:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9079:     # the user and return.
                   9080: 
                   9081:     if ($ssi_error) {
                   9082: 	$r->print("</form>");
                   9083: 	&ssi_print_error($r);
1.520     www      9084:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9085: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9086:     }
1.447     foxr     9087: 
1.755     raeburn  9088:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9089:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  9090:     my %orderedforcode;
1.542     raeburn  9091: 
1.157     albertel 9092:     while ($i<$scanlines->{'count'}) {
                   9093:  	($uname,$udom)=('','');
                   9094:  	$i++;
1.200     albertel 9095:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9096:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9097: 	if ($started) {
1.667     www      9098: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9099: 	}
                   9100: 	$started=1;
1.691     raeburn  9101:         my %respnumlookup = ();
                   9102:         my %startline = ();
                   9103:         my $total;
1.157     albertel 9104:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9105:                                                  $scan_data,undef,\%idmap,$randomorder,
                   9106:                                                  $randompick,$sequence,\@master_seq,
                   9107:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9108:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9109:                                                  \$total);
1.157     albertel 9110:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9111:  					      \%idmap,$i)) {
                   9112:   	    &scantron_add_delay(\@delayqueue,$line,
                   9113:  				'Unable to find a student that matches',1);
                   9114:  	    next;
                   9115:   	}
                   9116:  	if (exists $completedstudents{$uname}) {
                   9117:  	    &scantron_add_delay(\@delayqueue,$line,
                   9118:  				'Student '.$uname.' has multiple sheets',2);
                   9119:  	    next;
                   9120:  	}
1.677     raeburn  9121:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  9122:         if (($checksec ne '') && ($checksec ne $usec)) {
                   9123:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   9124:                 &scantron_add_delay(\@delayqueue,$line,
                   9125:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   9126:                 next;
                   9127:             }
                   9128:         }
1.677     raeburn  9129:         my $user = $uname.':'.$usec;
1.157     albertel 9130:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9131: 
1.677     raeburn  9132:         my $scancode;
                   9133:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9134:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9135:             $scancode = $scan_record->{'scantron.CODE'};
                   9136:         } else {
                   9137:             $scancode = '';
                   9138:         }
                   9139: 
                   9140:         my @mapresources = @resources;
1.689     raeburn  9141:         if ($randomorder || $randompick) {
1.678     raeburn  9142:             @mapresources = 
1.691     raeburn  9143:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9144:                              \%orderedforcode);
1.677     raeburn  9145:         }
1.586     raeburn  9146:         my (%partids_by_symb,$res_error);
1.677     raeburn  9147:         foreach my $resource (@mapresources) {
1.586     raeburn  9148:             my $ressymb;
                   9149:             if (ref($resource)) {
                   9150:                 $ressymb = $resource->symb();
                   9151:             } else {
                   9152:                 $res_error = 1;
                   9153:                 last;
                   9154:             }
1.557     raeburn  9155:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9156:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9157:                 my $currcode;
                   9158:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9159:                     $currcode = $scancode;
                   9160:                 }
1.557     raeburn  9161:                 my ($analysis,$parts) =
1.672     raeburn  9162:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  9163:                                               $uname,$udom,undef,$bubbles_per_row,
                   9164:                                               $currcode);
1.557     raeburn  9165:                 $partids_by_symb{$ressymb} = $parts;
                   9166:             } else {
                   9167:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9168:             }
1.554     raeburn  9169:         }
                   9170: 
1.586     raeburn  9171:         if ($res_error) {
                   9172:             &scantron_add_delay(\@delayqueue,$line,
                   9173:                                 'An error occurred while grading student '.$uname,2);
                   9174:             next;
                   9175:         }
                   9176: 
1.330     albertel 9177: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9178:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9179: 
                   9180: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9181: 	    &scantron_putfile($scanlines,$scan_data);
                   9182: 	}
1.161     albertel 9183: 	
1.542     raeburn  9184:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9185:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  9186:                                    $bubbles_per_row,$randomorder,$randompick,
                   9187:                                    \%respnumlookup,\%startline) 
                   9188:             eq 'ssi_error') {
1.542     raeburn  9189:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9190:             $r->print("</form>");
                   9191:             &ssi_print_error($r);
                   9192:             &Apache::lonnet::remove_lock($lock);
                   9193:             return '';      # Why return ''?  Beats me.
                   9194:         }
1.513     foxr     9195: 
1.692     raeburn  9196:         if (($scancode) && ($randomorder || $randompick)) {
                   9197:             my $parmresult =
                   9198:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   9199:                                                        '0_examcode',2,$scancode,
                   9200:                                                        'string_examcode',$uname,
                   9201:                                                        $udom);
                   9202:         }
1.140     albertel 9203: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9204:         if ($env{'form.verifyrecord'}) {
                   9205:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  9206:             if ($randompick) {
                   9207:                 if ($total) {
                   9208:                     $lastpos = $total*$scantron_config{'Qlength'};
                   9209:                 }
                   9210:             }
                   9211: 
1.542     raeburn  9212:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9213:             chomp($studentdata);
                   9214:             $studentdata =~ s/\r$//;
                   9215:             my $studentrecord = '';
                   9216:             my $counter = -1;
1.677     raeburn  9217:             foreach my $resource (@mapresources) {
1.554     raeburn  9218:                 my $ressymb = $resource->symb();
1.542     raeburn  9219:                 ($counter,my $recording) =
                   9220:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9221:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9222:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9223:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9224:                 $studentrecord .= $recording;
                   9225:             }
                   9226:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9227:                 &Apache::lonxml::clear_problem_counter();
                   9228:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9229:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  9230:                                            $bubbles_per_row,$randomorder,$randompick,
                   9231:                                            \%respnumlookup,\%startline) 
                   9232:                     eq 'ssi_error') {
1.554     raeburn  9233:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9234:                     $r->print("</form>");
                   9235:                     &ssi_print_error($r);
                   9236:                     &Apache::lonnet::remove_lock($lock);
                   9237:                     delete($completedstudents{$uname});
                   9238:                     return '';
                   9239:                 }
1.542     raeburn  9240:                 $counter = -1;
                   9241:                 $studentrecord = '';
1.677     raeburn  9242:                 foreach my $resource (@mapresources) {
1.554     raeburn  9243:                     my $ressymb = $resource->symb();
1.542     raeburn  9244:                     ($counter,my $recording) =
                   9245:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9246:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9247:                                                  \%scantron_config,\%lettdig,$numletts,
                   9248:                                                  $randomorder,$randompick,\%respnumlookup,
                   9249:                                                  \%startline);
1.542     raeburn  9250:                     $studentrecord .= $recording;
                   9251:                 }
                   9252:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   9253:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9254:                     if ($scancode eq '') {
1.658     bisitz   9255:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9256:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9257:                     } else {
1.658     bisitz   9258:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9259:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9260:                     }
                   9261:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9262:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9263:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9264:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9265:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9266:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   9267:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9268:                               &Apache::loncommon::end_data_table_row().
                   9269:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9270:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   9271:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9272:                               &Apache::loncommon::end_data_table_row().
                   9273:                               &Apache::loncommon::end_data_table().'</p>');
                   9274:                 } else {
                   9275:                     $r->print('<br /><span class="LC_warning">'.
                   9276:                              &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 />'.
                   9277:                              &mt("As a consequence, this user's submission history records two tries.").
                   9278:                                  '</span><br />');
                   9279:                 }
                   9280:             }
                   9281:         }
1.543     raeburn  9282:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9283:     } continue {
1.330     albertel 9284: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9285: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9286:     }
1.140     albertel 9287:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9288:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9289: #    my $lasttime = &Time::HiRes::time()-$start;
                   9290: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9291: 
1.200     albertel 9292:     $r->print("</form>");
1.157     albertel 9293:     return '';
1.75      albertel 9294: }
1.157     albertel 9295: 
1.557     raeburn  9296: sub graders_resources_pass {
1.649     raeburn  9297:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9298:         $bubbles_per_row) = @_;
1.557     raeburn  9299:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9300:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9301:         foreach my $resource (@{$resources}) {
                   9302:             my $ressymb = $resource->symb();
                   9303:             my ($analysis,$parts) =
                   9304:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  9305:                                           $env{'user.name'},$env{'user.domain'},
                   9306:                                           1,$bubbles_per_row);
1.557     raeburn  9307:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9308:             if (ref($analysis) eq 'HASH') {
                   9309:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9310:                     $grader_randomlists_by_symb->{$ressymb} =
                   9311:                         $analysis->{'parts_withrandomlist'};
                   9312:                 }
                   9313:             }
                   9314:         }
                   9315:     }
                   9316:     return;
                   9317: }
                   9318: 
1.678     raeburn  9319: =pod
                   9320: 
                   9321: =item users_order
                   9322: 
                   9323:   Returns array of resources in current map, ordered based on either CODE,
                   9324:   if this is a CODEd exam, or based on student's identity if this is a 
                   9325:   "NAMEd" exam.
                   9326: 
1.691     raeburn  9327:   Should be used when randomorder and/or randompick applied when the 
                   9328:   corresponding exam was printed, prior to students completing bubblesheets 
                   9329:   for the version of the exam the student received.
1.678     raeburn  9330: 
                   9331: =cut
                   9332: 
                   9333: sub users_order  {
1.691     raeburn  9334:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9335:     my @mapresources;
1.691     raeburn  9336:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9337:         return @mapresources;
1.691     raeburn  9338:     }
                   9339:     if ($scancode) {
                   9340:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9341:             @mapresources = @{$orderedforcode->{$scancode}};
                   9342:         } else {
                   9343:             $env{'form.CODE'} = $scancode;
                   9344:             my $actual_seq =
                   9345:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9346:                                                                $master_seq,
                   9347:                                                                $user,$scancode,1);
                   9348:             if (ref($actual_seq) eq 'ARRAY') {
                   9349:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9350:                 if (ref($orderedforcode) eq 'HASH') {
                   9351:                     if (@mapresources > 0) { 
                   9352:                         $orderedforcode->{$scancode} = \@mapresources;
                   9353:                     }
                   9354:                 }
                   9355:             }
                   9356:             delete($env{'form.CODE'});
1.678     raeburn  9357:         }
                   9358:     } else {
                   9359:         my $actual_seq =
                   9360:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9361:                                                            $master_seq,
1.688     raeburn  9362:                                                            $user,undef,1);
1.678     raeburn  9363:         if (ref($actual_seq) eq 'ARRAY') {
                   9364:             @mapresources = 
                   9365:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9366:         }
1.691     raeburn  9367:     }
                   9368:     return @mapresources;
1.678     raeburn  9369: }
                   9370: 
1.542     raeburn  9371: sub grade_student_bubbles {
1.691     raeburn  9372:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9373:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9374:     my $uselookup = 0;
                   9375:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9376:         (ref($startline) eq 'HASH')) {
                   9377:         $uselookup = 1;
                   9378:     }
                   9379: 
1.554     raeburn  9380:     if (ref($resources) eq 'ARRAY') {
                   9381:         my $count = 0;
                   9382:         foreach my $resource (@{$resources}) {
                   9383:             my $ressymb = $resource->symb();
                   9384:             my %form = ('submitted'      => 'scantron',
                   9385:                         'grade_target'   => 'grade',
                   9386:                         'grade_username' => $uname,
                   9387:                         'grade_domain'   => $udom,
                   9388:                         'grade_courseid' => $env{'request.course.id'},
                   9389:                         'grade_symb'     => $ressymb,
                   9390:                         'CODE'           => $scancode
                   9391:                        );
1.649     raeburn  9392:             if ($bubbles_per_row ne '') {
                   9393:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9394:             }
1.663     raeburn  9395:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9396:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9397:             }
1.554     raeburn  9398:             if (ref($parts) eq 'HASH') {
                   9399:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9400:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9401:                         if ($uselookup) {
                   9402:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9403:                         } else {
                   9404:                             $form{'scantron_questnum_start.'.$part} =
                   9405:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9406:                         }
1.554     raeburn  9407:                         $count++;
                   9408:                     }
                   9409:                 }
                   9410:             }
                   9411:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9412:             return 'ssi_error' if ($ssi_error);
                   9413:             last if (&Apache::loncommon::connection_aborted($r));
                   9414:         }
1.542     raeburn  9415:     }
                   9416:     return;
                   9417: }
                   9418: 
1.157     albertel 9419: sub scantron_upload_scantron_data {
1.767     raeburn  9420:     my ($r,$symb) = @_;
1.565     raeburn  9421:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9422:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9423:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9424:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9425:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9426: 							  'domainid',
1.565     raeburn  9427: 							  'coursename',$dom);
                   9428:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9429:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9430:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9431:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9432:     &js_escape(\$nofile_alert);
1.579     raeburn  9433:     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  9434:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9435:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9436:     function checkUpload(formname) {
                   9437: 	if (formname.upfile.value == "") {
1.579     raeburn  9438: 	    alert("'.$nofile_alert.'");
1.157     albertel 9439: 	    return false;
                   9440: 	}
1.565     raeburn  9441:         if (formname.courseid.value == "") {
1.579     raeburn  9442:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9443:             return false;
                   9444:         }
1.157     albertel 9445: 	formname.submit();
                   9446:     }
1.565     raeburn  9447: 
                   9448:     function ToSyllabus() {
                   9449:         var cdom = '."'$dom'".';
                   9450:         var cnum = document.rules.courseid.value;
                   9451:         if (cdom == "" || cdom == null) {
                   9452:             return;
                   9453:         }
                   9454:         if (cnum == "" || cnum == null) {
                   9455:            return;
                   9456:         }
                   9457:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9458:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9459:         return;
                   9460:     }
                   9461: 
1.754     raeburn  9462:     '.$formatjs.'
1.597     wenzelju 9463: '));
                   9464:     $r->print('
1.648     bisitz   9465: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9466: 
1.492     albertel 9467: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9468: '.$default_form_data.
                   9469:   &Apache::lonhtmlcommon::start_pick_box().
                   9470:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9471:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9472:   &Apache::lonhtmlcommon::row_closure().
                   9473:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9474:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9475:   &Apache::lonhtmlcommon::row_closure().
                   9476:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9477:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9478:   &Apache::lonhtmlcommon::row_closure());
                   9479:     if ($formatoptions) {
                   9480:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9481:                   &Apache::lonhtmlcommon::row_closure());
                   9482:     }
                   9483:     $r->print(
1.565     raeburn  9484:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9485:   '<input type="file" name="upfile" size="50" />'.
                   9486:   &Apache::lonhtmlcommon::row_closure(1).
                   9487:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9488: 
1.492     albertel 9489: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9490: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9491: </form>
1.492     albertel 9492: ');
1.157     albertel 9493:     return '';
                   9494: }
                   9495: 
1.754     raeburn  9496: sub scantron_upload_dataformat {
                   9497:     my ($dom) = @_;
                   9498:     my ($formatoptions,$formattitle,$formatjs);
                   9499:     $formatjs = <<'END';
                   9500: function toggleScantab(form) {
                   9501:    return;
                   9502: }
                   9503: END
                   9504:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9505:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9506:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9507:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9508:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9509:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  9510:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   9511:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9512:                             my ($onclick,$formatextra,$singleline);
                   9513:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9514:                             my $count = 0;
                   9515:                             foreach my $line (@lines) {
                   9516:                                 next if ($line =~ /^#/);
                   9517:                                 $singleline = $line;
                   9518:                                 $count ++;
                   9519:                             }
                   9520:                             if ($count > 1) {
                   9521:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  9522:                                                '<span class="LC_nobreak">'.
1.776     raeburn  9523:                                                &mt('Bubblesheet type').':&nbsp;'.
1.757     raeburn  9524:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  9525:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9526:                                 $formatjs = <<"END";
1.754     raeburn  9527: function toggleScantab(form) {
                   9528:     var divid = 'bubbletype';
                   9529:     if (document.getElementById(divid)) {
                   9530:         var radioname = 'fileformat';
                   9531:         var num = form.elements[radioname].length;
                   9532:         if (num) {
                   9533:             for (var i=0; i<num; i++) {
                   9534:                 if (form.elements[radioname][i].checked) {
                   9535:                     var chosen = form.elements[radioname][i].value;
                   9536:                     if (chosen == 'dat') {
                   9537:                         document.getElementById(divid).style.display = 'none';
                   9538:                     } else if (chosen == 'csv') {
1.757     raeburn  9539:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  9540:                     }
                   9541:                 }
                   9542:             }
                   9543:         }
                   9544:     }
                   9545:     return;
                   9546: }
                   9547: 
                   9548: END
1.756     raeburn  9549:                             } elsif ($count == 1) {
                   9550:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9551:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9552:                             }
                   9553:                             $formattitle = &mt('File format');
                   9554:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9555:                                              &mt('Plain Text (no delimiters)').
                   9556:                                              '</label>'.('&nbsp;'x2).
                   9557:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9558:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9559:                         }
                   9560:                     }
                   9561:                 }
                   9562:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  9563:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9564:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  9565:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  9566:                         $formatoptions = &scantron_scantab();
                   9567:                     }
1.754     raeburn  9568:                 }
                   9569:             }
                   9570:         }
                   9571:     }
                   9572:     return ($formatoptions,$formattitle,$formatjs);
                   9573: }
1.423     albertel 9574: 
1.157     albertel 9575: sub scantron_upload_scantron_data_save {
1.767     raeburn  9576:     my ($r,$symb) = @_;
1.182     albertel 9577:     my $doanotherupload=
                   9578: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9579: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9580: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9581: 	'</form>'."\n";
1.257     albertel 9582:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9583: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  9584: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   9585:         !&Apache::lonnet::allowed('usc',
                   9586:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      9587: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9588: 	unless ($symb) {
1.182     albertel 9589: 	    $r->print($doanotherupload);
                   9590: 	}
1.162     albertel 9591: 	return '';
                   9592:     }
1.257     albertel 9593:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9594:     my $uploadedfile;
1.710     bisitz   9595:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9596:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9597:         $r->print(
                   9598:             &Apache::lonhtmlcommon::confirm_success(
                   9599:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9600:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9601:     } else {
1.754     raeburn  9602:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9603:         my $parser;
                   9604:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9605:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9606:                 my $is_csv;
                   9607:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9608:                 if (@possibles > 1) {
                   9609:                     if ($env{'form.fileformat'} eq 'csv') {
                   9610:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9611:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9612:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9613:                                     $is_csv = 1;
                   9614:                                 }
1.754     raeburn  9615:                             }
                   9616:                         }
                   9617:                     }
                   9618:                 } elsif (@possibles == 1) {
                   9619:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9620:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9621:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9622:                                 $is_csv = 1;
                   9623:                             }
1.754     raeburn  9624:                         }
                   9625:                     }
                   9626:                 }
                   9627:                 if ($is_csv) {
                   9628:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9629:                 }
                   9630:             }
                   9631:         }
                   9632:         my $result =
                   9633:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9634:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9635:         if ($result =~ m{^/uploaded/}) {
                   9636:             $r->print(
                   9637:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9638:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9639:                         (length($env{'form.upfile'})-1),
                   9640:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9641:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  9642:             if ($uploadedfile =~ /^scantron_orig_/) {
                   9643:                 my $logname = $uploadedfile;
                   9644:                 $logname =~ s/^scantron_orig_//;
                   9645:                 if ($logname ne '') {
                   9646:                     my $now = time;
                   9647:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   9648:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9649:                 }
                   9650:             }
1.567     raeburn  9651:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  9652:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   9653:         } else {
                   9654:             $r->print(
                   9655:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9656:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9657:                           $result,
1.568     raeburn  9658: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9659: 	}
                   9660:     }
1.174     albertel 9661:     if ($symb) {
1.612     www      9662: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9663:     } else {
1.182     albertel 9664: 	$r->print($doanotherupload);
1.174     albertel 9665:     }
1.157     albertel 9666:     return '';
                   9667: }
                   9668: 
1.567     raeburn  9669: sub validate_uploaded_scantron_file {
1.770     raeburn  9670:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   9671: 
1.567     raeburn  9672:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9673:     my @lines;
                   9674:     if ($scanlines ne '-1') {
                   9675:         @lines=split("\n",$scanlines,-1);
                   9676:     }
1.770     raeburn  9677:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   9678:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   9679:     if ($context eq 'download') {
                   9680:         $priv = 'mgr';
                   9681:     } else {
                   9682:         $priv = 'usc';
                   9683:     }
                   9684:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   9685:             (($env{'request.course.id'}) &&
                   9686:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   9687:         if ($env{'request.course.sec'} ne '') {
                   9688:             unless (&Apache::lonnet::allowed($priv,
                   9689:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   9690:                 unless ($context eq 'download') {
                   9691:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   9692:                 }
                   9693:                 return $output;
                   9694:             }
                   9695:             ($checksec,@possibles)=&gradable_sections();
                   9696:         }
                   9697:     }
1.567     raeburn  9698:     if (@lines) {
                   9699:         my (%counts,$max_match_format);
1.710     bisitz   9700:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9701:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9702:         my %idmap = &username_to_idmap($classlist);
                   9703:         foreach my $key (keys(%idmap)) {
                   9704:             my $lckey = lc($key);
                   9705:             $idmap{$lckey} = $idmap{$key};
                   9706:         }
                   9707:         my %unique_formats;
1.754     raeburn  9708:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9709:         foreach my $line (@formatlines) {
                   9710:             chomp($line);
                   9711:             my @config = split(/:/,$line);
                   9712:             my $idstart = $config[5];
                   9713:             my $idlength = $config[6];
                   9714:             if (($idstart ne '') && ($idlength > 0)) {
                   9715:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9716:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9717:                 } else {
                   9718:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9719:                 }
                   9720:             }
                   9721:         }
                   9722:         foreach my $key (keys(%unique_formats)) {
                   9723:             my ($idstart,$idlength) = split(':',$key);
                   9724:             %{$counts{$key}} = (
                   9725:                                'found'   => 0,
                   9726:                                'total'   => 0,
1.770     raeburn  9727:                                'totalanysec' => 0,
                   9728:                                'othersec' => 0,
1.567     raeburn  9729:                               );
                   9730:             foreach my $line (@lines) {
                   9731:                 next if ($line =~ /^#/);
                   9732:                 next if ($line =~ /^[\s\cz]*$/);
                   9733:                 my $id = substr($line,$idstart-1,$idlength);
                   9734:                 $id = lc($id);
                   9735:                 if (exists($idmap{$id})) {
1.770     raeburn  9736:                     if ($checksec ne '') {
                   9737:                         $counts{$key}{'totalanysec'} ++;
                   9738:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9739:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9740:                             if ($stusec ne $checksec) {
                   9741:                                 if (@possibles) {
                   9742:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   9743:                                         $counts{$key}{'othersec'} ++;
                   9744:                                         next;
                   9745:                                     }
                   9746:                                 } else {
                   9747:                                     $counts{$key}{'othersec'} ++;
                   9748:                                     next;
                   9749:                                 }
                   9750:                             }
                   9751:                         }
                   9752:                     }
1.567     raeburn  9753:                     $counts{$key}{'found'} ++;
                   9754:                 }
                   9755:                 $counts{$key}{'total'} ++;
                   9756:             }
                   9757:             if ($counts{$key}{'total'}) {
                   9758:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9759:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9760:                     $max_match_pct = $percent_match;
                   9761:                     $max_match_format = $key;
1.710     bisitz   9762:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9763:                     $max_match_count = $counts{$key}{'total'};
                   9764:                 }
                   9765:             }
                   9766:         }
1.770     raeburn  9767:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  9768:             my $format_descs;
                   9769:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9770:             for (my $i=0; $i<$numwithformat; $i++) {
                   9771:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9772:                 if ($i<$numwithformat-2) {
                   9773:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9774:                 } elsif ($i==$numwithformat-2) {
                   9775:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9776:                 } elsif ($i==$numwithformat-1) {
                   9777:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9778:                 }
                   9779:             }
                   9780:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9781:             $output .= '<br />';
                   9782:             if ($found_match_count == $max_match_count) {
                   9783:                 # 100% matching entries
                   9784:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9785:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9786:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9787:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9788:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9789:                     ' in the file (for the format defined for [_3]).',
                   9790:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9791:             } else {
                   9792:                 # Not all entries matching? -> Show warning and additional info
                   9793:                 $output .=
                   9794:                     &Apache::lonhtmlcommon::confirm_success(
                   9795:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9796:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9797:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9798:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9799:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9800:                         ' in the file (for the format defined for [_3]).',
                   9801:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9802:                     '<p class="LC_info">'.
                   9803:                     &mt('A low percentage of matches results from one of the following:').
                   9804:                     '</p><ul>'.
                   9805:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9806:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9807:                                '<i>'.$cdom.'</i>').'</li>'.
                   9808:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9809:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9810:                     '</ul>';
                   9811:             }
1.770     raeburn  9812:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9813:                 if ($counts{$max_match_format}{'othersec'}) {
                   9814:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   9815:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   9816:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   9817:                     &js_escape(\$confirmdel);
                   9818:                     $output .= '<p class="LC_warning">'.
                   9819:                                &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',
                   9820:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   9821:                                '<br />'.
                   9822:                                &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>').
                   9823:                                '</p><p>'.
                   9824:                                &mt('If you prefer to delete the file now, use: [_1]').
                   9825:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   9826:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   9827:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   9828:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   9829:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   9830:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   9831:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   9832:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   9833:                                '</form></p>';
                   9834:                 }
                   9835:             }
1.567     raeburn  9836:         }
1.770     raeburn  9837:         if (($context eq 'download') && ($checksec ne '')) {
                   9838:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9839:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   9840:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   9841:             }
                   9842:         } 
                   9843:     } elsif ($context ne 'download') {
1.710     bisitz   9844:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9845:     }
                   9846:     return $output;
                   9847: }
                   9848: 
1.770     raeburn  9849: sub gradable_sections {
                   9850:     my $checksec = $env{'request.course.sec'};
                   9851:     my @oksecs;
                   9852:     if ($checksec) {
                   9853:         my %availablesecs = &sections_grade_privs();
                   9854:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   9855:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   9856:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   9857:                     push(@oksecs,$sec);
                   9858:                 }
                   9859:             }
                   9860:             if (grep(/^all$/,@oksecs)) {
                   9861:                 undef($checksec);
                   9862:             }
                   9863:         }
                   9864:     }
                   9865:     return($checksec,@oksecs);
                   9866: }
                   9867: 
                   9868: sub sections_grade_privs {
                   9869:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9870:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9871:     my %availablesecs = (
                   9872:                           mgr => [],
                   9873:                           vgr => [],
                   9874:                           usc => [],
                   9875:                         );
                   9876:     my $ccrole = 'cc';
                   9877:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   9878:         $ccrole = 'co';
                   9879:     }
                   9880:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   9881:                                                      'userroles',['active'],
                   9882:                                                      [$ccrole,'in','cr'],$cdom,1);
                   9883:     my $crsid = $cnum.':'.$cdom;
                   9884:     foreach my $item (keys(%crsroleshash)) {
                   9885:         next unless ($item =~ /^$crsid\:/);
                   9886:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   9887:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   9888:         if ($sec ne '') {
                   9889:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   9890:         }
                   9891:         if (($role eq $ccrole) || ($role eq 'in')) {
                   9892:             foreach my $priv ('mgr','vgr','usc') { 
                   9893:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9894:                     if ($sec eq '') {
                   9895:                         $availablesecs{$priv} = ['all'];
                   9896:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   9897:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9898:                             push(@{$availablesecs{$priv}},$sec);
                   9899:                         }
                   9900:                     }
                   9901:                 }
                   9902:             }
                   9903:         } elsif ($role =~ m{^cr/}) {
                   9904:             foreach my $priv ('mgr','vgr','usc') {
                   9905:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9906:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   9907:                         if ($sec eq '') {
                   9908:                             $availablesecs{$priv} = ['all'];
                   9909:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   9910:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9911:                                 push(@{$availablesecs{$priv}},$sec);
                   9912:                             }
                   9913:                         }
                   9914:                     }
                   9915:                 }
                   9916:             }
                   9917:         }
                   9918:     }
                   9919:     return %availablesecs;
                   9920: }
                   9921: 
                   9922: sub scantron_upload_delete {
                   9923:     my ($r,$symb) = @_;
                   9924:     my $filename = $env{'form.uploadedfile'};
                   9925:     if ($filename =~ /^scantron_orig_/) {
                   9926:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   9927:             &Apache::lonnet::allowed('usc',
                   9928:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   9929:             &Apache::lonnet::allowed('usc',
                   9930:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   9931:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   9932:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   9933:             if ($retrieval eq '-1') {
                   9934:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9935:                           &mt('File requested for deletion not found.'));
                   9936:             } else {
                   9937:                 $filename =~ s/^scantron_orig_//;
                   9938:                 if ($filename ne '') {
                   9939:                     my ($is_valid,$numleft);
                   9940:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9941:                     if (keys(%info)) {
                   9942:                         if (ref($info{$filename}) eq 'HASH') {
                   9943:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   9944:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9945:                                     $is_valid = 1;
                   9946:                                     delete($info{$filename}{$timestamp}); 
                   9947:                                 }
                   9948:                             }
                   9949:                             $numleft = scalar(keys(%{$info{$filename}}));
                   9950:                         }
                   9951:                     }
                   9952:                     if ($is_valid) {
                   9953:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   9954:                         if ($result eq 'ok') {
                   9955:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   9956:                             if ($numleft) {
                   9957:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9958:                             } else {
                   9959:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9960:                             }
                   9961:                         } else {
                   9962:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9963:                                       &mt('Result was [_1]',$result));
                   9964:                         }
                   9965:                     } else {
                   9966:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9967:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   9968:                     }
                   9969:                 } else {
                   9970:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9971:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9972:                 }
                   9973:             }
                   9974:         } else {
                   9975:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   9976:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   9977:         }
                   9978:     } else {
                   9979:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9980:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9981:     }
                   9982:     return;
                   9983: }
                   9984: 
1.202     albertel 9985: sub valid_file {
                   9986:     my ($requested_file)=@_;
                   9987:     foreach my $filename (sort(&scantron_filenames())) {
                   9988: 	if ($requested_file eq $filename) { return 1; }
                   9989:     }
                   9990:     return 0;
                   9991: }
                   9992: 
                   9993: sub scantron_download_scantron_data {
1.767     raeburn  9994:     my ($r,$symb) = @_;
1.608     www      9995:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9996:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9997:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9998:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9999:     if (! &valid_file($file)) {
1.492     albertel 10000: 	$r->print('
1.202     albertel 10001: 	<p>
1.686     bisitz   10002: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 10003:         </p>
1.492     albertel 10004: ');
1.202     albertel 10005: 	return;
                   10006:     }
1.770     raeburn  10007:     my (%uploader,$is_owner,%counts,$percent);
                   10008:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   10009:     if (ref($uploader{$file}) eq 'HASH') {
                   10010:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   10011:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   10012:                 $is_owner = 1;
                   10013:                 last;
                   10014:             }
                   10015:         }
                   10016:     }
                   10017:     unless ($is_owner) {
                   10018:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   10019:         if ($counts{'totalanysec'}) {
                   10020:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   10021:             if ($percent_othersec >= 10) {
                   10022:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   10023:                 $r->print('<p class="LC_warning">'.
                   10024:                           &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).
                   10025:                           '</p>');
                   10026:                 return;
                   10027:             }
                   10028:         }
                   10029:     }
1.202     albertel 10030:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   10031:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   10032:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   10033:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   10034:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   10035:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 10036:     $r->print('
1.202     albertel 10037:     <p>
1.723     raeburn  10038: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 10039: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 10040:     </p>
                   10041:     <p>
1.492     albertel 10042: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   10043: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 10044:     </p>
                   10045:     <p>
1.492     albertel 10046: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   10047: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 10048:     </p>
1.492     albertel 10049: ');
1.202     albertel 10050:     return '';
                   10051: }
1.157     albertel 10052: 
1.523     raeburn  10053: sub checkscantron_results {
1.608     www      10054:     my ($r,$symb) = @_;
1.523     raeburn  10055:     if (!$symb) {return '';}
                   10056:     my $cid = $env{'request.course.id'};
1.755     raeburn  10057:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  10058:     my $numletts = scalar(keys(%lettdig));
                   10059:     my $cnum = $env{'course.'.$cid.'.num'};
                   10060:     my $cdom = $env{'course.'.$cid.'.domain'};
                   10061:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10062:     my %record;
                   10063:     my %scantron_config =
1.754     raeburn  10064:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  10065:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  10066:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  10067:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10068:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   10069:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10070:     unless (ref($navmap)) {
                   10071:         $r->print(&navmap_errormsg());
                   10072:         return '';
                   10073:     }
1.523     raeburn  10074:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10075:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10076:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  10077:     if (ref($map)) { 
                   10078:         $randomorder=$map->randomorder();
1.689     raeburn  10079:         $randompick=$map->randompick();
1.677     raeburn  10080:     }
1.557     raeburn  10081:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10082:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10083:     if ($nav_error) {
                   10084:         $r->print(&navmap_errormsg());
                   10085:         return '';
1.678     raeburn  10086:     }
1.673     raeburn  10087:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10088:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  10089:     my ($uname,$udom);
1.523     raeburn  10090:     my (%scandata,%lastname,%bylast);
                   10091:     $r->print('
                   10092: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   10093: 
                   10094:     my @delayqueue;
                   10095:     my %completedstudents;
                   10096: 
1.691     raeburn  10097:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10098:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  10099:     my ($username,$domain,$started);
1.649     raeburn  10100:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10101:     if ($nav_error) {
                   10102:         $r->print(&navmap_errormsg());
                   10103:         return '';
                   10104:     }
1.523     raeburn  10105: 
1.667     www      10106:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  10107:     my $start=&Time::HiRes::time();
                   10108:     my $i=-1;
                   10109: 
                   10110:     while ($i<$scanlines->{'count'}) {
                   10111:         ($username,$domain,$uname)=('','','');
                   10112:         $i++;
                   10113:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   10114:         if ($line=~/^[\s\cz]*$/) { next; }
                   10115:         if ($started) {
1.667     www      10116:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  10117:         }
                   10118:         $started=1;
                   10119:         my $scan_record=
                   10120:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   10121:                                                      $scan_data);
1.693     raeburn  10122:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10123:                                               \%idmap,$i)) {
1.523     raeburn  10124:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10125:                                 'Unable to find a student that matches',1);
                   10126:             next;
                   10127:         }
                   10128:         if (exists $completedstudents{$uname}) {
                   10129:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10130:                                 'Student '.$uname.' has multiple sheets',2);
                   10131:             next;
                   10132:         }
                   10133:         my $pid = $scan_record->{'scantron.ID'};
                   10134:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   10135:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  10136:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   10137:         my $user = $uname.':'.$usec;
1.523     raeburn  10138:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  10139: 
1.678     raeburn  10140:         my $scancode;
1.677     raeburn  10141:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10142:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10143:             $scancode = $scan_record->{'scantron.CODE'};
                   10144:         } else {
                   10145:             $scancode = '';
                   10146:         }
                   10147: 
                   10148:         my @mapresources = @resources;
1.691     raeburn  10149:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   10150:         my %respnumlookup=();
                   10151:         my %startline=();
1.689     raeburn  10152:         if ($randomorder || $randompick) {
1.678     raeburn  10153:             @mapresources =
1.691     raeburn  10154:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10155:                              \%orderedforcode);
                   10156:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   10157:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   10158:                                              \%grader_partids_by_symb,\%orderedforcode,
                   10159:                                              \%respnumlookup,\%startline);
                   10160:             if ($randompick && $total) {
                   10161:                 $lastpos = $total*$scantron_config{'Qlength'};
                   10162:             }
1.677     raeburn  10163:         }
1.691     raeburn  10164:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10165:         chomp($scandata{$pid});
                   10166:         $scandata{$pid} =~ s/\r$//;
                   10167: 
1.523     raeburn  10168:         my $counter = -1;
1.677     raeburn  10169:         foreach my $resource (@mapresources) {
1.557     raeburn  10170:             my $parts;
1.554     raeburn  10171:             my $ressymb = $resource->symb();
1.557     raeburn  10172:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10173:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10174:                 my $currcode;
                   10175:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10176:                     $currcode = $scancode;
                   10177:                 }
1.557     raeburn  10178:                 (my $analysis,$parts) =
1.672     raeburn  10179:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   10180:                                               $username,$domain,undef,
1.741     raeburn  10181:                                               $bubbles_per_row,$currcode);
1.557     raeburn  10182:             } else {
                   10183:                 $parts = $grader_partids_by_symb{$ressymb};
                   10184:             }
1.542     raeburn  10185:             ($counter,my $recording) =
                   10186:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  10187:                                          $scandata{$pid},$parts,
1.691     raeburn  10188:                                          \%scantron_config,\%lettdig,$numletts,
                   10189:                                          $randomorder,$randompick,
                   10190:                                          \%respnumlookup,\%startline);
1.542     raeburn  10191:             $record{$pid} .= $recording;
1.523     raeburn  10192:         }
                   10193:     }
                   10194:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   10195:     $r->print('<br />');
                   10196:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   10197:     $passed = 0;
                   10198:     $failed = 0;
                   10199:     $numstudents = 0;
                   10200:     foreach my $last (sort(keys(%bylast))) {
                   10201:         if (ref($bylast{$last}) eq 'ARRAY') {
                   10202:             foreach my $pid (sort(@{$bylast{$last}})) {
                   10203:                 my $showscandata = $scandata{$pid};
                   10204:                 my $showrecord = $record{$pid};
                   10205:                 $showscandata =~ s/\s/&nbsp;/g;
                   10206:                 $showrecord =~ s/\s/&nbsp;/g;
                   10207:                 if ($scandata{$pid} eq $record{$pid}) {
                   10208:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   10209:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      10210: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  10211: '</tr>'."\n".
                   10212: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10213: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  10214:                     $passed ++;
                   10215:                 } else {
                   10216:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      10217:                     $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  10218: '</tr>'."\n".
                   10219: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10220: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  10221: '</tr>'."\n";
                   10222:                     $failed ++;
                   10223:                 }
                   10224:                 $numstudents ++;
                   10225:             }
                   10226:         }
                   10227:     }
1.648     bisitz   10228:     $r->print(
                   10229:         '<p>'
                   10230:        .&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).',
                   10231:             '<b>',
                   10232:             $numstudents,
                   10233:             '</b>',
                   10234:             $env{'form.scantron_maxbubble'})
                   10235:        .'</p>'
                   10236:     );
1.682     raeburn  10237:     $r->print('<p>'
1.683     raeburn  10238:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  10239:              .'<br />'
                   10240:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10241:              .'</p>'
                   10242:     );
1.523     raeburn  10243:     if ($passed) {
1.572     www      10244:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10245:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10246:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10247:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10248:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10249:                  $okstudents."\n".
                   10250:                  &Apache::loncommon::end_data_table().'<br />');
                   10251:     }
                   10252:     if ($failed) {
1.572     www      10253:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10254:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10255:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10256:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10257:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10258:                  $badstudents."\n".
                   10259:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10260:                  &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  10261:     }
1.614     www      10262:     $r->print('</form><br />');
1.523     raeburn  10263:     return;
                   10264: }
                   10265: 
1.542     raeburn  10266: sub verify_scantron_grading {
1.554     raeburn  10267:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  10268:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10269:         $respnumlookup,$startline) = @_;
1.542     raeburn  10270:     my ($record,%expected,%startpos);
                   10271:     return ($counter,$record) if (!ref($resource));
                   10272:     return ($counter,$record) if (!$resource->is_problem());
                   10273:     my $symb = $resource->symb();
1.554     raeburn  10274:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10275:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10276:         $counter ++;
                   10277:         $expected{$part_id} = 0;
1.691     raeburn  10278:         my $respnum = $counter;
                   10279:         if ($randomorder || $randompick) {
                   10280:             $respnum = $respnumlookup->{$counter};
                   10281:             $startpos{$part_id} = $startline->{$counter} + 1;
                   10282:         } else {
                   10283:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10284:         }
                   10285:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10286:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10287:             foreach my $item (@sub_lines) {
                   10288:                 $expected{$part_id} += $item;
                   10289:             }
                   10290:         } else {
1.691     raeburn  10291:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10292:         }
                   10293:     }
                   10294:     if ($symb) {
                   10295:         my %recorded;
                   10296:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10297:         if ($returnhash{'version'}) {
                   10298:             my %lasthash=();
                   10299:             my $version;
                   10300:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10301:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10302:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10303:                 }
                   10304:             }
                   10305:             foreach my $key (keys(%lasthash)) {
                   10306:                 if ($key =~ /\.scantron$/) {
                   10307:                     my $value = &unescape($lasthash{$key});
                   10308:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10309:                     if ($value eq '') {
                   10310:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10311:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10312:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10313:                             }
                   10314:                         }
                   10315:                     } else {
                   10316:                         my @tocheck;
                   10317:                         my @items = split(//,$value);
                   10318:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10319:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10320:                             if (@items < $expected{$part_id}) {
                   10321:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10322:                                 my @singles = split(//,$fragment);
                   10323:                                 foreach my $pos (@singles) {
                   10324:                                     if ($pos eq ' ') {
                   10325:                                         push(@tocheck,$pos);
                   10326:                                     } else {
                   10327:                                         my $next = shift(@items);
                   10328:                                         push(@tocheck,$next);
                   10329:                                     }
                   10330:                                 }
                   10331:                             } else {
                   10332:                                 @tocheck = @items;
                   10333:                             }
                   10334:                             foreach my $letter (@tocheck) {
                   10335:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10336:                                     if ($letter !~ /^[A-J]$/) {
                   10337:                                         $letter = $scantron_config->{'Qoff'};
                   10338:                                     }
                   10339:                                     $recorded{$part_id} .= $letter;
                   10340:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10341:                                     my $digit;
                   10342:                                     if ($letter !~ /^[A-J]$/) {
                   10343:                                         $digit = $scantron_config->{'Qoff'};
                   10344:                                     } else {
                   10345:                                         $digit = $lettdig->{$letter};
                   10346:                                     }
                   10347:                                     $recorded{$part_id} .= $digit;
                   10348:                                 }
                   10349:                             }
                   10350:                         } else {
                   10351:                             @tocheck = @items;
                   10352:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10353:                                 my $curr_sub = shift(@tocheck);
                   10354:                                 my $digit;
                   10355:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10356:                                     $digit = $lettdig->{$curr_sub}-1;
                   10357:                                 }
                   10358:                                 if ($curr_sub eq 'J') {
                   10359:                                     $digit += scalar($numletts);
                   10360:                                 }
                   10361:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10362:                                     if ($j == $digit) {
                   10363:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10364:                                     } else {
                   10365:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10366:                                     }
                   10367:                                 }
                   10368:                             }
                   10369:                         }
                   10370:                     }
                   10371:                 }
                   10372:             }
                   10373:         }
1.554     raeburn  10374:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10375:             if ($recorded{$part_id} eq '') {
                   10376:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10377:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10378:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10379:                     }
                   10380:                 }
                   10381:             }
                   10382:             $record .= $recorded{$part_id};
                   10383:         }
                   10384:     }
                   10385:     return ($counter,$record);
                   10386: }
                   10387: 
1.75      albertel 10388: #-------- end of section for handling grading scantron forms -------
                   10389: #
                   10390: #-------------------------------------------------------------------
                   10391: 
1.72      ng       10392: #-------------------------- Menu interface -------------------------
                   10393: #
1.614     www      10394: #--- Href with symb and command ---
                   10395: 
                   10396: sub href_symb_cmd {
                   10397:     my ($symb,$cmd)=@_;
1.669     raeburn  10398:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       10399: }
                   10400: 
1.443     banghart 10401: sub grading_menu {
1.608     www      10402:     my ($request,$symb) = @_;
1.443     banghart 10403:     if (!$symb) {return '';}
                   10404: 
                   10405:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      10406:                   'command'=>'individual');
1.538     schulted 10407:     
1.598     www      10408:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10409: 
                   10410:     $fields{'command'}='ungraded';
                   10411:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10412: 
                   10413:     $fields{'command'}='table';
                   10414:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10415: 
                   10416:     $fields{'command'}='all_for_one';
                   10417:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10418: 
1.621     www      10419:     $fields{'command'}='downloadfilesselect';
                   10420:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10421: 
1.443     banghart 10422:     $fields{'command'} = 'csvform';
1.538     schulted 10423:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10424:     
1.443     banghart 10425:     $fields{'command'} = 'processclicker';
1.538     schulted 10426:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10427:     
1.443     banghart 10428:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10429:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      10430: 
                   10431:     $fields{'command'} = 'initialverifyreceipt';
                   10432:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.780     raeburn  10433: 
                   10434:     my %permissions;
                   10435:     if ($perm{'mgr'}) {
                   10436:         $permissions{'either'} = 'F';
                   10437:         $permissions{'mgr'} = 'F';
                   10438:     }
                   10439:     if ($perm{'vgr'}) {
                   10440:         $permissions{'either'} = 'F';
                   10441:         $permissions{'vgr'} = 'F';
                   10442:     }
                   10443: 
1.598     www      10444:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10445:             items =>[
1.598     www      10446:                         {	linktext => 'Select individual students to grade',
                   10447:                     		url => $url1a,
1.781     raeburn  10448:                     		permission => $permissions{'either'},
1.636     wenzelju 10449:                     		icon => 'grade_students.png',
1.598     www      10450:                     		linktitle => 'Grade current resource for a selection of students.'
                   10451:                         }, 
1.764     raeburn  10452:                         {       linktext => 'Grade ungraded submissions',
1.598     www      10453:                                 url => $url1b,
1.781     raeburn  10454:                                 permission => $permissions{'either'},
1.636     wenzelju 10455:                                 icon => 'ungrade_sub.png',
1.598     www      10456:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 10457:                         },
1.598     www      10458: 
                   10459:                         {       linktext => 'Grading table',
                   10460:                                 url => $url1c,
1.781     raeburn  10461:                                 permission => $permissions{'either'},
1.636     wenzelju 10462:                                 icon => 'grading_table.png',
1.598     www      10463:                                 linktitle => 'Grade current resource for all students.'
                   10464:                         },
1.615     www      10465:                         {       linktext => 'Grade page/folder for one student',
1.598     www      10466:                                 url => $url1d,
1.781     raeburn  10467:                                 permission => $permissions{'either'},
1.636     wenzelju 10468:                                 icon => 'grade_PageFolder.png',
1.598     www      10469:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      10470:                         },
                   10471:                         {       linktext => 'Download submissions',
                   10472:                                 url => $url1e,
1.781     raeburn  10473:                                 permission => $permissions{'either'},
1.636     wenzelju 10474:                                 icon => 'download_sub.png',
1.621     www      10475:                                 linktitle => 'Download all students submissions.'
1.598     www      10476:                         }]},
                   10477:                          { categorytitle=>'Automated Grading',
                   10478:                items =>[
                   10479: 
1.538     schulted 10480:                 	    {	linktext => 'Upload Scores',
                   10481:                     		url => $url2,
1.780     raeburn  10482:                     		permission => $permissions{'mgr'},
1.538     schulted 10483:                     		icon => 'uploadscores.png',
                   10484:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10485:                 	    },
                   10486:                 	    {	linktext => 'Process Clicker',
                   10487:                     		url => $url3,
1.780     raeburn  10488:                     		permission => $permissions{'mgr'},
1.538     schulted 10489:                     		icon => 'addClickerInfoFile.png',
                   10490:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10491:                 	    },
1.587     raeburn  10492:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10493:                     		url => $url4,
1.780     raeburn  10494:                     		permission => $permissions{'mgr'},
1.636     wenzelju 10495:                     		icon => 'bubblesheet.png',
1.648     bisitz   10496:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      10497:                 	    },
1.616     www      10498:                             {   linktext => 'Verify Receipt Number',
1.602     www      10499:                                 url => $url5,
1.780     raeburn  10500:                                 permission => $permissions{'either'},
1.636     wenzelju 10501:                                 icon => 'receipt_number.png',
1.602     www      10502:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10503:                             }
                   10504: 
1.538     schulted 10505:                     ]
                   10506:             });
                   10507: 
1.443     banghart 10508:     # Create the menu
                   10509:     my $Str;
1.445     banghart 10510:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10511:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      10512:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 10513: 
1.602     www      10514:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10515:     return $Str;    
                   10516: }
                   10517: 
1.598     www      10518: sub ungraded {
                   10519:     my ($request)=@_;
                   10520:     &submit_options($request);
                   10521: }
                   10522: 
1.599     www      10523: sub submit_options_sequence {
1.608     www      10524:     my ($request,$symb) = @_;
1.599     www      10525:     if (!$symb) {return '';}
1.600     www      10526:     &commonJSfunctions($request);
                   10527:     my $result;
1.599     www      10528: 
1.600     www      10529:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10530:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      10531:     $result.=&selectfield(0).
1.601     www      10532:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      10533:             <div>
                   10534:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10535:             </div>
                   10536:         </div>
                   10537:   </form>';
                   10538:     return $result;
                   10539: }
                   10540: 
                   10541: sub submit_options_table {
1.608     www      10542:     my ($request,$symb) = @_;
1.600     www      10543:     if (!$symb) {return '';}
1.599     www      10544:     &commonJSfunctions($request);
1.746     raeburn  10545:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      10546:     my $result;
                   10547: 
                   10548:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10549:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      10550: 
1.745     raeburn  10551:     $result.=&selectfield(1,$is_tool).
1.601     www      10552:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      10553:             <div>
                   10554:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10555:             </div>
                   10556:         </div>
                   10557:   </form>';
                   10558:     return $result;
                   10559: }
1.443     banghart 10560: 
1.621     www      10561: sub submit_options_download {
                   10562:     my ($request,$symb) = @_;
                   10563:     if (!$symb) {return '';}
                   10564: 
1.773     raeburn  10565:     my $res_error;
                   10566:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10567:         &response_type($symb,\$res_error);
                   10568:     if ($res_error) {
                   10569:         $request->print(&mt('An error occurred retrieving response types'));
                   10570:         return;
                   10571:     }
                   10572:     unless ($numessay) {
                   10573:         $request->print(&mt('No essayresponse items found'));
                   10574:         return;
                   10575:     }
                   10576:     my $table;
                   10577:     if (ref($partlist) eq 'ARRAY') {
                   10578:         if (scalar(@$partlist) > 1 ) {
                   10579:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   10580:         }
                   10581:     }
                   10582: 
1.746     raeburn  10583:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      10584:     &commonJSfunctions($request);
                   10585: 
                   10586:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  10587:                $table."\n".
                   10588:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      10589:     $result.='
                   10590: <h2>
1.750     raeburn  10591:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  10592: </h2>'.&selectfield(1,$is_tool).'
1.621     www      10593:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   10594:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10595:             </div>
                   10596:           </div>
1.600     www      10597: 
                   10598: 
1.621     www      10599:   </form>';
                   10600:     return $result;
                   10601: }
                   10602: 
1.443     banghart 10603: #--- Displays the submissions first page -------
                   10604: sub submit_options {
1.608     www      10605:     my ($request,$symb) = @_;
1.72      ng       10606:     if (!$symb) {return '';}
                   10607: 
1.746     raeburn  10608:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       10609:     &commonJSfunctions($request);
1.473     albertel 10610:     my $result;
1.533     bisitz   10611: 
1.72      ng       10612:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10613: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  10614:     $result.=&selectfield(1,$is_tool).'
1.601     www      10615:                 <input type="hidden" name="command" value="submission" /> 
                   10616: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10617:             </div>
                   10618:           </div>
                   10619:   </form>';
                   10620:     return $result;
                   10621: }
1.533     bisitz   10622: 
1.601     www      10623: sub selectfield {
1.745     raeburn  10624:    my ($full,$is_tool)=@_;
                   10625:    my %options;
                   10626:    if ($is_tool) {
                   10627:        %options =
                   10628:            (&transtatus_options,
                   10629:             'select_form_order' => ['yes','incorrect','all']);
                   10630:    } else {
                   10631:        %options = 
                   10632:            (&substatus_options,
                   10633:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10634:    }
1.782   ! raeburn  10635: 
        !          10636:   #
        !          10637:   # PrepareClasslist() needs to be called to avoid getting a sections list
        !          10638:   # for a different course from the @Sections global in lonstatistics.pm, 
        !          10639:   # populated by an earlier request.
        !          10640:   #
        !          10641:    &Apache::lonstatistics::PrepareClasslist();
        !          10642: 
1.601     www      10643:    my $result='<div class="LC_columnSection">
1.537     harmsja  10644:   
1.533     bisitz   10645:     <fieldset>
                   10646:       <legend>
                   10647:        '.&mt('Sections').'
                   10648:       </legend>
1.601     www      10649:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10650:     </fieldset>
1.537     harmsja  10651:   
1.533     bisitz   10652:     <fieldset>
                   10653:       <legend>
                   10654:         '.&mt('Groups').'
                   10655:       </legend>
                   10656:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10657:     </fieldset>
1.537     harmsja  10658:   
1.533     bisitz   10659:     <fieldset>
                   10660:       <legend>
                   10661:         '.&mt('Access Status').'
                   10662:       </legend>
1.601     www      10663:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10664:     </fieldset>';
                   10665:     if ($full) {
1.745     raeburn  10666:         my $heading = &mt('Submission Status');
                   10667:         if ($is_tool) {
                   10668:             $heading = &mt('Transaction Status');
                   10669:         }
                   10670:         $result.='
1.533     bisitz   10671:     <fieldset>
                   10672:       <legend>
1.745     raeburn  10673:         '.$heading.'
1.601     www      10674:       </legend>'.
1.635     raeburn  10675:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      10676:    '</fieldset>';
                   10677:     }
                   10678:     $result.='</div><br />';
1.44      ng       10679:     return $result;
1.2       albertel 10680: }
                   10681: 
1.738     raeburn  10682: sub substatus_options {
                   10683:     return &Apache::lonlocal::texthash(
                   10684:                                       'yes'       => 'with submissions',
                   10685:                                       'queued'    => 'in grading queue',
                   10686:                                       'graded'    => 'with ungraded submissions',
                   10687:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10688:                                       'all'       => 'with any status',
                   10689:                                       );
1.738     raeburn  10690: }
                   10691: 
1.745     raeburn  10692: sub transtatus_options {
                   10693:     return &Apache::lonlocal::texthash(
                   10694:                                        'yes'       => 'with score transactions',
                   10695:                                        'incorrect' => 'with less than full credit',
                   10696:                                        'all'       => 'with any status',
                   10697:                                       );
                   10698: }
                   10699: 
1.285     albertel 10700: sub reset_perm {
                   10701:     undef(%perm);
                   10702: }
                   10703: 
                   10704: sub init_perm {
                   10705:     &reset_perm();
1.770     raeburn  10706:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 10707: 
                   10708: 	my $scope = $env{'request.course.id'};
                   10709: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10710: 
                   10711: 	    $scope .= '/'.$env{'request.course.sec'};
                   10712: 	    if ( $perm{$test_perm}=
                   10713: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10714: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10715: 	    } else {
                   10716: 		delete($perm{$test_perm});
                   10717: 	    }
1.285     albertel 10718: 	}
                   10719:     }
                   10720: }
                   10721: 
1.674     raeburn  10722: sub init_old_essays {
                   10723:     my ($symb,$apath,$adom,$aname) = @_;
                   10724:     if ($symb ne '') {
                   10725:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10726:         if (keys(%essays) > 0) {
                   10727:             $old_essays{$symb} = \%essays;
                   10728:         }
                   10729:     }
                   10730:     return;
                   10731: }
                   10732: 
                   10733: sub reset_old_essays {
                   10734:     undef(%old_essays);
                   10735: }
                   10736: 
1.400     www      10737: sub gather_clicker_ids {
1.408     albertel 10738:     my %clicker_ids;
1.400     www      10739: 
                   10740:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10741: 
                   10742:     # Set up a couple variables.
1.407     albertel 10743:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10744:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10745:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10746: 
1.407     albertel 10747:     foreach my $student (keys(%$classlist)) {
1.438     www      10748:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10749:         my $username = $classlist->{$student}->[$username_idx];
                   10750:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10751:         my $clickers =
1.408     albertel 10752: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10753:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10754:             $id=~s/^[\#0]+//;
1.421     www      10755:             $id=~s/[\-\:]//g;
1.407     albertel 10756:             if (exists($clicker_ids{$id})) {
1.408     albertel 10757: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10758:             } else {
1.408     albertel 10759: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10760:             }
                   10761:         }
                   10762:     }
1.407     albertel 10763:     return %clicker_ids;
1.400     www      10764: }
                   10765: 
1.402     www      10766: sub gather_adv_clicker_ids {
1.408     albertel 10767:     my %clicker_ids;
1.402     www      10768:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10769:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10770:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10771:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10772:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10773:             my ($puname,$pudom)=split(/\:/,$person);
                   10774:             my $clickers =
1.408     albertel 10775: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10776:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10777: 		$id=~s/^[\#0]+//;
1.421     www      10778:                 $id=~s/[\-\:]//g;
1.408     albertel 10779: 		if (exists($clicker_ids{$id})) {
                   10780: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10781: 		} else {
                   10782: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10783: 		}
1.405     www      10784:             }
1.402     www      10785:         }
                   10786:     }
1.407     albertel 10787:     return %clicker_ids;
1.402     www      10788: }
                   10789: 
1.413     www      10790: sub clicker_grading_parameters {
                   10791:     return ('gradingmechanism' => 'scalar',
                   10792:             'upfiletype' => 'scalar',
                   10793:             'specificid' => 'scalar',
                   10794:             'pcorrect' => 'scalar',
                   10795:             'pincorrect' => 'scalar');
                   10796: }
                   10797: 
1.400     www      10798: sub process_clicker {
1.608     www      10799:     my ($r,$symb)=@_;
1.400     www      10800:     if (!$symb) {return '';}
                   10801:     my $result=&checkforfile_js();
1.632     www      10802:     $result.=&Apache::loncommon::start_data_table().
                   10803:              &Apache::loncommon::start_data_table_header_row().
                   10804:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10805:              &Apache::loncommon::end_data_table_header_row().
                   10806:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10807: # Attempt to restore parameters from last session, set defaults if not present
                   10808:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10809:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10810:                                                  \%Saveable_Parameters);
                   10811:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10812:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10813:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10814:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10815: 
                   10816:     my %checked;
1.521     www      10817:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10818:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10819:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10820:        }
                   10821:     }
                   10822: 
1.632     www      10823:     my $upload=&mt("Evaluate File");
1.400     www      10824:     my $type=&mt("Type");
1.402     www      10825:     my $attendance=&mt("Award points just for participation");
                   10826:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10827:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10828:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10829:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10830:     my $pcorrect=&mt("Percentage points for correct solution");
                   10831:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10832:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10833: 						   {'iclicker' => 'i>clicker',
1.666     www      10834:                                                     'interwrite' => 'interwrite PRS',
                   10835:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10836:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10837:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10838: function sanitycheck() {
                   10839: // Accept only integer percentages
                   10840:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10841:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10842: // Find out grading choice
                   10843:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10844:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10845:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10846:       }
                   10847:    }
                   10848: // By default, new choice equals user selection
                   10849:    newgradingchoice=gradingchoice;
                   10850: // Not good to give more points for false answers than correct ones
                   10851:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10852:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10853:    }
                   10854: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10855:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10856:       document.forms.gradesupload.pcorrect.value=100;
                   10857:       document.forms.gradesupload.pincorrect.value=100;
                   10858:    }
                   10859: // If the values are different, cannot be attendance only
                   10860:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10861:        (gradingchoice=='attendance')) {
                   10862:        newgradingchoice='personnel';
                   10863:    }
                   10864: // Change grading choice to new one
                   10865:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10866:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10867:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10868:       } else {
                   10869:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10870:       }
                   10871:    }
                   10872: // Remember the old state
                   10873:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10874: }
1.597     wenzelju 10875: ENDUPFORM
                   10876:     $result.= <<ENDUPFORM;
1.400     www      10877: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10878: <input type="hidden" name="symb" value="$symb" />
                   10879: <input type="hidden" name="command" value="processclickerfile" />
                   10880: <input type="file" name="upfile" size="50" />
                   10881: <br /><label>$type: $selectform</label>
1.632     www      10882: ENDUPFORM
                   10883:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10884:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10885:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10886: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10887: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10888: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10889: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10890: <br />&nbsp;&nbsp;&nbsp;
                   10891: <input type="text" name="givenanswer" size="50" />
1.413     www      10892: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10893: ENDGRADINGFORM
1.766     raeburn  10894:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      10895:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10896:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10897: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10898: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  10899: </form>
1.632     www      10900: ENDPERCFORM
                   10901:     $result.='</td>'.
                   10902:              &Apache::loncommon::end_data_table_row().
                   10903:              &Apache::loncommon::end_data_table();
1.400     www      10904:     return $result;
                   10905: }
                   10906: 
                   10907: sub process_clicker_file {
1.766     raeburn  10908:     my ($r,$symb) = @_;
1.400     www      10909:     if (!$symb) {return '';}
1.413     www      10910: 
                   10911:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10912:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10913:                                               \%Saveable_Parameters);
1.598     www      10914:     my $result='';
1.404     www      10915:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10916: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10917: 	return $result;
1.404     www      10918:     }
1.522     www      10919:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10920:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10921:         return $result;
1.521     www      10922:     }
1.522     www      10923:     my $foundgiven=0;
1.521     www      10924:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10925:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10926:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10927:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10928:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10929:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10930:         $foundgiven=$#answers+1;
1.521     www      10931:     }
1.407     albertel 10932:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10933:     my %correct_ids;
1.404     www      10934:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10935: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10936:     }
                   10937:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10938: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10939: 	   $correct_id=~tr/a-z/A-Z/;
                   10940: 	   $correct_id=~s/\s//gs;
                   10941: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10942:            $correct_id=~s/[\-\:]//g;
1.414     www      10943:            if ($correct_id) {
                   10944: 	      $correct_ids{$correct_id}='specified';
                   10945:            }
                   10946:         }
1.400     www      10947:     }
1.404     www      10948:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10949: 	$result.=&mt('Score based on attendance only');
1.521     www      10950:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10951:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10952:     } else {
1.408     albertel 10953: 	my $number=0;
1.411     www      10954: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10955: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10956: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10957: 	    if ($correct_ids{$id} eq 'specified') {
                   10958: 		$result.=&mt('specified');
                   10959: 	    } else {
                   10960: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10961: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10962: 	    }
                   10963: 	    $number++;
                   10964: 	}
1.411     www      10965:         $result.="</p>\n";
1.710     bisitz   10966:         if ($number==0) {
                   10967:             $result .=
                   10968:                  &Apache::lonhtmlcommon::confirm_success(
                   10969:                      &mt('No IDs found to determine correct answer'),1);
                   10970:             return $result;
                   10971:         }
1.404     www      10972:     }
1.405     www      10973:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10974:         $result .=
                   10975:             &Apache::lonhtmlcommon::confirm_success(
                   10976:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10977:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10978:         return $result;
1.405     www      10979:     }
1.760     raeburn  10980:     my $mimetype;
                   10981:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10982:         my $mm = new File::MMagic;
                   10983:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10984:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10985:             $result.= '<p>'.
                   10986:                 &Apache::lonhtmlcommon::confirm_success(
                   10987:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   10988:             return $result;
                   10989:         }
                   10990:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10991:         $result .= '<p>'.
                   10992:             &Apache::lonhtmlcommon::confirm_success(
                   10993:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   10994:         return $result;
                   10995:     }
1.410     www      10996: 
                   10997: # Were able to get all the info needed, now analyze the file
                   10998: 
1.411     www      10999:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 11000:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      11001:     $result.=&Apache::loncommon::start_data_table().
                   11002:              &Apache::loncommon::start_data_table_header_row().
                   11003:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   11004:              &Apache::loncommon::end_data_table_header_row().
                   11005:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   11006: <td>
1.410     www      11007: <form method="post" action="/adm/grades" name="clickeranalysis">
                   11008: <input type="hidden" name="symb" value="$symb" />
                   11009: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      11010: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   11011: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   11012: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      11013: ENDHEADER
1.522     www      11014:     if ($env{'form.gradingmechanism'} eq 'given') {
                   11015:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   11016:     } 
1.408     albertel 11017:     my %responses;
                   11018:     my @questiontitles;
1.405     www      11019:     my $errormsg='';
                   11020:     my $number=0;
                   11021:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  11022:         if ($mimetype eq 'text/plain') {
                   11023:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   11024:         } elsif ($mimetype eq 'text/html') {
                   11025:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   11026:         }
                   11027:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      11028:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  11029:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      11030:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   11031:     }
1.411     www      11032:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   11033:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   11034:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   11035:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   11036:              '<br />';
1.522     www      11037:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   11038:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      11039:        return $result;
1.522     www      11040:     } 
1.414     www      11041: # Remember Question Titles
                   11042: # FIXME: Possibly need delimiter other than ":"
                   11043:     for (my $i=0;$i<$number;$i++) {
                   11044:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   11045:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   11046:     }
1.411     www      11047:     my $correct_count=0;
                   11048:     my $student_count=0;
                   11049:     my $unknown_count=0;
1.414     www      11050: # Match answers with usernames
                   11051: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 11052:     foreach my $id (keys(%responses)) {
1.410     www      11053:        if ($correct_ids{$id}) {
1.414     www      11054:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      11055:           $correct_count++;
1.410     www      11056:        } elsif ($clicker_ids{$id}) {
1.437     www      11057:           if ($clicker_ids{$id}=~/\,/) {
                   11058: # More than one user with the same clicker!
1.632     www      11059:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11060:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11061:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      11062:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11063:                            "<select name='multi".$id."'>";
                   11064:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   11065:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   11066:              }
                   11067:              $result.='</select>';
                   11068:              $unknown_count++;
                   11069:           } else {
                   11070: # Good: found one and only one user with the right clicker
                   11071:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   11072:              $student_count++;
                   11073:           }
1.410     www      11074:        } else {
1.632     www      11075:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11076:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11077:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      11078:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11079:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   11080:                    "\n".&mt("Domain").": ".
                   11081:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  11082:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      11083:           $unknown_count++;
1.410     www      11084:        }
1.405     www      11085:     }
1.412     www      11086:     $result.='<hr />'.
                   11087:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      11088:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      11089:        if ($correct_count==0) {
1.696     bisitz   11090:           $errormsg.="Found no correct answers for grading!";
1.412     www      11091:        } elsif ($correct_count>1) {
1.414     www      11092:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      11093:        }
                   11094:     }
1.428     www      11095:     if ($number<1) {
                   11096:        $errormsg.="Found no questions.";
                   11097:     }
1.412     www      11098:     if ($errormsg) {
                   11099:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   11100:     } else {
                   11101:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   11102:     }
1.632     www      11103:     $result.='</form></td>'.
                   11104:              &Apache::loncommon::end_data_table_row().
                   11105:              &Apache::loncommon::end_data_table();
1.614     www      11106:     return $result;
1.400     www      11107: }
                   11108: 
1.405     www      11109: sub iclicker_eval {
1.406     www      11110:     my ($questiontitles,$responses)=@_;
1.405     www      11111:     my $number=0;
                   11112:     my $errormsg='';
                   11113:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      11114:         my %components=&Apache::loncommon::record_sep($line);
                   11115:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 11116: 	if ($entries[0] eq 'Question') {
                   11117: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   11118: 		$$questiontitles[$number]=$entries[$i];
                   11119: 		$number++;
                   11120: 	    }
                   11121: 	}
                   11122: 	if ($entries[0]=~/^\#/) {
                   11123: 	    my $id=$entries[0];
                   11124: 	    my @idresponses;
                   11125: 	    $id=~s/^[\#0]+//;
                   11126: 	    for (my $i=0;$i<$number;$i++) {
                   11127: 		my $idx=3+$i*6;
1.644     www      11128:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 11129: 		push(@idresponses,$entries[$idx]);
                   11130: 	    }
                   11131: 	    $$responses{$id}=join(',',@idresponses);
                   11132: 	}
1.405     www      11133:     }
                   11134:     return ($errormsg,$number);
                   11135: }
                   11136: 
1.760     raeburn  11137: sub iclickerxml_eval {
                   11138:     my ($questiontitles,$responses)=@_;
                   11139:     my $number=0;
                   11140:     my $errormsg='';
                   11141:     my @state;
                   11142:     my %respbyid;
                   11143:     my $p = HTML::Parser->new
                   11144:     (
                   11145:         xml_mode => 1,
                   11146:         start_h =>
                   11147:             [sub {
                   11148:                  my ($tagname,$attr) = @_;
                   11149:                  push(@state,$tagname);
                   11150:                  if ("@state" eq "ssn p") {
                   11151:                      my $title = $attr->{qn};
                   11152:                      $title =~ s/(^\s+|\s+$)//g;
                   11153:                      $questiontitles->[$number]=$title;
                   11154:                  } elsif ("@state" eq "ssn p v") {
                   11155:                      my $id = $attr->{id};
                   11156:                      my $entry = $attr->{ans};
                   11157:                      $id=~s/^[\#0]+//;
                   11158:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   11159:                      $respbyid{$id}[$number] = $entry;
                   11160:                  }
                   11161:             }, "tagname, attr"],
                   11162:          end_h =>
                   11163:                [sub {
                   11164:                    my ($tagname) = @_;
                   11165:                    if ("@state" eq "ssn p") {
                   11166:                        $number++;
                   11167:                    }
                   11168:                    pop(@state);
                   11169:                 }, "tagname"],
                   11170:     );
                   11171: 
                   11172:     $p->parse($env{'form.upfile'});
                   11173:     $p->eof;
                   11174:     foreach my $id (keys(%respbyid)) {
                   11175:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   11176:     }
                   11177:     return ($errormsg,$number);
                   11178: }
                   11179: 
1.419     www      11180: sub interwrite_eval {
                   11181:     my ($questiontitles,$responses)=@_;
                   11182:     my $number=0;
                   11183:     my $errormsg='';
1.420     www      11184:     my $skipline=1;
                   11185:     my $questionnumber=0;
                   11186:     my %idresponses=();
1.419     www      11187:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11188:         my %components=&Apache::loncommon::record_sep($line);
                   11189:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      11190:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   11191:         if ($entries[1] eq 'Response') { $skipline=1; }
                   11192:         next if $skipline;
                   11193:         if ($entries[0]!=$questionnumber) {
                   11194:            $questionnumber=$entries[0];
                   11195:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   11196:            $number++;
1.419     www      11197:         }
1.420     www      11198:         my $id=$entries[4];
                   11199:         $id=~s/^[\#0]+//;
1.421     www      11200:         $id=~s/^v\d*\://i;
                   11201:         $id=~s/[\-\:]//g;
1.420     www      11202:         $idresponses{$id}[$number]=$entries[6];
                   11203:     }
1.524     raeburn  11204:     foreach my $id (keys(%idresponses)) {
1.420     www      11205:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   11206:        $$responses{$id}=~s/^\s*\,//;
1.419     www      11207:     }
                   11208:     return ($errormsg,$number);
                   11209: }
                   11210: 
1.666     www      11211: sub turning_eval {
                   11212:     my ($questiontitles,$responses)=@_;
                   11213:     my $number=0;
                   11214:     my $errormsg='';
                   11215:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11216:         my %components=&Apache::loncommon::record_sep($line);
                   11217:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   11218:         if ($#entries>$number) { $number=$#entries; }
                   11219:         my $id=$entries[0];
                   11220:         my @idresponses;
                   11221:         $id=~s/^[\#0]+//;
                   11222:         unless ($id) { next; }
                   11223:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   11224:             $entries[$idx]=~s/\,/\;/g;
                   11225:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   11226:             push(@idresponses,$entries[$idx]);
                   11227:         }
                   11228:         $$responses{$id}=join(',',@idresponses);
                   11229:     }
                   11230:     for (my $i=1; $i<=$number; $i++) {
                   11231:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   11232:     }
                   11233:     return ($errormsg,$number);
                   11234: }
                   11235: 
                   11236: 
1.414     www      11237: sub assign_clicker_grades {
1.766     raeburn  11238:     my ($r,$symb) = @_;
1.414     www      11239:     if (!$symb) {return '';}
1.416     www      11240: # See which part we are saving to
1.582     raeburn  11241:     my $res_error;
                   11242:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   11243:     if ($res_error) {
                   11244:         return &navmap_errormsg();
                   11245:     }
1.416     www      11246: # FIXME: This should probably look for the first handgradeable part
                   11247:     my $part=$$partlist[0];
                   11248: # Start screen output
1.766     raeburn  11249:     my $result = &Apache::loncommon::start_data_table().
                   11250:                  &Apache::loncommon::start_data_table_header_row().
                   11251:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   11252:                  &Apache::loncommon::end_data_table_header_row().
                   11253:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11254: # Get correct result
                   11255: # FIXME: Possibly need delimiter other than ":"
                   11256:     my @correct=();
1.415     www      11257:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11258:     my $number=$env{'form.number'};
                   11259:     if ($gradingmechanism ne 'attendance') {
1.414     www      11260:        foreach my $key (keys(%env)) {
                   11261:           if ($key=~/^form\.correct\:/) {
                   11262:              my @input=split(/\,/,$env{$key});
                   11263:              for (my $i=0;$i<=$#input;$i++) {
                   11264:                  if (($correct[$i]) && ($input[$i]) &&
                   11265:                      ($correct[$i] ne $input[$i])) {
                   11266:                     $result.='<br /><span class="LC_warning">'.
                   11267:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11268:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      11269:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11270:                     $correct[$i]=$input[$i];
                   11271:                  }
                   11272:              }
                   11273:           }
                   11274:        }
1.415     www      11275:        for (my $i=0;$i<$number;$i++) {
1.644     www      11276:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11277:              $result.='<br /><span class="LC_error">'.
                   11278:                       &mt('No correct result given for question "[_1]"!',
                   11279:                           $env{'form.question:'.$i}).'</span>';
                   11280:           }
                   11281:        }
1.644     www      11282:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11283:     }
                   11284: # Start grading
1.415     www      11285:     my $pcorrect=$env{'form.pcorrect'};
                   11286:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11287:     my $storecount=0;
1.632     www      11288:     my %users=();
1.415     www      11289:     foreach my $key (keys(%env)) {
1.420     www      11290:        my $user='';
1.415     www      11291:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11292:           $user=$1;
                   11293:        }
                   11294:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11295:           my $id=$1;
                   11296:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11297:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11298:           } elsif ($env{'form.multi'.$id}) {
                   11299:              $user=$env{'form.multi'.$id};
1.420     www      11300:           }
                   11301:        }
1.632     www      11302:        if ($user) {
                   11303:           if ($users{$user}) {
                   11304:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   11305:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      11306:                       '</span><br />';
                   11307:           }
                   11308:           $users{$user}=1; 
1.415     www      11309:           my @answer=split(/\,/,$env{$key});
                   11310:           my $sum=0;
1.522     www      11311:           my $realnumber=$number;
1.415     www      11312:           for (my $i=0;$i<$number;$i++) {
1.576     www      11313:              if  ($correct[$i] eq '-') {
                   11314:                 $realnumber--;
1.766     raeburn  11315:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11316:                 if ($gradingmechanism eq 'attendance') {
                   11317:                    $sum+=$pcorrect;
1.576     www      11318:                 } elsif ($correct[$i] eq '*') {
1.522     www      11319:                    $sum+=$pcorrect;
1.415     www      11320:                 } else {
1.644     www      11321: # We actually grade if correct or not
                   11322:                    my $increment=$pincorrect;
                   11323: # Special case: numerical answer "0"
                   11324:                    if ($correct[$i] eq '0') {
                   11325:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11326:                          $increment=$pcorrect;
                   11327:                       }
                   11328: # General numerical answer, both evaluate to something non-zero
                   11329:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11330:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11331:                          $increment=$pcorrect;
                   11332:                       }
                   11333: # Must be just alphanumeric
                   11334:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11335:                       $increment=$pcorrect;
1.415     www      11336:                    }
1.644     www      11337:                    $sum+=$increment;
1.415     www      11338:                 }
                   11339:              }
                   11340:           }
1.522     www      11341:           my $ave=$sum/(100*$realnumber);
1.416     www      11342: # Store
                   11343:           my ($username,$domain)=split(/\:/,$user);
                   11344:           my %grades=();
                   11345:           $grades{"resource.$part.solved"}='correct_by_override';
                   11346:           $grades{"resource.$part.awarded"}=$ave;
                   11347:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11348:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11349:                                                  $env{'request.course.id'},
                   11350:                                                  $domain,$username);
                   11351:           if ($returncode ne 'ok') {
                   11352:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11353:           } else {
                   11354:              $storecount++;
                   11355:           }
1.415     www      11356:        }
                   11357:     }
                   11358: # We are done
1.549     hauer    11359:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      11360:              '</td>'.
                   11361:              &Apache::loncommon::end_data_table_row().
                   11362:              &Apache::loncommon::end_data_table();
1.614     www      11363:     return $result;
1.414     www      11364: }
                   11365: 
1.582     raeburn  11366: sub navmap_errormsg {
                   11367:     return '<div class="LC_error">'.
                   11368:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11369:            &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  11370:            '</div>';
                   11371: }
1.607     droeschl 11372: 
1.609     www      11373: sub startpage {
1.777     raeburn  11374:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
1.754     raeburn  11375:     my %args;
                   11376:     if ($onload) {
                   11377:          my %loaditems = (
                   11378:                         'onload' => $onload,
                   11379:                       );
                   11380:          $args{'add_entries'} = \%loaditems;
                   11381:     }
1.671     raeburn  11382:     if ($nomenu) {
1.754     raeburn  11383:         $args{'only_body'} = 1; 
1.777     raeburn  11384:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
1.671     raeburn  11385:     } else {
                   11386:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.754     raeburn  11387:         $args{'bread_crumbs'} = $crumbs;
1.777     raeburn  11388:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
1.765     raeburn  11389:         if ($env{'request.course.id'}) {
                   11390:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   11391:         }
1.671     raeburn  11392:     }
1.613     www      11393:     unless ($nodisplayflag) {
1.773     raeburn  11394:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      11395:     }
1.607     droeschl 11396: }
1.582     raeburn  11397: 
1.622     www      11398: sub select_problem {
                   11399:     my ($r)=@_;
1.632     www      11400:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  11401:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      11402:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11403:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11404: }
                   11405: 
1.1       albertel 11406: sub handler {
1.41      ng       11407:     my $request=$_[0];
1.434     albertel 11408:     &reset_caches();
1.646     raeburn  11409:     if ($request->header_only) {
                   11410:         &Apache::loncommon::content_type($request,'text/html');
                   11411:         $request->send_http_header;
                   11412:         return OK;
                   11413:     }
                   11414:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   11415: 
1.664     raeburn  11416: # see what command we need to execute
                   11417: 
                   11418:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11419:     my $command=$commands[0];
                   11420: 
1.646     raeburn  11421:     &init_perm();
                   11422:     if (!$env{'request.course.id'}) {
1.664     raeburn  11423:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11424:                 ($command =~ /^scantronupload/)) {
                   11425:             # Not in a course.
                   11426:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11427:             return HTTP_NOT_ACCEPTABLE;
                   11428:         }
1.646     raeburn  11429:     } elsif (!%perm) {
                   11430:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  11431:         return OK;
1.41      ng       11432:     }
1.646     raeburn  11433:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       11434:     $request->send_http_header;
1.646     raeburn  11435: 
1.160     albertel 11436:     if ($#commands > 0) {
                   11437: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11438:     }
1.608     www      11439: 
                   11440: # see what the symb is
                   11441: 
                   11442:     my $symb=$env{'form.symb'};
                   11443:     unless ($symb) {
                   11444:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11445:        $symb=&Apache::lonnet::symbread($url);
                   11446:     }
1.646     raeburn  11447:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      11448: 
1.513     foxr     11449:     $ssi_error = 0;
1.637     www      11450:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      11451: #
1.637     www      11452: # Not called from a resource, but inside a course
1.601     www      11453: #    
1.622     www      11454:         &startpage($request,undef,[],1,1);
                   11455:         &select_problem($request);
1.41      ng       11456:     } else {
1.104     albertel 11457: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  11458:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  11459:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11460:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11461:                     &choose_task_version_form($symb,$env{'form.student'},
                   11462:                                               $env{'form.userdom'});
                   11463:             }
1.773     raeburn  11464:             my $divforres;
                   11465:             if ($env{'form.student'} eq '') {
                   11466:                 $js .= &part_selector_js();
                   11467:                 $onload = "toggleParts('gradesub');";
                   11468:             } else {
                   11469:                 $divforres = 1;
                   11470:             }
1.778     raeburn  11471:             my $head_extra = $js;
                   11472:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11473:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11474:                 if ($csslinks) {
                   11475:                     $head_extra .= "\n$csslinks";
                   11476:                 }
                   11477:             }
1.777     raeburn  11478:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   11479:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
1.671     raeburn  11480:             if ($versionform) {
1.775     raeburn  11481:                 if ($divforres) {
                   11482:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   11483:                 }
1.671     raeburn  11484:                 $request->print($versionform);
                   11485:             }
1.773     raeburn  11486: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  11487:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11488:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11489:                 &choose_task_version_form($symb,$env{'form.student'},
                   11490:                                           $env{'form.userdom'},
                   11491:                                           $env{'form.inhibitmenu'});
1.778     raeburn  11492:             my $head_extra = $js;
                   11493:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11494:                 my $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11495:                 if ($csslinks) {
                   11496:                     $head_extra .= "\n$csslinks";
                   11497:                 }
                   11498:             }
1.777     raeburn  11499:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   11500:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
1.671     raeburn  11501:             if ($versionform) {
                   11502:                 $request->print($versionform);
                   11503:             }
                   11504:             $request->print('<br clear="all" />');
                   11505:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 11506: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      11507:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11508:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      11509: 	    &pickStudentPage($request,$symb);
1.103     albertel 11510: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.778     raeburn  11511:             my $csslinks;
                   11512:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11513:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
1.778     raeburn  11514:             }
1.615     www      11515:             &startpage($request,$symb,
                   11516:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11517:                                        {href=>'',text=>'Select student'},
1.777     raeburn  11518:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
1.608     www      11519: 	    &displayPage($request,$symb);
1.104     albertel 11520: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      11521:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11522:                                        {href=>'',text=>'Select student'},
                   11523:                                        {href=>'',text=>'Grade student'},
                   11524:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      11525: 	    &updateGradeByPage($request,$symb);
1.104     albertel 11526: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.778     raeburn  11527:             my $csslinks;
                   11528:             unless ($env{'form.vProb'} eq 'no') {
1.779     raeburn  11529:                 $csslinks = &Apache::loncommon::css_links($symb);
1.778     raeburn  11530:             }
1.619     www      11531:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.777     raeburn  11532:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
1.608     www      11533: 	    &processGroup($request,$symb);
1.104     albertel 11534: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      11535:             &startpage($request,$symb);
                   11536: 	    $request->print(&grading_menu($request,$symb));
1.598     www      11537: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      11538:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      11539: 	    $request->print(&submit_options($request,$symb));
1.598     www      11540:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  11541:             my $js = &part_selector_js();
                   11542:             my $onload = "toggleParts('gradesub');";
                   11543:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11544:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      11545:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      11546:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      11547:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      11548:             $request->print(&submit_options_table($request,$symb));
1.598     www      11549:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      11550:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      11551:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 11552: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      11553:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      11554: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 11555: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      11556:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11557:                                        {href=>'',text=>'Store grades'}]);
1.608     www      11558: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 11559: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      11560:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11561:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11562:                                                                              text=>"Modify grades"},
                   11563:                                        {href=>'', text=>"Store grades"}]);
1.608     www      11564: 	    $request->print(&editgrades($request,$symb));
1.602     www      11565:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      11566:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      11567:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 11568: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      11569:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11570:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      11571: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      11572:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      11573:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      11574:             $request->print(&process_clicker($request,$symb));
1.400     www      11575:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      11576:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11577:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      11578:             $request->print(&process_clicker_file($request,$symb));
1.414     www      11579:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      11580:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11581:                                        {href=>'', text=>'Process clicker file'},
                   11582:                                        {href=>'', text=>'Store grades'}]);
1.608     www      11583:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 11584: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      11585:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11586: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 11587: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      11588:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11589: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 11590: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      11591:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11592: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 11593: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 11594: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      11595:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11596: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       11597: 	    } else {
1.257     albertel 11598: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11599: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       11600: 		} else {
1.257     albertel 11601: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       11602: 		}
1.627     www      11603:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11604: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       11605: 	    }
1.246     albertel 11606: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      11607:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11608: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 11609: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  11610:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11611:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      11612: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 11613:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      11614:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11615:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 11616: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      11617:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11618: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 11619: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      11620:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11621: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 11622:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  11623:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  11624:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11625:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      11626:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 11627:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  11628:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      11629:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11630:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  11631:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      11632:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11633:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  11634:         } elsif ($command eq 'scantronupload_delete' &&
                   11635:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   11636:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11637:             &scantron_upload_delete($request,$symb);
1.523     raeburn  11638:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      11639:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      11640:             $request->print(&checkscantron_results($request,$symb));
                   11641:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  11642:             my $js = &part_selector_js();
                   11643:             my $onload = "toggleParts('gradingMenu');";
                   11644:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11645:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      11646:             $request->print(&submit_options_download($request,$symb));
                   11647:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11648:             &startpage($request,$symb,
                   11649:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  11650:     {href=>'', text=>'Download submitted files'}],
                   11651:                undef,undef,undef,undef,undef,undef,undef,1);
1.775     raeburn  11652:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
1.621     www      11653:             &submit_download_link($request,$symb);
1.106     albertel 11654: 	} elsif ($command) {
1.620     www      11655:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   11656: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 11657: 	}
1.2       albertel 11658:     }
1.513     foxr     11659:     if ($ssi_error) {
                   11660: 	&ssi_print_error($request);
                   11661:     }
1.671     raeburn  11662:     if ($env{'form.inhibitmenu'}) {
                   11663:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  11664:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  11665:         &Apache::lonquickgrades::endGradeScreen($request);
                   11666:     }
1.434     albertel 11667:     &reset_caches();
1.646     raeburn  11668:     return OK;
1.44      ng       11669: }
                   11670: 
1.1       albertel 11671: 1;
                   11672: 
1.13      albertel 11673: __END__;
1.531     jms      11674: 
                   11675: 
                   11676: =head1 NAME
                   11677: 
                   11678: Apache::grades
                   11679: 
                   11680: =head1 SYNOPSIS
                   11681: 
                   11682: Handles the viewing of grades.
                   11683: 
                   11684: This is part of the LearningOnline Network with CAPA project
                   11685: described at http://www.lon-capa.org.
                   11686: 
                   11687: =head1 OVERVIEW
                   11688: 
                   11689: Do an ssi with retries:
1.715     bisitz   11690: While I'd love to factor out this with the version in lonprintout,
1.531     jms      11691: 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
                   11692: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11693: 
                   11694: At least the logic that drives this has been pulled out into loncommon.
                   11695: 
                   11696: 
                   11697: 
                   11698: ssi_with_retries - Does the server side include of a resource.
                   11699:                      if the ssi call returns an error we'll retry it up to
                   11700:                      the number of times requested by the caller.
1.715     bisitz   11701:                      If we still have a problem, no text is appended to the
1.531     jms      11702:                      output and we set some global variables.
                   11703:                      to indicate to the caller an SSI error occurred.  
                   11704:                      All of this is supposed to deal with the issues described
1.715     bisitz   11705:                      in LON-CAPA BZ 5631 see:
1.531     jms      11706:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11707:                      by informing the user that this happened.
                   11708: 
                   11709: Parameters:
                   11710:   resource   - The resource to include.  This is passed directly, without
                   11711:                interpretation to lonnet::ssi.
                   11712:   form       - The form hash parameters that guide the interpretation of the resource
                   11713:                
                   11714:   retries    - Number of retries allowed before giving up completely.
                   11715: Returns:
                   11716:   On success, returns the rendered resource identified by the resource parameter.
                   11717: Side Effects:
                   11718:   The following global variables can be set:
                   11719:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11720:                               It is up to the caller to initialize this to false
                   11721:                               if desired.
                   11722:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11723:                               of the resource that could not be rendered by the ssi
                   11724:                               call.
                   11725:    ssi_error_message   - The error string fetched from the ssi response
                   11726:                               in the event of an error.
                   11727: 
                   11728: 
                   11729: =head1 HANDLER SUBROUTINE
                   11730: 
                   11731: ssi_with_retries()
                   11732: 
                   11733: =head1 SUBROUTINES
                   11734: 
                   11735: =over
                   11736: 
1.671     raeburn  11737: =head1 Routines to display previous version of a Task for a specific student
                   11738: 
                   11739: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   11740: can receive another opportunity. Access to tasks is slot-based. If a slot
                   11741: requires a proctor to check-in the student, a new version of the Task will
                   11742: be created when the student is checked in to the new opportunity.
                   11743: 
                   11744: If a particular student has tried two or more versions of a particular task,
                   11745: the submission screen provides a user with vgr privileges (e.g., a Course
                   11746: Coordinator) the ability to display a previous version worked on by the
                   11747: student.  By default, the current version is displayed. If a previous version
                   11748: has been selected for display, submission data are only shown that pertain
                   11749: to that particular version, and the interface to submit grades is not shown.
                   11750: 
                   11751: =over 4
                   11752: 
                   11753: =item show_previous_task_version()
                   11754: 
                   11755: Displays a specified version of a student's Task, as the student sees it.
                   11756: 
                   11757: Inputs: 2
                   11758:         request - request object
                   11759:         symb    - unique symb for current instance of resource
                   11760: 
                   11761: Output: None.
                   11762: 
                   11763: Side Effects: calls &show_problem() to print version of Task, with
                   11764:               version contained in form item: $env{'form.previousversion'}
                   11765: 
                   11766: =item choose_task_version_form()
                   11767: 
                   11768: Displays a web form used to select which version of a student's view of a
                   11769: Task should be displayed.  Either launches a pop-up window, or replaces
                   11770: content in existing pop-up, or replaces page in main window.
                   11771: 
                   11772: Inputs: 4
                   11773:         symb    - unique symb for current instance of resource
                   11774:         uname   - username of student
                   11775:         udom    - domain of student
                   11776:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11777:                   breadcrumbs etc., are displayed
                   11778: 
                   11779: Output: 4
                   11780:         current   - student's current version
                   11781:         displayed - student's version being displayed
                   11782:         result    - scalar containing HTML for web form used to switch to
                   11783:                     a different version (or a link to close window, if pop-up).
                   11784:         js        - javascript for processing selection in versions web form
                   11785: 
                   11786: Side Effects: None.
                   11787: 
                   11788: =item previous_display_javascript()
                   11789: 
                   11790: Inputs: 2
                   11791:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11792:                   breadcrumbs etc., are displayed.
                   11793:         current - student's current version number.
                   11794: 
                   11795: Output: 1
                   11796:         js      - javascript for processing selection in versions web form.
                   11797: 
                   11798: Side Effects: None.
                   11799: 
                   11800: =back
                   11801: 
                   11802: =head1 Routines to process bubblesheet data.
                   11803: 
                   11804: =over 4
                   11805: 
1.531     jms      11806: =item scantron_get_correction() : 
                   11807: 
                   11808:    Builds the interface screen to interact with the operator to fix a
                   11809:    specific error condition in a specific scanline
                   11810: 
                   11811:  Arguments:
                   11812:     $r           - Apache request object
                   11813:     $i           - number of the current scanline
                   11814:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  11815:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11816:     $line        - full contents of the current scanline
                   11817:     $error       - error condition, valid values are
                   11818:                    'incorrectCODE', 'duplicateCODE',
                   11819:                    'doublebubble', 'missingbubble',
                   11820:                    'duplicateID', 'incorrectID'
                   11821:     $arg         - extra information needed
                   11822:        For errors:
                   11823:          - duplicateID   - paper number that this studentID was seen before on
                   11824:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11825:                            seen on before
                   11826:          - incorrectCODE - current incorrect CODE 
                   11827:          - doublebubble  - array ref of the bubble lines that have double
                   11828:                            bubble errors
                   11829:          - missingbubble - array ref of the bubble lines that have missing
                   11830:                            bubble errors
                   11831: 
1.691     raeburn  11832:    $randomorder - True if exam folder has randomorder set
                   11833:    $randompick  - True if exam folder has randompick set
                   11834:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11835:                      for current line to question number used for same question
                   11836:                      in "Master Seqence" (as seen by Course Coordinator).
                   11837:    $startline   - Reference to hash where key is question number (0 is first)
                   11838:                   and value is number of first bubble line for current student
                   11839:                   or code-based randompick and/or randomorder.
                   11840: 
                   11841: 
                   11842: 
1.531     jms      11843: =item  scantron_get_maxbubble() : 
                   11844: 
1.582     raeburn  11845:    Arguments:
                   11846:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11847:                       failure to retrieve a navmap object.
                   11848:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11849:        calling routine should trap the error condition and display the warning
                   11850:        found in &navmap_errormsg().
                   11851: 
1.649     raeburn  11852:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11853: 
1.531     jms      11854:    Returns the maximum number of bubble lines that are expected to
                   11855:    occur. Does this by walking the selected sequence rendering the
                   11856:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11857:    for what the current value of the problem counter is.
                   11858: 
                   11859:    Caches the results to $env{'form.scantron_maxbubble'},
                   11860:    $env{'form.scantron.bubble_lines.n'}, 
                   11861:    $env{'form.scantron.first_bubble_line.n'} and
                   11862:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11863:    which are the total number of bubble lines, the number of bubble
1.531     jms      11864:    lines for response n and number of the first bubble line for response n,
                   11865:    and a comma separated list of numbers of bubble lines for sub-questions
                   11866:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11867: 
                   11868: 
                   11869: =item  scantron_validate_missingbubbles() : 
                   11870: 
                   11871:    Validates all scanlines in the selected file to not have any
                   11872:     answers that don't have bubbles that have not been verified
                   11873:     to be bubble free.
                   11874: 
                   11875: =item  scantron_process_students() : 
                   11876: 
1.659     raeburn  11877:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11878: 
                   11879:    The parsed scanline hash is added to %env 
                   11880: 
                   11881:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11882:    foreach resource , with the form data of
                   11883: 
                   11884: 	'submitted'     =>'scantron' 
                   11885: 	'grade_target'  =>'grade',
                   11886: 	'grade_username'=> username of student
                   11887: 	'grade_domain'  => domain of student
                   11888: 	'grade_courseid'=> of course
                   11889: 	'grade_symb'    => symb of resource to grade
                   11890: 
                   11891:     This triggers a grading pass. The problem grading code takes care
                   11892:     of converting the bubbled letter information (now in %env) into a
                   11893:     valid submission.
                   11894: 
                   11895: =item  scantron_upload_scantron_data() :
                   11896: 
1.659     raeburn  11897:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11898: 
                   11899: =item  scantron_upload_scantron_data_save() : 
                   11900: 
                   11901:    Adds a provided bubble information data file to the course if user
1.770     raeburn  11902:    has the correct privileges to do so.
                   11903: 
                   11904: = item scantron_upload_delete() :
                   11905: 
                   11906:    Deletes a previously uploaded bubble information data file, if user
                   11907:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      11908: 
                   11909: =item  valid_file() :
                   11910: 
                   11911:    Validates that the requested bubble data file exists in the course.
                   11912: 
                   11913: =item  scantron_download_scantron_data() : 
                   11914: 
                   11915:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11916:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11917:    course.
                   11918: 
                   11919: =item  scantron_validate_ID() : 
                   11920: 
                   11921:    Validates all scanlines in the selected file to not have any
1.556     weissno  11922:    invalid or underspecified student/employee IDs
1.531     jms      11923: 
1.582     raeburn  11924: =item navmap_errormsg() :
                   11925: 
                   11926:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11927:    Should be called whenever the request to instantiate a navmap object fails.
                   11928: 
                   11929: =back
1.582     raeburn  11930: 
1.531     jms      11931: =back
                   11932: 
                   11933: =cut

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